forked from stjeong/XmlCodeGenerator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXmlCodeGenerator.cs
More file actions
357 lines (299 loc) · 12.7 KB
/
XmlCodeGenerator.cs
File metadata and controls
357 lines (299 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml.Xsl;
using System.Diagnostics;
using System.Collections;
using Microsoft.Win32;
using System.Globalization;
using System.Reflection;
using System.Runtime.Remoting;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using Microsoft.VisualStudio.TextTemplating.VSHost;
using Microsoft.VisualStudio.Shell;
using VSLangProj80;
using System.CodeDom.Compiler;
using Microsoft.VisualStudio.Shell.Interop;
namespace BclExtension
{
/// <summary>
/// This class exists to be cocreated a in a preprocessor build step.
/// </summary>
[Guid(XmlCodeGenerator.RefGuid)]
[ClassInterface(ClassInterfaceType.None)]
[CodeGeneratorRegistration(typeof(XmlCodeGenerator), "C# XML Code Generator", vsContextGuids.vsContextGuidVCSProject, GeneratesDesignTimeSource = true)]
[CodeGeneratorRegistration(typeof(XmlCodeGenerator), "VB XML Code Generator", vsContextGuids.vsContextGuidVBProject, GeneratesDesignTimeSource = true)]
[ProvideObject(typeof(XmlCodeGenerator))]
public class XmlCodeGenerator : BaseCodeGeneratorWithSite
{
internal const string RefGuid = "64B3B9EF-EEF7-4523-82FD-7D68459D7DFA";
internal const string DefaultXslFileName = "default.xslt";
internal string BaseFolder
{
get
{
string modulePath = typeof(XmlCodeGenerator).Assembly.Location;
return Path.GetDirectoryName(modulePath);
}
}
/// <summary>
/// 기본 생성자
/// </summary>
public XmlCodeGenerator()
{
}
static Dictionary<string, XslCompiledTransform> xsltDict = new Dictionary<string, XslCompiledTransform>();
/// <summary>
/// public method for GenerateCode
/// </summary>
/// <param name="inputFileName"></param>
/// <returns></returns>
public string GenerateCode(string inputFileName)
{
return Encoding.UTF8.GetString(GenerateCode(inputFileName, string.Empty));
}
/// <summary>
/// demand-creates a CodeDomProvider
/// </summary>
protected override byte[] GenerateCode(string inputFileName, string inputFileContent)
{
string xmlFilePath = inputFileName;
string xslFilePath = ResolveXSLPath(xmlFilePath);
if (string.IsNullOrEmpty(xslFilePath) == true)
{
string msg = string.Format("// XSL File not found ({0})", xslFilePath);
return System.Text.Encoding.UTF8.GetBytes(msg);
}
Debug.WriteLine("Original XmlFilePath: " + xmlFilePath);
xmlFilePath = ResolveXmlPath(xmlFilePath);
Debug.WriteLine("Resolved XmlFilePath: " + xmlFilePath);
Debug.WriteLine("Resolved XslFilePath: " + xslFilePath);
#if DEBUG
string txt2 = File.ReadAllText(xslFilePath);
#endif
XslCompiledTransform xslt;
XsltSettings xst = XsltSettings.Default;
xst.EnableScript = true;
try
{
string xsltText = File.ReadAllText(xslFilePath);
// 재활용한다.
if (xsltDict.TryGetValue(xsltText, out xslt) == false)
{
xslt = new XslCompiledTransform();
StringReader sr = new StringReader(xsltText);
using (XmlReader xr = XmlReader.Create(sr))
{
xslt.Load(xr, xst, null);
}
xsltDict.Add(xsltText, xslt);
}
}
catch (Exception ex)
{
string output = string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.ToString());
return System.Text.Encoding.UTF8.GetBytes(output);
}
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb, CultureInfo.CurrentCulture))
{
XmlWriterSettings xws = new XmlWriterSettings();
xws.ConformanceLevel = ConformanceLevel.Auto;
xws.Encoding = Encoding.UTF8;
XmlReaderSettings xrs = new XmlReaderSettings();
XmlWriter writer = XmlTextWriter.Create(sw, xws);
using (XmlReader reader = XmlReader.Create(xmlFilePath, xrs))
{
XsltArgumentList xal = new XsltArgumentList();
// LoadXsltExtensionMethod(xal);
xal.AddParam("XCG_CurrentTime", string.Empty, DateTime.Now.ToString(CultureInfo.InvariantCulture));
xal.AddParam("XCG_Namespace", string.Empty, this.FileNamespace);
xal.AddParam("XCG_BaseFolder", string.Empty, this.BaseFolder);
xal.AddParam("XCG_Version", string.Empty, "1.0");
xslt.Transform(reader, xal, writer);
}
#if DEBUG
string txt = sb.ToString();
#endif
}
return System.Text.Encoding.UTF8.GetBytes(sb.ToString());
}
/// <summary>
/// XML 파일 경로가 XML 파일안에 있는 경우를 해석
/// </summary>
/// <param name="xmlFilePath">VS.NET IDE 에서 제공되는 XML 파일 경로</param>
/// <returns></returns>
private static string ResolveXmlPath(string xmlFilePath)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
string baseFolder = Path.GetDirectoryName(xmlFilePath);
XmlNode sourceNode = xmlDoc.SelectSingleNode("//ExternalSource");
if (sourceNode == null)
{
return xmlFilePath;
}
return Path.Combine(baseFolder, sourceNode.InnerText);
}
private string ResolveXSLPath(string xmlFilePath)
{
// 0: 만약 XML 파일안에 xcg-xsltKey Preprocessor 가 있다면 그를 따른다.
XmlDocument document = new XmlDocument();
document.Load(xmlFilePath);
XmlProcessingInstruction xcgPI =
document.SelectSingleNode("/processing-instruction(\"xcg-xsltKey\")")
as XmlProcessingInstruction;
if (xcgPI != null)
{
return Path.Combine(this.BaseFolder, xcgPI.Value) + ".xslt";
}
// 0.1: 만약 XML 파일안에 xcg-xsltFileName Preprocessor 가 있다면 그를 따른다.
xcgPI = document.SelectSingleNode("/processing-instruction(\"xcg-xsltFileName\")") as XmlProcessingInstruction;
if (xcgPI != null)
{
string xmlFolder = Path.GetDirectoryName(xmlFilePath);
return Path.Combine(xmlFolder, xcgPI.Value) + ".xslt";
}
// 1: XML 파일에서 "xslt" 확장자만 교체해서 검색
string xslFilePath = Path.ChangeExtension(xmlFilePath, "xslt");
if (File.Exists(xslFilePath) == true)
{
return xslFilePath;
}
// 2: 같은 폴더에서 파일명만 default.xslt
string defaultXslFilePath = PathExtension.ChangeFileName(xslFilePath, DefaultXslFileName);
if (File.Exists(defaultXslFilePath) == true)
{
return defaultXslFilePath;
}
// 3: 상위 폴더에서 루트 드라이브까지 파일명이 XML 파일에서 xslt 확장자만 교체한 것과 일치한 것을 검색
string found = PathExtension.SearchInParents(xslFilePath);
if (string.IsNullOrEmpty(found) == false)
{
return found;
}
// 4: 상위 폴더에서 루트 드라이브까지 파일명이 default.xslt 파일이 있는지 검사.
return PathExtension.SearchInParents(defaultXslFilePath);
}
public override string GetDefaultExtension()
{
CodeDomProvider codeDom = GetCodeProvider();
Debug.Assert(codeDom != null, "CodeDomProvider is NULL.");
string extension = codeDom.FileExtension;
if (extension != null && extension.Length > 0)
{
extension = "." + extension.TrimStart(".".ToCharArray());
}
return extension;
}
private CodeDomProvider codeDomProvider = null;
protected virtual CodeDomProvider GetCodeProvider()
{
if (codeDomProvider == null)
{
// Query for IVSMDCodeDomProvider/SVSMDCodeDomProvider for this project type
Microsoft.VisualStudio.Designer.Interfaces.IVSMDCodeDomProvider provider = GetService(typeof(SVSMDCodeDomProvider))
as Microsoft.VisualStudio.Designer.Interfaces.IVSMDCodeDomProvider;
if (provider != null)
{
codeDomProvider = provider.CodeDomProvider as CodeDomProvider;
}
else
{
//In the case where no language specific CodeDom is available, fall back to C#
codeDomProvider = CodeDomProvider.CreateProvider("C#");
}
}
return codeDomProvider;
}
//private static void LoadXsltExtensionMethod(XsltArgumentList xal)
//{
// // 지정된 레지스트리에 등록된 Xslt Extension 메서드 목록을 반환.
// string regPath = XmlCodeGenerator.CodeGeneratorRegistryPath;
// using (RegistryKey baseKey = Registry.LocalMachine.OpenSubKey(regPath))
// {
// string[] subKeyNames = baseKey.GetSubKeyNames();
// foreach (string subKeyName in subKeyNames)
// {
// Trace.WriteLine(subKeyName);
// using (RegistryKey subKey = baseKey.OpenSubKey(subKeyName))
// {
// string extensionPath = Convert.ToString(subKey.GetValue("Path"));
// Trace.WriteLine("==> " + extensionPath);
// Assembly extensionAssembly = Assembly.LoadFrom(extensionPath);
// foreach (Type type in extensionAssembly.GetTypes())
// {
// Type extensionInterface = type.GetInterface(typeof(IXmlCodeGenExtension).Name);
// if (extensionInterface == null)
// {
// continue;
// }
// Trace.WriteLine("Extension Type: " + type.FullName);
// IXmlCodeGenExtension extension = extensionAssembly.CreateInstance(type.FullName) as IXmlCodeGenExtension;
// extension.AddExtensionObject(xal);
// }
// }
// }
// }
//}
}
}
/*
* AppDomain newDomain = null;
string filePath = string.Empty;
try
{
newDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
string thisAssemblyFileName = this.GetType().Assembly.Location;
string path = Path.GetDirectoryName(thisAssemblyFileName);
string dllPath = Path.Combine(path, "SeparatedCodeGenerator.dll");
Debug.WriteLine(dllPath);
ObjectHandle objHandle = newDomain.CreateInstanceFrom(dllPath, "BclExtension.XmlCodeGenerator");
object objTarget = objHandle.Unwrap();
if (objTarget == null)
{
Debug.WriteLine("objTarget == null");
}
else
{
Debug.WriteLine("objTarget != null");
}
Debug.WriteLine("GetHashCode == " + objTarget.GetHashCode());
Type type = objTarget.GetType();
Debug.WriteLine(type.FullName);
Debug.WriteLine(type.BaseType.FullName);
Debug.WriteLine("MemberInfo member in type.GetMembers");
foreach (MemberInfo member in type.GetMembers())
{
Debug.WriteLine(member.Name);
}
Debug.WriteLine("Type itype in type.GetInterfaces");
foreach (Type itype in type.GetInterfaces())
{
Debug.WriteLine(itype.FullName);
}
IXmlCodeGenerator codeGen = objTarget as IXmlCodeGenerator;
if (codeGen == null)
{
Debug.WriteLine("codeGen == null");
}
else
{
Debug.WriteLine("codeGen != null");
}
Debug.WriteLine("TEST");
string txt = codeGen.GenerateCode(dllPath);
Debug.WriteLine("TEST-7");
return System.Text.Encoding.UTF8.GetBytes(txt);
}
finally
{
if (newDomain != null)
{
AppDomain.Unload(newDomain);
newDomain = null;
}
}
*/