PageRenderTime 3ms CodeModel.GetById 1ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/XObjects/Cmdline/XObjectsGenerator.cs

https://bitbucket.org/hma2/sdmxsource.net
C# | 277 lines | 254 code | 16 blank | 7 comment | 41 complexity | f3d73c3da3b8336e6d0668e493de9e32 MD5 | raw file
  1//Copyright (c) Microsoft Corporation.  All rights reserved.
  2
  3using System;
  4using System.Xml;
  5using System.Xml.Schema;
  6using System.Xml.Linq;
  7using System.CodeDom;
  8using System.CodeDom.Compiler;
  9using Xml.Schema.Linq;
 10using Xml.Schema.Linq.CodeGen;
 11using System.IO;
 12using System.Globalization;
 13using Microsoft.CSharp;
 14using System.Reflection;
 15
 16namespace XObjectsGenerator
 17{
 18    using System.Linq;
 19    public class XObjectsGenerator 
 20    {
 21        public static Assembly ThisAssembly;
 22
 23        public static int Main(string[] args) 
 24        {
 25            ThisAssembly  = Assembly.GetExecutingAssembly();
 26            var set = new XmlSchemaSet();
 27            var veh = new ValidationEventHandler(ValidationCallback);
 28            set.ValidationEventHandler += veh;
 29            
 30            string csFileName = string.Empty;
 31            string configFileName = null;
 32            string assemblyName = string.Empty;
 33            bool fSourceNameProvided = false;
 34            bool xmlSerializable = false;
 35            bool nameMangler2 = false;
 36
 37            if (args.Length == 0) 
 38            {
 39                PrintHelp();
 40                return 0;
 41            }
 42            for (int i = 0; i < args.Length; i++) 
 43            {
 44                string arg = args[i];
 45                string value = string.Empty;
 46                bool argument = false;
 47                
 48                if (arg.StartsWith("/") || arg.StartsWith("-")) 
 49                {
 50                    argument = true;
 51                    int colonPos = arg.IndexOf(":");
 52                    if (colonPos != -1) 
 53                    {
 54                        value = arg.Substring(colonPos + 1);
 55                        arg = arg.Substring(0, colonPos);
 56                    }
 57                }
 58                arg = arg.ToLower(CultureInfo.InvariantCulture);
 59                if (!argument) 
 60                {
 61                    try
 62                    {
 63                        set.Add(null, CreateReader(arg));
 64                    }
 65                    catch(Exception e)
 66                    {
 67                        PrintErrorMessage(e.ToString());
 68                        return 1;
 69                    }
 70                    if (csFileName == string.Empty) 
 71                    {
 72                        csFileName = Path.ChangeExtension(arg, "cs");
 73                    }
 74                }
 75                else if (ArgumentMatch(arg, "?") || ArgumentMatch(arg, "help")) 
 76                {
 77                    PrintHelp();
 78                    return 0;
 79                }
 80                else if (ArgumentMatch(arg, "config")) 
 81                {
 82                    configFileName = value;
 83                }
 84                else if (ArgumentMatch(arg, "filename")) 
 85                {
 86                    csFileName = value;
 87                    fSourceNameProvided = true;
 88                }
 89                else if (ArgumentMatch(arg, "enableservicereference")) 
 90                {
 91                    xmlSerializable = true; 
 92                }
 93                else if (ArgumentMatch(arg, "lib"))
 94                {
 95                    assemblyName = value;
 96                }
 97                else if (ArgumentMatch(arg, "namemangler2"))
 98                {
 99                    nameMangler2 = true;
100                }
101            }
102            if(assemblyName != string.Empty && !fSourceNameProvided)
103            { 
104                //only generate assembly
105                csFileName = string.Empty;
106            }
107            set.Compile();
108            set.ValidationEventHandler  -= veh;
109            if (set.Count > 0 && set.IsCompiled) 
110            {
111                /*
112                GenerateXObjects(
113                    set, csFileName, configFileName, assemblyName, xmlSerializable, nameMangler2);
114                */
115                try 
116                {
117                    GenerateXObjects(
118                        set, 
119                        csFileName, 
120                        configFileName, 
121                        assemblyName, 
122                        xmlSerializable, 
123                        nameMangler2);
124                }
125                catch(Exception e) 
126                {
127                    PrintErrorMessage(e.ToString());
128                    return 1;
129                }
130            }
131            return 0;
132        }
133
134        public static void GenerateXObjects(
135            XmlSchemaSet set, 
136            string csFileName, 
137            string configFileName, 
138            string assemblyName, 
139            bool xmlSerializable, 
140            bool nameMangler2) 
141        {
142            var configSettings = new LinqToXsdSettings(nameMangler2);
143            if (configFileName != null) 
144            {
145                configSettings.Load(configFileName);
146            }
147            configSettings.EnableServiceReference = xmlSerializable;
148            var xsdConverter = new XsdToTypesConverter(configSettings);
149            var mapping = xsdConverter.GenerateMapping(set);
150
151            var codeGenerator = new CodeDomTypesGenerator(configSettings);
152            var ccu = new CodeCompileUnit();
153            foreach(var codeNs in codeGenerator.GenerateTypes(mapping))
154            {
155                ccu.Namespaces.Add(codeNs);
156            }
157            //Write to file
158            var provider = new CSharpCodeProvider();
159            if (csFileName != string.Empty && csFileName != null)
160            {
161                using (var update = 
162                    new Update(csFileName, System.Text.Encoding.UTF8))
163                {
164                    provider.GenerateCodeFromCompileUnit(
165                        ccu, update.Writer, new CodeGeneratorOptions());
166                }
167                PrintMessage(csFileName);
168            }
169            if(assemblyName != string.Empty)
170            {
171                var options = new CompilerParameters
172                {
173                    OutputAssembly = assemblyName,
174                    IncludeDebugInformation = true,
175                    TreatWarningsAsErrors = true,
176                };
177                options.TempFiles.KeepFiles = true;
178                {
179                    var r = options.ReferencedAssemblies;
180                    r.Add("System.dll");
181                    r.Add("System.Core.dll");
182                    r.Add("System.Xml.dll");
183                    r.Add("System.Xml.Linq.dll");
184                    r.Add("Xml.Schema.Linq.dll");
185                }
186                var results = provider.CompileAssemblyFromDom(options, ccu);
187                if (results.Errors.Count > 0)
188                {
189                    PrintErrorMessage("compilation error(s): ");
190                    for (int i = 0; i < results.Errors.Count; i++)
191                    {
192                        PrintErrorMessage(results.Errors[i].ToString());
193                    }
194                    throw new Exception("compilation error(s)");
195                }
196                else
197                {
198                    PrintMessage(
199                        "Generated Assembly: " +
200                        results.CompiledAssembly.ToString());
201                }
202            }
203        }
204
205        private static XmlReader CreateReader(string xsdFile) 
206        {
207            return XmlReader.Create(
208                xsdFile, 
209                new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse });
210        }
211        
212        private static void PrintMessage(string csFileName) 
213        {
214            PrintHeader();
215            Console.WriteLine("Generated " + csFileName + "...");
216        }
217
218        private static void PrintErrorMessage(String e)
219        {
220            Console.Error.WriteLine("LinqToXsd: error TX0001: {0}", e);
221        }
222
223        private static void PrintErrorMessage(ValidationEventArgs args)
224        {
225            Console.Error.WriteLine(
226                "{0}({1},{2}): {3} TX0001: {4}", 
227                args.Exception.SourceUri.
228                    Replace("file:///", "").Replace('/', '\\'),
229                args.Exception.LineNumber,
230                args.Exception.LinePosition, 
231                args.Severity == XmlSeverityType.Warning ? "warning" : "error",
232                args.Message);
233        }
234
235        private static void PrintHeader() 
236        {
237            Console.WriteLine(
238                String.Format(
239                    CultureInfo.CurrentCulture, 
240                    "[Microsoft (R) .NET Framework, Version {0}]", 
241                    ThisAssembly.ImageRuntimeVersion));
242        }
243
244        private static void PrintHelp() 
245        {
246            PrintHeader();
247            string name = ThisAssembly.GetName().Name;
248            Console.WriteLine();
249            Console.WriteLine(
250                name + 
251                " - " + 
252                "Utility to generate typed wrapper classes from a XML Schema");
253            Console.WriteLine(
254                "Usage: " + 
255                name + 
256                " <schemaFile> [one or more schema files] [/fileName:<csFileName>.cs] [/lib:<assemblyName>] [/config:<configFileName>.xml] [/enableServiceReference] [/nameMangler2]");
257        }
258
259        private static void ValidationCallback(
260            object sender, ValidationEventArgs args) 
261        {
262            PrintErrorMessage(args);
263        }
264
265        private static bool ArgumentMatch(string arg, string toMatch) 
266        {
267            switch (arg[0])
268            {
269                case '/':
270                case '-':
271                    return arg.Substring(1) == toMatch;
272                default:
273                    return false;
274            }
275        }
276    }
277}