/// <summary> /// Analyse file to find generation option. /// </summary> /// <param name="xsdFilePath">The XSD file path.</param> /// <param name="languageIdentifier">The language identifier.</param> /// <param name="defaultNamespace">The default namespace.</param> public void Init(string xsdFilePath, string languageIdentifier, string defaultNamespace, TargetFramework framework) { string outputFile; this.generatorParams = GeneratorParams.LoadFromFile(xsdFilePath, out outputFile); if (this.generatorParams == null) { this.generatorParams = new GeneratorParams(); switch (languageIdentifier) { case "{B5E9BD33-6D3E-4B5D-925E-8A43B79820B4}": this.generatorParams.Language = GenerationLanguage.VisualBasic; break; case "{B5E9BD36-6D3E-4B5D-925E-8A43B79820B4}": this.generatorParams.Language = GenerationLanguage.VisualCpp; break; default: this.generatorParams.Language = GenerationLanguage.CSharp; break; } this.generatorParams.TargetFramework = framework; this.generatorParams.NameSpace = defaultNamespace; } this.propertyGrid.SelectedObject = this.generatorParams; this.OutputFile = outputFile; }
/// <summary> /// Processes the code generation. /// </summary> /// <returns>true if sucess or false.</returns> public Result<string> Generate(GeneratorParams generatorParams) { GeneratorContext.GeneratorParams = generatorParams; var outputFileName = GeneratorContext.GeneratorParams.OutputFilePath; var processResult = this.Process(outputFileName); return new Result<string>(outputFileName, processResult.Success, processResult.Messages); }
internal static Result<CodeNamespace> Process(string xsdFile, string targetNamespace, GenerationLanguage language, CollectionType collectionType, bool enableDataBinding, bool hidePrivate, bool enableSummaryComment, List<NamespaceParam> customUsings, string collectionBase, bool includeSerializeMethod, string serializeMethodName, string deserializeMethodName, string saveToFileMethodName, string loadFromFileMethodName, bool generateCloneMethod, TargetFramework targetFramework) { var generatorParams = new GeneratorParams { CollectionObjectType = collectionType, EnableDataBinding = enableDataBinding, Language = language, CustomUsings = customUsings, CollectionBase = collectionBase, GenerateCloneMethod = generateCloneMethod, TargetFramework = targetFramework }; generatorParams.Miscellaneous.HidePrivateFieldInIde = hidePrivate; generatorParams.Miscellaneous.EnableSummaryComment = enableSummaryComment; generatorParams.Serialization.Enabled = includeSerializeMethod; generatorParams.Serialization.SerializeMethodName = serializeMethodName; generatorParams.Serialization.DeserializeMethodName = deserializeMethodName; generatorParams.Serialization.SaveToFileMethodName = saveToFileMethodName; generatorParams.Serialization.LoadFromFileMethodName = loadFromFileMethodName; return Process(generatorParams); }
static void Main(string[] args) { const string outFile = @"cobieliteuk.designer.cs"; const string inFile = @"..\..\..\Xbim.COBieLiteUK\Schemas\cobieliteuk.xsd"; if (!File.Exists(inFile)) Console.WriteLine(@"COBieLiteUK schema not found."); var generatorParams = new GeneratorParams { InputFilePath = inFile, CollectionObjectType = CollectionType.List, Language = GenerationLanguage.CSharp, NameSpace = "Xbim.COBieLiteUK", OutputFilePath = outFile, TargetFramework = TargetFramework.CobieLiteUk, EnableInitializeFields = false, Serialization = new SerializeParams { DefaultEncoder = DefaultEncoder.UTF8, GenerateXmlAttributes = true } }; generatorParams.PropertyParams = new PropertyParams(generatorParams) { GenerateShouldSerializeProperty = true, GeneratePropertyNameSpecified = PropertyNameSpecifiedType.None }; // Create an instance of Generator var generator = new GeneratorFacade(generatorParams); // Generate code var result = generator.Generate(); if (!result.Success) { // Display the error and wait for user confirmation Console.WriteLine(); Console.WriteLine(result.Messages.ToString()); Console.WriteLine(); Console.WriteLine(@"Press ENTER to continue..."); Console.ReadLine(); return; } //do textual replacement var outFileFullPath = Path.Combine(Path.GetDirectoryName(inFile), outFile); var code = File.ReadAllText(outFileFullPath); code = code.Replace("System.", "global::System."); code = code.Replace("System;", "global::System;"); File.WriteAllText(outFileFullPath, code); Console.WriteLine(@"Generated code has been saved to the file {0}.", result.Entity); Console.WriteLine(); Console.WriteLine(@"Finished"); Console.WriteLine(); }
/// <summary> /// Processes the code generation. /// </summary> /// <returns>true if sucess or false.</returns> public Result <string> Generate(GeneratorParams generatorParams) { GeneratorContext.GeneratorParams = generatorParams; var outputFileName = GeneratorContext.GeneratorParams.OutputFilePath; var processResult = this.Process(outputFileName); return(new Result <string>(outputFileName, processResult.Success, processResult.Messages)); }
/// <summary> /// Initialize generator /// </summary> /// <param name="provider"></param> /// <param name="generatorParams"></param> public void Init(CodeDomProvider provider, GeneratorParams generatorParams) { this.providerField = provider; GeneratorContext.GeneratorParams = generatorParams.Clone(); if (string.IsNullOrEmpty(GeneratorContext.GeneratorParams.OutputFilePath)) { string outputFilePath = Utility.GetOutputFilePath(generatorParams.InputFilePath, provider); GeneratorContext.GeneratorParams.OutputFilePath = outputFilePath; } }
/// <summary> /// Get <see cref="ICodeExtension"/> code generator extension /// </summary> /// <param name="generatorParams">Generator parameters</param> /// <returns><see cref="ICodeExtension"/></returns> internal static Result <ICodeExtension> GetCodeExtension(GeneratorParams generatorParams) { var extention = new Result <ICodeExtension>(GeneratorFactory.GetExtention(generatorParams.TargetFramework), true); if (extention.Entity != null) { return(extention); } var types = Assembly.GetExecutingAssembly().GetTypes() .Select(type => new { Type = type, TargetFrameworkAttributes = type.GetCustomAttributes(typeof(CodeExtensionAttribute), true) }) .Where(o => o.TargetFrameworkAttributes.Length > 0 && o.TargetFrameworkAttributes .Where(attr => ((CodeExtensionAttribute)attr).TargetFramework == generatorParams.TargetFramework) .Count() > 0) .ToList(); if (types.Count == 1) { try { return(new Result <ICodeExtension>(Activator.CreateInstance(types[0].Type) as ICodeExtension, true)); } catch (Exception ex) { return(new Result <ICodeExtension>(null, false, ex.Message, MessageType.Error)); } } return(new Result <ICodeExtension>(null, false, string.Format(Resources.UnsupportedTargetFramework, generatorParams.TargetFramework), MessageType.Error)); }
/// <summary> /// Get <see cref="ICodeExtension"/> code generator extension /// </summary> /// <param name="generatorParams">Generator parameters</param> /// <returns><see cref="ICodeExtension"/></returns> internal static Result<ICodeExtension> GetCodeExtension(GeneratorParams generatorParams) { var extention = new Result<ICodeExtension>(GeneratorFactory.GetExtention(generatorParams.TargetFramework), true); if (extention.Entity != null) return extention; var types = Assembly.GetExecutingAssembly().GetTypes() .Select(type => new { Type = type, TargetFrameworkAttributes = type.GetCustomAttributes(typeof(CodeExtensionAttribute), true) }) .Where(o => o.TargetFrameworkAttributes.Length > 0 && o.TargetFrameworkAttributes .Where(attr => ((CodeExtensionAttribute)attr).TargetFramework == generatorParams.TargetFramework) .Count() > 0) .ToList(); if (types.Count == 1) { try { return new Result<ICodeExtension>(Activator.CreateInstance(types[0].Type) as ICodeExtension, true); } catch (Exception ex) { return new Result<ICodeExtension>(null, false, ex.Message, MessageType.Error); } } return new Result<ICodeExtension>(null, false, string.Format(Resources.UnsupportedTargetFramework, generatorParams.TargetFramework), MessageType.Error); }
private static void GenereateCodeWithXsd2Code(string xsdFilepath, string codeOutPath, string nameSpace) { GeneratorParams generatorParams = new GeneratorParams { InputFilePath = xsdFilepath, OutputFilePath = codeOutPath, Language = GenerationLanguage.CSharp, NameSpace = nameSpace, CollectionObjectType = CollectionType.List, PropertyParams = { AutomaticProperties = true, PascalCaseProperty = true }, Serialization = { Enabled = true, GenerateXmlAttributes = true } }; // Create an instance of Generator GeneratorFacade generator = new GeneratorFacade(generatorParams); // Generate code Result<string> result = generator.Generate(); }
public GeneratorFacade(GeneratorParams generatorParams) { var provider = CodeDomProviderFactory.GetProvider(generatorParams.Language); this.Init(provider, generatorParams); }
public void CircularClassReference() { lock (testLock) { // Copy resource file to the run-time directory string inputFilePath = GetInputFilePath("CircularClassReference.xsd", Resources.CircularClassReference); var generatorParams = new GeneratorParams { InputFilePath = inputFilePath, TargetFramework = TargetFramework.Net20, AutomaticProperties = true, IncludeSerializeMethod = false, UseGenericBaseClass = false, OutputFilePath = GetOutputFilePath(inputFilePath) }; var xsdGen = new GeneratorFacade(generatorParams); var result = xsdGen.Generate(); Assert.IsTrue(result.Success, result.Messages.ToString()); try { var cs = new Circular(); #pragma warning disable 168 int count = cs.circular.count; #pragma warning restore 168 var compileResult = CompileCSFile(generatorParams.OutputFilePath); Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString()); } catch (Exception e) { Assert.Fail(e.Message); } } }
private static void Main(string[] args) { // Display hekp when no parameters have been specified if (args.Length < 1) { DisplayApplicationInfo(); DisplayHelp(); return; } DisplayApplicationInfo(); // Create new instance of GeneratorParams, which contains all generation parameters var xsdFilePath = args[0]; var generatorParams = new GeneratorParams { InputFilePath = xsdFilePath }; // When only the XSD file name is specified, // try to locate generated Designer file and load output parameters from the file header if (args.Length == 1) { string outputFilePath; var tempGeneratorParams = GeneratorParams.LoadFromFile(xsdFilePath, out outputFilePath); if (tempGeneratorParams != null) { generatorParams = tempGeneratorParams; generatorParams.InputFilePath = xsdFilePath; if (!string.IsNullOrEmpty(outputFilePath)) generatorParams.OutputFilePath = outputFilePath; } } // Second command-line parameter that is not a switch is the generated code namespace if (args.Length > 1 && !args[1].StartsWith("/")) { generatorParams.NameSpace = args[1]; // Third command-line parameter that is not a switch is the generated code namespace if (args.Length > 2 && !args[2].StartsWith("/")) generatorParams.OutputFilePath = args[2]; } // Process command-line parameter switches for (int i = 1; i < args.Length; i++) { switch (args[i].Trim().ToLower()) { case "/n": case "/ns": case "/namespace": if (i < args.Length - 1) { generatorParams.NameSpace = args[i + 1]; i++; } break; case "/o": case "/out": case "/output": if (i < args.Length - 1) { generatorParams.OutputFilePath = args[i + 1]; i++; } break; case "/l": case "/lang": case "/language": if (i < args.Length - 1) { generatorParams.Language = Utility.GetGenerationLanguage(args[i + 1]); i++; } break; case "/c": case "/col": case "/collection": case "/collectionbase": if (i < args.Length - 1) { generatorParams.CollectionObjectType = Utility.ToEnum<CollectionType>(args[i + 1]); i++; } break; //Duplicate with /pl case "/cb": case "/codebase": if (i < args.Length - 1) { Console.WriteLine("Warning: /cb /codebase is obsolete please use /pl[atform] <Platform> - Generated code target platform (Net20|Net30|Net35|Silverlight20). Default: Net20"); generatorParams.TargetFramework = Utility.ToEnum<TargetFramework>(args[i + 1]); i++; } break; case "/cu": case "/customusings": if (i < args.Length - 1) { //generatorParams.CustomUsingsString = args[i + 1]; foreach (string item in args[i + 1].Split(',')) { generatorParams.CustomUsings.Add(new NamespaceParam { NameSpace = item }); } i++; } break; case "/lf": case "/lfm": if (i < args.Length - 1) { generatorParams.Serialization.LoadFromFileMethodName = args[i + 1]; i++; } break; case "/sm": if (i < args.Length - 1) { generatorParams.Serialization.SerializeMethodName = args[i + 1]; i++; } break; case "/sf": case "/sfm": if (i < args.Length - 1) { generatorParams.Serialization.SaveToFileMethodName = args[i + 1]; i++; } break; case "/p": case "/pl": case "/tp": case "/tpl": case "/platform": if (i < args.Length - 1) { generatorParams.TargetFramework = Utility.GetTargetPlatform(args[i + 1]); i++; } break; case "/u": case "/us": case "/using": if (i < args.Length - 1) { var nsList = args[i + 1].Split(','); foreach (var ns in nsList) generatorParams.CustomUsings.Add(new NamespaceParam { NameSpace = ns }); i++; } break; case "/dbg": case "/dbg+": case "/debug": case "/debug+": generatorParams.Miscellaneous.DisableDebug = false; break; case "/dbg-": case "/debug-": generatorParams.Miscellaneous.DisableDebug = true; break; case "/db": case "/db+": generatorParams.EnableDataBinding = true; break; case "/db-": generatorParams.EnableDataBinding = false; break; case "/dc": case "/dc+": generatorParams.GenerateDataContracts = true; break; case "/dc-": generatorParams.GenerateDataContracts = false; break; case "/ap": case "/ap+": generatorParams.PropertyParams.AutomaticProperties = true; break; case "/ap-": generatorParams.PropertyParams.AutomaticProperties = false; break; case "/if": case "/if+": generatorParams.EnableInitializeFields = true; break; case "/if-": generatorParams.EnableInitializeFields = false; break; case "/eit": case "/eit+": generatorParams.Miscellaneous.ExcludeIncludedTypes = true; break; case "/eit-": generatorParams.Miscellaneous.ExcludeIncludedTypes = false; break; case "/gbc": case "/gbc+": generatorParams.GenericBaseClass.Enabled = true; break; case "/gbc-": generatorParams.GenericBaseClass.Enabled = false; break; case "/ggbc": case "/ggbc+": generatorParams.GenericBaseClass.GenerateBaseClass = true; break; case "/ggbc-": generatorParams.GenericBaseClass.GenerateBaseClass = false; break; case "/sc": case "/sc+": generatorParams.Miscellaneous.EnableSummaryComment = true; break; case "/sc-": case "/sum-": generatorParams.Miscellaneous.EnableSummaryComment = false; break; case "/xa": case "/xa+": generatorParams.Serialization.GenerateXmlAttributes = true; break; case "/xa-": generatorParams.Serialization.GenerateXmlAttributes = false; break; case "/cl": case "/cl+": generatorParams.GenerateCloneMethod = true; break; case "/cl-": generatorParams.GenerateCloneMethod = false; break; case "/hp": case "/hp+": generatorParams.Miscellaneous.HidePrivateFieldInIde = true; break; case "/hp-": generatorParams.Miscellaneous.HidePrivateFieldInIde = false; break; case "/tc": case "/tc+": generatorParams.TrackingChanges.Enabled = true; break; case "/tc-": generatorParams.TrackingChanges.Enabled = false; break; case "/tcc": case "/tcc+": generatorParams.TrackingChanges.GenerateTrackingClasses = true; break; case "/tcc-": generatorParams.TrackingChanges.GenerateTrackingClasses = false; break; case "/ssp": case "/ssp+": generatorParams.PropertyParams.GenerateShouldSerializeProperty = true; break; case "/ssp-": generatorParams.PropertyParams.GenerateShouldSerializeProperty = false; break; case "/s": case "/s+": case "/is": case "/is+": generatorParams.Serialization.Enabled = true; break; case "/s-": case "/is-": generatorParams.Serialization.Enabled = false; break; case "/lic": case "/license": DisplayLicense(); return; case "/?": case "/h": case "/hlp": case "/help": DisplayHelp(); return; } } // Auto-generate missing output file path if (string.IsNullOrEmpty(generatorParams.OutputFilePath)) { generatorParams.OutputFilePath = Utility.GetOutputFilePath(generatorParams.InputFilePath, generatorParams.Language); } // Auto-generate missing generated code namespace if (string.IsNullOrEmpty(generatorParams.NameSpace)) generatorParams.NameSpace = Path.GetFileNameWithoutExtension(generatorParams.InputFilePath); // Create an instance of Generator var generator = new GeneratorFacade(generatorParams); // Generate code var result = generator.Generate(); if (!result.Success) { // Display the error and wait for user confirmation Console.WriteLine(); Console.WriteLine(result.Messages.ToString()); Console.WriteLine(); Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); return; } Console.WriteLine("Generated code has been saved into the file {0}.", result.Entity); Console.WriteLine(); Console.WriteLine("Finished"); Console.WriteLine(); }
private static GeneratorParams GetGeneratorParams(string inputFilePath) { var generatorParams = new GeneratorParams { InputFilePath = inputFilePath, NameSpace = CodeGenerationNamespace, TargetFramework = TargetFramework.Net20, CollectionObjectType = CollectionType.ObservableCollection, EnableDataBinding = true, GenerateDataContracts = true, GenerateCloneMethod = true, OutputFilePath = GetOutputFilePath(inputFilePath) }; generatorParams.Miscellaneous.HidePrivateFieldInIde = true; generatorParams.Miscellaneous.DisableDebug = true; generatorParams.Serialization.Enabled = true; return generatorParams; }
/// <summary> /// Generator facade class constructor /// </summary> /// <param name="provider">Code DOM provider</param> /// <param name="generatorParams">Generator parameters</param> public GeneratorFacade(CodeDomProvider provider, GeneratorParams generatorParams) { this.Init(provider, generatorParams); }
public void TestAnnotations() { lock (testLock) { // Get the code namespace for the schema. string inputFilePath = GetInputFilePath("TestAnnotations.xsd", Resources.TestAnnotations); var generatorParams = new GeneratorParams {InputFilePath = inputFilePath}; GetGeneratorParams(inputFilePath); generatorParams.EnableSummaryComment = true; generatorParams.TargetFramework = TargetFramework.Net35; generatorParams.AutomaticProperties = true; generatorParams.OutputFilePath = Path.ChangeExtension(generatorParams.InputFilePath, ".TestAnnotations.cs"); var xsdGen = new GeneratorFacade(generatorParams); var result = xsdGen.Generate(); Assert.IsTrue(result.Success, result.Messages.ToString()); var compileResult = CompileCSFile(generatorParams.OutputFilePath); Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString()); } }
public void ArrayOfArray() { lock (testLock) { // Copy resource file to the run-time directory var inputFilePath = GetInputFilePath("ArrayOfArray.xsd", Resources.ArrayOfArray); var generatorParams = new GeneratorParams { GenerateCloneMethod = true, IncludeSerializeMethod = true, AutomaticProperties = true, InputFilePath = inputFilePath, NameSpace = "MyNameSpace", CollectionObjectType = CollectionType.Array, EnableDataBinding = true, Language = GenerationLanguage.CSharp, OutputFilePath = Path.ChangeExtension(inputFilePath, ".TestGenerated.cs") }; var xsdGen = new GeneratorFacade(generatorParams); var result = xsdGen.Generate(); Assert.IsTrue(result.Success, result.Messages.ToString()); var compileResult = CompileCSFile(generatorParams.OutputFilePath); Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString()); } }
/// <summary> /// Gets the params. /// </summary> /// <param name="parameters">The parameters.</param> /// <returns>GeneratorParams instance</returns> public static GeneratorParams GetParams(string parameters) { var newparams = new GeneratorParams(); return newparams; }
public PropertyParams(GeneratorParams mainParams) { mainParamsFields = mainParams; }
/// <summary> /// Get Code DOM provider /// </summary> /// <param name="generatorParams"></param> /// <returns></returns> public static CodeDomProvider GetProvider(GeneratorParams generatorParams) { return GetProvider(generatorParams.Language); }
/// <summary> /// Loads from file. /// </summary> /// <param name="xsdFilePath">The XSD file path.</param> /// <param name="outputFile">The output file.</param> /// <returns>GeneratorParams instance</returns> public static GeneratorParams LoadFromFile(string xsdFilePath, out string outputFile) { var parameters = new GeneratorParams(); #region Search generationFile outputFile = string.Empty; foreach (GenerationLanguage language in Enum.GetValues(typeof(GenerationLanguage))) { string fileName = Utility.GetOutputFilePath(xsdFilePath, language); if (File.Exists(fileName)) { outputFile = fileName; break; } } if (outputFile.Length == 0) return null; #endregion #region Try to get Last options using (TextReader streamReader = new StreamReader(outputFile)) { streamReader.ReadLine(); streamReader.ReadLine(); streamReader.ReadLine(); string optionLine = streamReader.ReadLine(); if (optionLine != null) { parameters.NameSpace = XmlHelper.ExtractStrFromXML(optionLine, GeneratorContext.NAMESPACETAG); parameters.CollectionObjectType = Utility.ToEnum<CollectionType>( XmlHelper.ExtractStrFromXML(optionLine, GeneratorContext.COLLECTIONTAG)); parameters.Language = Utility.ToEnum<GenerationLanguage>(XmlHelper.ExtractStrFromXML(optionLine, GeneratorContext.CODETYPETAG)); parameters.EnableDataBinding = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEDATABINDINGTAG)); parameters.EnableLasyLoading = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLELASYLOADINGTAG)); parameters.HidePrivateFieldInIde = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.HIDEPRIVATEFIELDTAG)); parameters.EnableSummaryComment = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLESUMMARYCOMMENTTAG)); parameters.IncludeSerializeMethod = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.INCLUDESERIALIZEMETHODTAG)); parameters.GenerateCloneMethod = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATECLONEMETHODTAG)); parameters.GenerateDataContracts = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEDATACONTRACTSTAG)); parameters.TargetFramework = Utility.ToEnum<TargetFramework>(optionLine.ExtractStrFromXML(GeneratorContext.CODEBASETAG)); parameters.DisableDebug = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.DISABLEDEBUGTAG)); parameters.GenerateXMLAttributes = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEXMLATTRIBUTESTAG)); parameters.AutomaticProperties = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.AUTOMATICPROPERTIESTAG)); parameters.UseGenericBaseClass = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.USEGENERICBASECLASSTAG)); parameters.EnableInitializeFields = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEINITIALIZEFIELDSTAG),true); parameters.ExcludeIncludedTypes = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.EXCLUDEINCLUDEDTYPESTAG)); string str = optionLine.ExtractStrFromXML(GeneratorContext.SERIALIZEMETHODNAMETAG); parameters.SerializeMethodName = str.Length > 0 ? str : "Serialize"; str = optionLine.ExtractStrFromXML(GeneratorContext.DESERIALIZEMETHODNAMETAG); parameters.DeserializeMethodName = str.Length > 0 ? str : "Deserialize"; str = optionLine.ExtractStrFromXML(GeneratorContext.SAVETOFILEMETHODNAMETAG); parameters.SaveToFileMethodName = str.Length > 0 ? str : "SaveToFile"; str = optionLine.ExtractStrFromXML(GeneratorContext.LOADFROMFILEMETHODNAMETAG); parameters.LoadFromFileMethodName = str.Length > 0 ? str : "LoadFromFile"; str = optionLine.ExtractStrFromXML(GeneratorContext.BASECLASSNAMETAG); parameters.BaseClassName = str.Length > 0 ? str : "EntityBase"; // TODO:get custom using string customUsingString = optionLine.ExtractStrFromXML(GeneratorContext.CUSTOMUSINGSTAG); if (!string.IsNullOrEmpty(customUsingString)) { string[] usings = customUsingString.Split(';'); foreach (string item in usings) parameters.CustomUsings.Add(new NamespaceParam { NameSpace = item }); } parameters.CollectionBase = optionLine.ExtractStrFromXML(GeneratorContext.COLLECTIONBASETAG); } } return parameters; #endregion }
/// <summary> /// Initiate code generation process /// </summary> /// <param name="generatorParams">Generator parameters</param> /// <returns></returns> internal static Result <CodeNamespace> Process(GeneratorParams generatorParams) { var ns = new CodeNamespace(); XmlReader reader = null; try { #region Set generation context GeneratorContext.GeneratorParams = generatorParams; #endregion #region Get XmlTypeMapping XmlSchema xsd; var schemas = new XmlSchemas(); reader = XmlReader.Create(generatorParams.InputFilePath); xsd = XmlSchema.Read(reader, new ValidationEventHandler(Validate)); var schemaSet = new XmlSchemaSet(); schemaSet.Add(xsd); schemaSet.Compile(); foreach (XmlSchema schema in schemaSet.Schemas()) { schemas.Add(schema); } const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateOrder; var exporter = new XmlCodeExporter(ns); var importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchemaElement element in xsd.Elements.Values) { var mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } //Fixes/handles http://xsd2code.codeplex.com/WorkItem/View.aspx?WorkItemId=6941 foreach (XmlSchemaComplexType complex in xsd.Items.OfType <XmlSchemaComplexType>()) { var mapping = importer.ImportSchemaType(complex.QualifiedName); exporter.ExportTypeMapping(mapping); } #endregion #region Execute extensions var getExtensionResult = GeneratorFactory.GetCodeExtension(generatorParams); if (!getExtensionResult.Success) { return(new Result <CodeNamespace>(ns, false, getExtensionResult.Messages)); } var ext = getExtensionResult.Entity; ext.Process(ns, xsd); #endregion Execute extensions return(new Result <CodeNamespace>(ns, true)); } catch (Exception e) { return(new Result <CodeNamespace>(ns, false, e.Message, MessageType.Error)); } finally { if (reader != null) { reader.Close(); } } }
public void AutomaticProperties() { lock (testLock) { // Get the code namespace for the schema. GetInputFilePath("Actor.xsd", Resources.Actor); string inputFilePath = GetInputFilePath("dvd.xsd", Resources.dvd); var generatorParams = new GeneratorParams { InputFilePath = inputFilePath }; GetGeneratorParams(inputFilePath); generatorParams.TargetFramework = TargetFramework.Net30; generatorParams.Miscellaneous.EnableSummaryComment = false; generatorParams.GenerateDataContracts = false; generatorParams.PropertyParams.AutomaticProperties = true; generatorParams.Serialization.GenerateXmlAttributes = true; generatorParams.OutputFilePath = Path.ChangeExtension(generatorParams.InputFilePath, ".autoProp.cs"); var xsdGen = new GeneratorFacade(generatorParams); var result = xsdGen.Generate(); Assert.IsTrue(result.Success, result.Messages.ToString()); var compileResult = CompileCSFile(generatorParams.OutputFilePath); Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString()); } }
public void UseBaseClass() { lock (testLock) { // Get the code namespace for the schema. GetInputFilePath("Actor.xsd", Resources.Actor); string inputFilePath = GetInputFilePath("dvd.xsd", Resources.dvd); string outputFilePath = Path.ChangeExtension(inputFilePath, ".baseClass.cs"); var generatorParams = new GeneratorParams { InputFilePath = inputFilePath, TargetFramework = TargetFramework.Net30, EnableSummaryComment = true, GenerateDataContracts = true, AutomaticProperties = false, EnableDataBinding = true, UseGenericBaseClass = true, BaseClassName = "EntityObject", OutputFilePath = outputFilePath }; var xsdGen = new GeneratorFacade(generatorParams); var result = xsdGen.Generate(); Assert.IsTrue(result.Success, result.Messages.ToString()); var compileResult = CompileCSFile(generatorParams.OutputFilePath); Assert.IsTrue(compileResult.Success, compileResult.Messages.ToString()); } }
/// <summary> /// Loads from file. /// </summary> /// <param name="xsdFilePath">The XSD file path.</param> /// <param name="outputFile">The output file.</param> /// <returns>GeneratorParams instance</returns> public static GeneratorParams LoadFromFile(string xsdFilePath, out string outputFile) { var parameters = new GeneratorParams(); #region Search generationFile outputFile = string.Empty; var localDir = Path.GetDirectoryName(xsdFilePath); var schemaConfigPath = Path.ChangeExtension(xsdFilePath, "xsd.xsd2code"); var defaultsConfigPath = Path.Combine(localDir, "defaults.xsd2code"); var configFile = string.Empty; //Try local <schemaName>.xsd.xsd2code if exist Use this file always. if (File.Exists(schemaConfigPath)) { configFile = schemaConfigPath; //outputFile = Utility.GetOutputFilePath(xsdFilePath, language); } else { //Load from the output files if one of them exist foreach (GenerationLanguage language in Enum.GetValues(typeof(GenerationLanguage))) { string fileName = Utility.GetOutputFilePath(xsdFilePath, language); if (File.Exists(fileName)) { outputFile = fileName; configFile = fileName; break; } } //If there isn't a Schema Config File or an output File see if there is a defaults file if (outputFile.Length == 0) { if (File.Exists(defaultsConfigPath)) { configFile = defaultsConfigPath; } } } if (configFile.Length == 0) return null; #endregion #region Try to get Last options //DCM Created Routine to Search for Auto-Generated Parameters var optionLine = ExtractAutoGeneratedParams(configFile); //DCM Fall back to old method because of some invalid Tag names if (optionLine == null) { using (TextReader streamReader = new StreamReader(configFile)) { streamReader.ReadLine(); streamReader.ReadLine(); streamReader.ReadLine(); optionLine = streamReader.ReadLine(); } } if (optionLine != null) { parameters.NameSpace = optionLine.ExtractStrFromXML(GeneratorContext.NAMESPACETAG); parameters.CollectionObjectType = Utility.ToEnum<CollectionType>(optionLine.ExtractStrFromXML(GeneratorContext.COLLECTIONTAG)); parameters.Language = Utility.ToEnum<GenerationLanguage>(optionLine.ExtractStrFromXML(GeneratorContext.CODETYPETAG)); parameters.EnableDataBinding = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEDATABINDINGTAG)); parameters.PropertyParams.EnableLazyLoading = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLELAZYLOADINGTAG)); parameters.Miscellaneous.HidePrivateFieldInIde = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.HIDEPRIVATEFIELDTAG)); parameters.Miscellaneous.EnableSummaryComment = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLESUMMARYCOMMENTTAG)); parameters.TrackingChanges.Enabled = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLETRACKINGCHANGESTAG)); parameters.TrackingChanges.GenerateTrackingClasses = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATETRACKINGCLASSESTAG)); parameters.Serialization.Enabled = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.INCLUDESERIALIZEMETHODTAG)); parameters.Serialization.EnableEncoding = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEENCODINGTAG)); parameters.Serialization.DefaultEncoder = Utility.ToEnum<DefaultEncoder>(optionLine.ExtractStrFromXML(GeneratorContext.DEFAULTENCODERTAG)); parameters.GenerateCloneMethod = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATECLONEMETHODTAG)); parameters.GenerateDataContracts = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEDATACONTRACTSTAG)); parameters.TargetFramework = Utility.ToEnum<TargetFramework>(optionLine.ExtractStrFromXML(GeneratorContext.CODEBASETAG)); parameters.Miscellaneous.DisableDebug = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.DISABLEDEBUGTAG)); parameters.Serialization.GenerateXmlAttributes = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEXMLATTRIBUTESTAG)); parameters.Serialization.GenerateOrderXmlAttributes = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ORDERXMLATTRIBUTETAG)); parameters.PropertyParams.AutomaticProperties = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.AUTOMATICPROPERTIESTAG)); parameters.PropertyParams.EnableVirtualProperties = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEVIRTUALPROPERTIESTAG)); parameters.GenericBaseClass.Enabled = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.USEGENERICBASECLASSTAG)); parameters.GenericBaseClass.GenerateBaseClass = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEBASECLASSTAG)); parameters.PropertyParams.GenerateShouldSerializeProperty = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATESHOULDSERIALIZETAG)); parameters.EnableInitializeFields = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEINITIALIZEFIELDSTAG), true); parameters.Miscellaneous.ExcludeIncludedTypes = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.EXCLUDEINCLUDEDTYPESTAG)); parameters.PropertyParams.GeneratePropertyNameSpecified = Utility.ToEnum<PropertyNameSpecifiedType>(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEPROPERTYNAMESPECIFIEDTAG)); string str = optionLine.ExtractStrFromXML(GeneratorContext.SERIALIZEMETHODNAMETAG); parameters.Serialization.SerializeMethodName = str.Length > 0 ? str : "Serialize"; str = optionLine.ExtractStrFromXML(GeneratorContext.DESERIALIZEMETHODNAMETAG); parameters.Serialization.DeserializeMethodName = str.Length > 0 ? str : "Deserialize"; str = optionLine.ExtractStrFromXML(GeneratorContext.SAVETOFILEMETHODNAMETAG); parameters.Serialization.SaveToFileMethodName = str.Length > 0 ? str : "SaveToFile"; str = optionLine.ExtractStrFromXML(GeneratorContext.LOADFROMFILEMETHODNAMETAG); parameters.Serialization.LoadFromFileMethodName = str.Length > 0 ? str : "LoadFromFile"; str = optionLine.ExtractStrFromXML(GeneratorContext.BASECLASSNAMETAG); parameters.GenericBaseClass.BaseClassName = str.Length > 0 ? str : "EntityBase"; // TODO:get custom using string customUsingString = optionLine.ExtractStrFromXML(GeneratorContext.CUSTOMUSINGSTAG); if (!string.IsNullOrEmpty(customUsingString)) { string[] usings = customUsingString.Split(';'); foreach (string item in usings) parameters.CustomUsings.Add(new NamespaceParam { NameSpace = item }); } parameters.CollectionBase = optionLine.ExtractStrFromXML(GeneratorContext.COLLECTIONBASETAG); } return parameters; #endregion }
/// <summary> /// Initiate code generation process /// </summary> /// <param name="generatorParams">Generator parameters</param> /// <returns></returns> internal static Result<CodeNamespace> Process(GeneratorParams generatorParams) { var ns = new CodeNamespace(); XmlReader reader = null; try { #region Set generation context GeneratorContext.GeneratorParams = generatorParams; #endregion #region Get XmlTypeMapping XmlSchema xsd; var schemas = new XmlSchemas(); reader = XmlReader.Create(generatorParams.InputFilePath); xsd = XmlSchema.Read(reader, new ValidationEventHandler(Validate)); var schemaSet = new XmlSchemaSet(); schemaSet.Add(xsd); schemaSet.Compile(); foreach (XmlSchema schema in schemaSet.Schemas()) { schemas.Add(schema); } var exporter = new XmlCodeExporter(ns); var generationOptions = CodeGenerationOptions.None; if (generatorParams.Serialization.GenerateOrderXmlAttributes) { generationOptions = CodeGenerationOptions.GenerateOrder; } var importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchemaElement element in xsd.Elements.Values) { var mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } //Fixes/handles http://xsd2code.codeplex.com/WorkItem/View.aspx?WorkItemId=6941 foreach (XmlSchemaType type in xsd.Items.OfType<XmlSchemaType>()) { var mapping = importer.ImportSchemaType(type.QualifiedName); exporter.ExportTypeMapping(mapping); } #endregion #region Execute extensions var getExtensionResult = GeneratorFactory.GetCodeExtension(generatorParams); if (!getExtensionResult.Success) return new Result<CodeNamespace>(ns, false, getExtensionResult.Messages); var ext = getExtensionResult.Entity; ext.Process(ns, xsd); #endregion Execute extensions return new Result<CodeNamespace>(ns, true); } catch (Exception e) { return new Result<CodeNamespace>(ns, false, e.Message, MessageType.Error); } finally { if (reader != null) reader.Close(); } }
/// <summary> /// Loads from file. /// </summary> /// <param name="xsdFilePath">The XSD file path.</param> /// <param name="outputFile">The output file.</param> /// <returns>GeneratorParams instance</returns> public static GeneratorParams LoadFromFile(string xsdFilePath, out string outputFile) { var parameters = new GeneratorParams(); #region Search generationFile outputFile = string.Empty; var localDir = Path.GetDirectoryName(xsdFilePath); var schemaConfigPath = Path.ChangeExtension(xsdFilePath, "xsd.xsd2code"); var defaultsConfigPath = Path.Combine(localDir, "defaults.xsd2code"); var configFile = string.Empty; //Try local <schemaName>.xsd.xsd2code if exist Use this file always. if (File.Exists(schemaConfigPath)) { configFile = schemaConfigPath; //outputFile = Utility.GetOutputFilePath(xsdFilePath, language); } else { //Load from the output files if one of them exist foreach (GenerationLanguage language in Enum.GetValues(typeof(GenerationLanguage))) { string fileName = Utility.GetOutputFilePath(xsdFilePath, language); if (File.Exists(fileName)) { outputFile = fileName; configFile = fileName; break; } } //If there isn't a Schema Config File or an output File see if there is a defaults file if (outputFile.Length == 0) { if (File.Exists(defaultsConfigPath)) { configFile = defaultsConfigPath; } } } if (configFile.Length == 0) { return(null); } #endregion #region Try to get Last options //DCM Created Routine to Search for Auto-Generated Parameters var optionLine = ExtractAutoGeneratedParams(configFile); //DCM Fall back to old method because of some invalid Tag names if (optionLine == null) { using (TextReader streamReader = new StreamReader(configFile)) { streamReader.ReadLine(); streamReader.ReadLine(); streamReader.ReadLine(); optionLine = streamReader.ReadLine(); } } if (optionLine != null) { parameters.NameSpace = optionLine.ExtractStrFromXML(GeneratorContext.NAMESPACETAG); parameters.CollectionObjectType = Utility.ToEnum <CollectionType>(optionLine.ExtractStrFromXML(GeneratorContext.COLLECTIONTAG)); parameters.Language = Utility.ToEnum <GenerationLanguage>(optionLine.ExtractStrFromXML(GeneratorContext.CODETYPETAG)); parameters.EnableDataBinding = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEDATABINDINGTAG)); parameters.PropertyParams.EnableLazyLoading = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLELAZYLOADINGTAG)); parameters.Miscellaneous.HidePrivateFieldInIde = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.HIDEPRIVATEFIELDTAG)); parameters.Miscellaneous.EnableSummaryComment = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLESUMMARYCOMMENTTAG)); parameters.TrackingChanges.Enabled = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLETRACKINGCHANGESTAG)); parameters.TrackingChanges.GenerateTrackingClasses = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATETRACKINGCLASSESTAG)); parameters.Serialization.Enabled = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.INCLUDESERIALIZEMETHODTAG)); parameters.Serialization.EnableEncoding = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEENCODINGTAG)); parameters.Serialization.DefaultEncoder = Utility.ToEnum <DefaultEncoder>(optionLine.ExtractStrFromXML(GeneratorContext.DEFAULTENCODERTAG)); parameters.GenerateCloneMethod = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATECLONEMETHODTAG)); parameters.GenerateDataContracts = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEDATACONTRACTSTAG)); parameters.TargetFramework = Utility.ToEnum <TargetFramework>(optionLine.ExtractStrFromXML(GeneratorContext.CODEBASETAG)); parameters.Miscellaneous.DisableDebug = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.DISABLEDEBUGTAG)); parameters.Serialization.GenerateXmlAttributes = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEXMLATTRIBUTESTAG)); parameters.Serialization.GenerateOrderXmlAttributes = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ORDERXMLATTRIBUTETAG)); parameters.PropertyParams.AutomaticProperties = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.AUTOMATICPROPERTIESTAG)); parameters.PropertyParams.EnableVirtualProperties = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEVIRTUALPROPERTIESTAG)); parameters.GenericBaseClass.Enabled = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.USEGENERICBASECLASSTAG)); parameters.GenericBaseClass.GenerateBaseClass = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEBASECLASSTAG)); parameters.PropertyParams.GenerateShouldSerializeProperty = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.GENERATESHOULDSERIALIZETAG)); parameters.EnableInitializeFields = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.ENABLEINITIALIZEFIELDSTAG), true); parameters.Miscellaneous.ExcludeIncludedTypes = Utility.ToBoolean(optionLine.ExtractStrFromXML(GeneratorContext.EXCLUDEINCLUDEDTYPESTAG)); parameters.PropertyParams.GeneratePropertyNameSpecified = Utility.ToEnum <PropertyNameSpecifiedType>(optionLine.ExtractStrFromXML(GeneratorContext.GENERATEPROPERTYNAMESPECIFIEDTAG)); string str = optionLine.ExtractStrFromXML(GeneratorContext.SERIALIZEMETHODNAMETAG); parameters.Serialization.SerializeMethodName = str.Length > 0 ? str : "Serialize"; str = optionLine.ExtractStrFromXML(GeneratorContext.DESERIALIZEMETHODNAMETAG); parameters.Serialization.DeserializeMethodName = str.Length > 0 ? str : "Deserialize"; str = optionLine.ExtractStrFromXML(GeneratorContext.SAVETOFILEMETHODNAMETAG); parameters.Serialization.SaveToFileMethodName = str.Length > 0 ? str : "SaveToFile"; str = optionLine.ExtractStrFromXML(GeneratorContext.LOADFROMFILEMETHODNAMETAG); parameters.Serialization.LoadFromFileMethodName = str.Length > 0 ? str : "LoadFromFile"; str = optionLine.ExtractStrFromXML(GeneratorContext.BASECLASSNAMETAG); parameters.GenericBaseClass.BaseClassName = str.Length > 0 ? str : "EntityBase"; // TODO:get custom using string customUsingString = optionLine.ExtractStrFromXML(GeneratorContext.CUSTOMUSINGSTAG); if (!string.IsNullOrEmpty(customUsingString)) { string[] usings = customUsingString.Split(';'); foreach (string item in usings) { parameters.CustomUsings.Add(new NamespaceParam { NameSpace = item }); } } parameters.CollectionBase = optionLine.ExtractStrFromXML(GeneratorContext.COLLECTIONBASETAG); } return(parameters); #endregion }
/// <summary> /// Gets the params. /// </summary> /// <param name="parameters">The parameters.</param> /// <returns>GeneratorParams instance</returns> public static GeneratorParams GetParams(string parameters) { var newparams = new GeneratorParams(); return(newparams); }
/// <summary> /// Get Code DOM provider /// </summary> /// <param name="generatorParams"></param> /// <returns></returns> public static CodeDomProvider GetProvider(GeneratorParams generatorParams) { return(GetProvider(generatorParams.Language)); }