diff --git a/XmlSchemaClassGenerator.Console/Program.cs b/XmlSchemaClassGenerator.Console/Program.cs index 5417cadf..ca4d7f8f 100644 --- a/XmlSchemaClassGenerator.Console/Program.cs +++ b/XmlSchemaClassGenerator.Console/Program.cs @@ -48,6 +48,7 @@ static void Main(string[] args) var separateSubstitutes = false; var collectionSettersMode = CollectionSettersMode.Private; var doNotForceIsNullable = false; + var compactTypeNames = false; var options = new OptionSet { { "h|help", "show this message and exit", v => showHelp = v != null }, @@ -113,7 +114,8 @@ A file name may be given by appending a pipe sign (|) followed by a file name (l { "s|useShouldSerialize", "use ShouldSerialize pattern instead of Specified pattern (default is false)", v => useShouldSerialize = v != null }, { "sf|separateFiles", "generate a separate file for each class (default is false)", v => separateClasses = v != null }, { "sg|separateSubstitutes", "generate a separate property for each element of a substitution group (default is false)", v => separateSubstitutes = v != null }, - { "dnfin|doNotForceIsNullable", "do not force generator to emit IsNullable = true in XmlElement annotation for nillable elements when element is nullable (minOccurs < 1 or parent element is choice) (default is false)", v => doNotForceIsNullable = v != null } + { "dnfin|doNotForceIsNullable", "do not force generator to emit IsNullable = true in XmlElement annotation for nillable elements when element is nullable (minOccurs < 1 or parent element is choice) (default is false)", v => doNotForceIsNullable = v != null }, + { "cn|compactTypeNames", "use type names without namespace qualifier for types in the using list (default is false)", v => compactTypeNames = v != null } }; var globsAndUris = options.Parse(args); @@ -184,7 +186,8 @@ A file name may be given by appending a pipe sign (|) followed by a file name (l SeparateClasses = separateClasses, CollectionSettersMode = collectionSettersMode, DoNotForceIsNullable = doNotForceIsNullable, - SeparateSubstitutes = separateSubstitutes + SeparateSubstitutes = separateSubstitutes, + CompactTypeNames = compactTypeNames }; if (pclCompatible) diff --git a/XmlSchemaClassGenerator.Tests/Compiler.cs b/XmlSchemaClassGenerator.Tests/Compiler.cs index 00f70bc7..0bc7ae8b 100644 --- a/XmlSchemaClassGenerator.Tests/Compiler.cs +++ b/XmlSchemaClassGenerator.Tests/Compiler.cs @@ -108,7 +108,8 @@ public static Assembly GenerateFiles(string name, IEnumerable files, Gen SeparateClasses = generatorPrototype.SeparateClasses, CollectionType = generatorPrototype.CollectionType, CollectionImplementationType = generatorPrototype.CollectionImplementationType, - SeparateSubstitutes = generatorPrototype.SeparateSubstitutes + SeparateSubstitutes = generatorPrototype.SeparateSubstitutes, + CompactTypeNames = generatorPrototype.CompactTypeNames }; output.Configuration = gen.Configuration; diff --git a/XmlSchemaClassGenerator.Tests/XmlTests.cs b/XmlSchemaClassGenerator.Tests/XmlTests.cs index 7e31ff5a..73607340 100644 --- a/XmlSchemaClassGenerator.Tests/XmlTests.cs +++ b/XmlSchemaClassGenerator.Tests/XmlTests.cs @@ -30,7 +30,7 @@ public XmlTests(ITestOutputHelper output) Output = output; } - private IEnumerable ConvertXml(string name, IEnumerable xsds, Generator generatorPrototype = null) + private static IEnumerable ConvertXml(string name, IEnumerable xsds, Generator generatorPrototype = null) { if (name is null) { @@ -75,7 +75,7 @@ private IEnumerable ConvertXml(string name, IEnumerable xsds, Ge return writer.Content; } - private IEnumerable ConvertXml(string name, string xsd, Generator generatorPrototype = null) + private static IEnumerable ConvertXml(string name, string xsd, Generator generatorPrototype = null) { return ConvertXml(name, new[] {xsd}, generatorPrototype); } @@ -325,7 +325,20 @@ public void TestArrayOrder() [UseCulture("en-US")] public void TestIS24RestApi() { - Compiler.Generate("IS24RestApi", IS24Pattern); + Compiler.Generate("IS24RestApi", IS24Pattern, new Generator + { + GenerateNullables = true, + IntegerDataType = typeof(int), + DataAnnotationMode = DataAnnotationMode.All, + GenerateDesignerCategoryAttribute = false, + GenerateComplexTypesForCollections = true, + EntityFramework = false, + GenerateInterfaces = true, + NamespacePrefix = "IS24RestApi", + GenerateDescriptionAttribute = true, + TextValuePropertyName = "Value", + CompactTypeNames = true + }); TestSamples("IS24RestApi", IS24Pattern); } @@ -376,7 +389,7 @@ public void TestIS24ImmoTransfer() [UseCulture("en-US")] public void TestTableau() { - Compiler.Generate("Tableau", TableauPattern, new Generator()); + Compiler.Generate("Tableau", TableauPattern, new Generator { CompactTypeNames = true }); TestSamples("Tableau", TableauPattern); } @@ -440,7 +453,7 @@ private void TestSamples(string name, string pattern) private bool HandleValidationError(string[] xmlLines, ValidationEventArgs e) { - var line = xmlLines[e.Exception.LineNumber - 1].Substring(e.Exception.LinePosition - 1); + var line = xmlLines[e.Exception.LineNumber - 1][(e.Exception.LinePosition - 1)..]; var severity = e.Severity == XmlSeverityType.Error ? "Error" : "Warning"; Output.WriteLine($"{severity} at line {e.Exception.LineNumber}, column {e.Exception.LinePosition}: {e.Message}"); Output.WriteLine(line); @@ -578,12 +591,12 @@ public void ProducesSameXmlAsXsd() Assert.NotNull(t1); var t2 = Assembly.GetExecutingAssembly().GetTypes().SingleOrDefault(t => t.Name == c && t.Namespace == "IS24RestApi.Xsd"); Assert.NotNull(t2); - var f = char.ToLower(c[0]) + c.Substring(1); + var f = char.ToLower(c[0]) + c[1..]; TestCompareToXsd(t1, t2, f); } } - void TestCompareToXsd(Type t1, Type t2, string file) + static void TestCompareToXsd(Type t1, Type t2, string file) { foreach (var suffix in new[] { "max", "min" }) { @@ -727,7 +740,7 @@ void UnknownAttributeHandler(object sender, XmlAttributeEventArgs e) } } - private IDictionary GetNamespacesFromSource(string source) + private static IDictionary GetNamespacesFromSource(string source) { XPathDocument doc = new XPathDocument(new StringReader(source)); XPathNavigator namespaceNavigator = doc.CreateNavigator(); @@ -744,12 +757,12 @@ public void CanSerializeAndDeserializeAllExampleXmlFiles() { var t1 = assembly.GetTypes().SingleOrDefault(t => t.Name == c && t.Namespace.StartsWith("IS24RestApi.Offer.Realestates")); Assert.NotNull(t1); - var f = char.ToLower(c[0]) + c.Substring(1); + var f = char.ToLower(c[0]) + c[1..]; TestRoundtrip(t1, f); } } - void TestRoundtrip(Type t, string file) + static void TestRoundtrip(Type t, string file) { var serializer = new XmlSerializer(t); @@ -811,7 +824,7 @@ public void DontGenerateElementForEmptyCollectionInChoice() [Theory] [InlineData(CodeTypeReferenceOptions.GlobalReference, "[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]")] - [InlineData((CodeTypeReferenceOptions)0, "[System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)]")] + [InlineData((CodeTypeReferenceOptions)0, "[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]")] public void EditorBrowsableAttributeRespectsCodeTypeReferenceOptions(CodeTypeReferenceOptions codeTypeReferenceOptions, string expectedLine) { const string xsd = @" @@ -987,10 +1000,6 @@ public void ComplexTypeWithAttributeGroupExtension() // This code was generated by Tests version 1.0.0.1. namespace Test { - using System.Collections; - using System.Collections.Generic; - using System.Collections.ObjectModel; - using System.Xml.Serialization; [System.CodeDom.Compiler.GeneratedCodeAttribute(""Tests"", ""1.0.0.1"")] diff --git a/XmlSchemaClassGenerator/CodeUtilities.cs b/XmlSchemaClassGenerator/CodeUtilities.cs index 0a7c0257..e99d82a8 100644 --- a/XmlSchemaClassGenerator/CodeUtilities.cs +++ b/XmlSchemaClassGenerator/CodeUtilities.cs @@ -1,4 +1,5 @@ using System; +using System.CodeDom; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; @@ -34,24 +35,13 @@ public static string ToBackingField(this string propertyName, string privateFiel public static bool? IsDataTypeAttributeAllowed(this XmlSchemaDatatype type) { - bool? result; - switch (type.TypeCode) + bool? result = type.TypeCode switch { - case XmlTypeCode.AnyAtomicType: - // union - result = false; - break; - case XmlTypeCode.DateTime: - case XmlTypeCode.Time: - case XmlTypeCode.Date: - case XmlTypeCode.Base64Binary: - case XmlTypeCode.HexBinary: - result = true; - break; - default: - result = false; - break; - } + XmlTypeCode.AnyAtomicType => false,// union + XmlTypeCode.DateTime or XmlTypeCode.Time or XmlTypeCode.Date or XmlTypeCode.Base64Binary or XmlTypeCode.HexBinary => true, + _ => false, + }; + return result; } @@ -118,7 +108,7 @@ private static Type GetIntegerDerivedType(XmlSchemaDatatype type, GeneratorConfi return result; } - if (!(restrictions.SingleOrDefault(r => r is TotalDigitsRestrictionModel) is TotalDigitsRestrictionModel totalDigits) + if (restrictions.SingleOrDefault(r => r is TotalDigitsRestrictionModel) is not TotalDigitsRestrictionModel totalDigits || ((xmlTypeCode == XmlTypeCode.PositiveInteger || xmlTypeCode == XmlTypeCode.NonNegativeInteger) && totalDigits.Value >= 30) || ((xmlTypeCode == XmlTypeCode.Integer @@ -126,7 +116,7 @@ private static Type GetIntegerDerivedType(XmlSchemaDatatype type, GeneratorConfi || xmlTypeCode == XmlTypeCode.NonPositiveInteger) && totalDigits.Value >= 29)) { if (configuration.UseIntegerDataTypeAsFallback && configuration.IntegerDataType != null) - return configuration.IntegerDataType; + return configuration.IntegerDataType; return typeof(string); } @@ -184,40 +174,15 @@ private static Type GetIntegerDerivedType(XmlSchemaDatatype type, GeneratorConfi public static Type GetEffectiveType(this XmlSchemaDatatype type, GeneratorConfiguration configuration, IEnumerable restrictions, bool attribute = false) { - Type resultType; - - switch (type.TypeCode) + var resultType = type.TypeCode switch { - case XmlTypeCode.AnyAtomicType: - // union - resultType = typeof(string); - break; - case XmlTypeCode.AnyUri: - case XmlTypeCode.Duration: - case XmlTypeCode.GDay: - case XmlTypeCode.GMonth: - case XmlTypeCode.GMonthDay: - case XmlTypeCode.GYear: - case XmlTypeCode.GYearMonth: - resultType = typeof(string); - break; - case XmlTypeCode.Time: - resultType = typeof(DateTime); - break; - case XmlTypeCode.Idref: - resultType = typeof(string); - break; - case XmlTypeCode.Integer: - case XmlTypeCode.NegativeInteger: - case XmlTypeCode.NonNegativeInteger: - case XmlTypeCode.NonPositiveInteger: - case XmlTypeCode.PositiveInteger: - resultType = GetIntegerDerivedType(type, configuration, restrictions); - break; - default: - resultType = type.ValueType; - break; - } + XmlTypeCode.AnyAtomicType => typeof(string),// union + XmlTypeCode.AnyUri or XmlTypeCode.Duration or XmlTypeCode.GDay or XmlTypeCode.GMonth or XmlTypeCode.GMonthDay or XmlTypeCode.GYear or XmlTypeCode.GYearMonth => typeof(string), + XmlTypeCode.Time => typeof(DateTime), + XmlTypeCode.Idref => typeof(string), + XmlTypeCode.Integer or XmlTypeCode.NegativeInteger or XmlTypeCode.NonNegativeInteger or XmlTypeCode.NonPositiveInteger or XmlTypeCode.PositiveInteger => GetIntegerDerivedType(type, configuration, restrictions), + _ => type.ValueType, + }; if (type.Variety == XmlSchemaDatatypeVariety.List) { @@ -248,7 +213,7 @@ public static XmlQualifiedName GetQualifiedName(this XmlSchemaType schemaType) public static XmlQualifiedName GetQualifiedName(this TypeModel typeModel) { XmlQualifiedName qualifiedName; - if (!(typeModel is SimpleModel simpleTypeModel)) + if (typeModel is not SimpleModel simpleTypeModel) { if (typeModel.IsAnonymous) { @@ -398,5 +363,40 @@ public static KeyValuePair ParseNamespace(string nsArg, st } return new KeyValuePair(new NamespaceKey(source, xmlNs), netNs); } + + public static readonly List<(string Namespace, Func Condition)> UsingNamespaces = new List<(string, Func)> { + ("System", c => c.CompactTypeNames), + ("System.CodeDom.Compiler", c => c.CompactTypeNames), + ("System.Collections.Generic", c => c.CompactTypeNames), + ("System.Collections.ObjectModel", c => c.CompactTypeNames), + ("System.ComponentModel", c => c.CompactTypeNames), + ("System.ComponentModel.DataAnnotations", c => c.CompactTypeNames && (c.DataAnnotationMode != DataAnnotationMode.None || c.EntityFramework)), + ("System.Diagnostics", c => c.CompactTypeNames && c.GenerateDebuggerStepThroughAttribute), + ("System.Linq", c => c.EnableDataBinding), + ("System.Xml.Serialization", c => c.CompactTypeNames) + }; + + public static bool IsUsingNamespace(Type t, GeneratorConfiguration conf) => UsingNamespaces.Any(n => n.Namespace == t.Namespace && n.Condition(conf)); + + public static CodeTypeReference CreateTypeReference(Type t, GeneratorConfiguration conf) + { + if (IsUsingNamespace(t, conf)) + { + var name = t.Name; + var typeRef = new CodeTypeReference(name, conf.CodeTypeReferenceOptions); + + if (t.IsConstructedGenericType) + { + var typeArgs = t.GenericTypeArguments.Select(a => CreateTypeReference(a, conf)).ToArray(); + typeRef.TypeArguments.AddRange(typeArgs); + } + + var generic = t.IsGenericType || t.IsGenericTypeDefinition || t.IsConstructedGenericType; + + return typeRef; + } + else + return new CodeTypeReference(t, conf.CodeTypeReferenceOptions); + } } } \ No newline at end of file diff --git a/XmlSchemaClassGenerator/Generator.cs b/XmlSchemaClassGenerator/Generator.cs index 9ac725f2..20b73568 100644 --- a/XmlSchemaClassGenerator/Generator.cs +++ b/XmlSchemaClassGenerator/Generator.cs @@ -259,6 +259,12 @@ public bool SeparateSubstitutes set { _configuration.SeparateSubstitutes = value; } } + public bool CompactTypeNames + { + get { return _configuration.CompactTypeNames; } + set { _configuration.CompactTypeNames = value; } + } + static Generator() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); diff --git a/XmlSchemaClassGenerator/GeneratorConfiguration.cs b/XmlSchemaClassGenerator/GeneratorConfiguration.cs index 1c4a1df0..5acee3e9 100644 --- a/XmlSchemaClassGenerator/GeneratorConfiguration.cs +++ b/XmlSchemaClassGenerator/GeneratorConfiguration.cs @@ -240,17 +240,17 @@ public void WriteLog(string message) /// /// /// With false it generates the classes: - /// + /// /// /// public class books { /// public Container<componentType> components {get; set;} /// } /// - /// public class componentType {} + /// public class componentType {} /// /// /// With true it generates the classes: - /// + /// /// /// public class books { /// public Container<componentType> components {get; set;} @@ -260,7 +260,7 @@ public void WriteLog(string message) /// public Container<componentType> components {get; set;} /// } /// - /// public class componentType {} + /// public class componentType {} /// /// public bool GenerateComplexTypesForCollections { get; set; } = true; @@ -274,5 +274,10 @@ public void WriteLog(string message) /// Generates a separate property for each element of a substitution group /// public bool SeparateSubstitutes { get; set; } = false; + + /// + /// Generates type names without namespace qualifiers for namespaces in using list + /// + public bool CompactTypeNames { get; set; } } } diff --git a/XmlSchemaClassGenerator/ModelBuilder.cs b/XmlSchemaClassGenerator/ModelBuilder.cs index 8615e0f8..4990c880 100644 --- a/XmlSchemaClassGenerator/ModelBuilder.cs +++ b/XmlSchemaClassGenerator/ModelBuilder.cs @@ -1011,7 +1011,7 @@ public IEnumerable GenerateCode() var hierarchy = NamespaceHierarchyItem.Build(Namespaces.Values.GroupBy(x => x.Name).SelectMany(x => x)) .MarkAmbiguousNamespaceTypes(); return hierarchy.Flatten() - .Select(nhi => NamespaceModel.Generate(nhi.FullName, nhi.Models)); + .Select(nhi => NamespaceModel.Generate(nhi.FullName, nhi.Models, _configuration)); } private string BuildNamespace(Uri source, string xmlNamespace) diff --git a/XmlSchemaClassGenerator/RestrictionModel.cs b/XmlSchemaClassGenerator/RestrictionModel.cs index 6fbe2b3e..000e9bf9 100644 --- a/XmlSchemaClassGenerator/RestrictionModel.cs +++ b/XmlSchemaClassGenerator/RestrictionModel.cs @@ -89,7 +89,7 @@ public override DataAnnotationMode MinimumDataAnnotationMode public override CodeAttributeDeclaration GetAttribute() { - var a = new CodeAttributeDeclaration(new CodeTypeReference(typeof(StringLengthAttribute), Configuration.CodeTypeReferenceOptions), + var a = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(StringLengthAttribute), Configuration), new CodeAttributeArgument(Max > 0 ? (CodeExpression)new CodePrimitiveExpression(Max) : new CodeSnippetExpression("int.MaxValue"))); if (Min > 0) { a.Arguments.Add(new CodeAttributeArgument("MinimumLength", new CodePrimitiveExpression(Min))); } @@ -120,7 +120,7 @@ public override DataAnnotationMode MinimumDataAnnotationMode public override CodeAttributeDeclaration GetAttribute() { - return new CodeAttributeDeclaration(new CodeTypeReference(typeof(MaxLengthAttribute), Configuration.CodeTypeReferenceOptions), + return new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(MaxLengthAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(Value))); } } @@ -148,7 +148,7 @@ public override DataAnnotationMode MinimumDataAnnotationMode public override CodeAttributeDeclaration GetAttribute() { - return new CodeAttributeDeclaration(new CodeTypeReference(typeof(MinLengthAttribute), Configuration.CodeTypeReferenceOptions), + return new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(MinLengthAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(Value))); } } @@ -220,7 +220,7 @@ public override DataAnnotationMode MinimumDataAnnotationMode public override CodeAttributeDeclaration GetAttribute() { - return new CodeAttributeDeclaration(new CodeTypeReference(typeof(RegularExpressionAttribute), Configuration.CodeTypeReferenceOptions), + return new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(RegularExpressionAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(Value))); } } diff --git a/XmlSchemaClassGenerator/TypeModel.cs b/XmlSchemaClassGenerator/TypeModel.cs index 19cb2d43..84928b18 100644 --- a/XmlSchemaClassGenerator/TypeModel.cs +++ b/XmlSchemaClassGenerator/TypeModel.cs @@ -34,20 +34,14 @@ public NamespaceModel(NamespaceKey key, GeneratorConfiguration configuration) Types = new Dictionary(); } - public static CodeNamespace Generate(string namespaceName, IEnumerable parts) + public static CodeNamespace Generate(string namespaceName, IEnumerable parts, GeneratorConfiguration conf) { var codeNamespace = new CodeNamespace(namespaceName); - codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections")); - codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic")); - codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.ObjectModel")); - codeNamespace.Imports.Add(new CodeNamespaceImport("System.Xml.Serialization")); + + foreach (var (Namespace, Condition) in CodeUtilities.UsingNamespaces.Where(n => n.Condition(conf))) + codeNamespace.Imports.Add(new CodeNamespaceImport(Namespace)); var typeModels = parts.SelectMany(x => x.Types.Values).ToList(); - if (typeModels.OfType().Any(x => x.Configuration.EnableDataBinding)) - { - codeNamespace.Imports.Add(new CodeNamespaceImport("System.Linq")); - codeNamespace.Imports.Add(new CodeNamespaceImport("System.ComponentModel")); - } foreach (var typeModel in typeModels) { @@ -94,7 +88,7 @@ public static void AddDescription(CodeAttributeDeclarationCollection attributes, if (doc != null) { - var descriptionAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DescriptionAttribute), conf.CodeTypeReferenceOptions), + var descriptionAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(DescriptionAttribute), conf), new CodeAttributeArgument(new CodePrimitiveExpression(Regex.Replace(doc.Text, @"\s+", " ").Trim()))); attributes.Add(descriptionAttribute); } @@ -137,7 +131,7 @@ public virtual CodeTypeDeclaration Generate() DocumentationModel.AddDescription(typeDeclaration.CustomAttributes, Documentation, Configuration); - var generatedAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(GeneratedCodeAttribute), Configuration.CodeTypeReferenceOptions), + var generatedAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(GeneratedCodeAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(Configuration.Version.Title)), new CodeAttributeArgument(new CodePrimitiveExpression(Configuration.Version.Version))); typeDeclaration.CustomAttributes.Add(generatedAttribute); @@ -149,7 +143,7 @@ protected void GenerateTypeAttribute(CodeTypeDeclaration typeDeclaration) { if (XmlSchemaName != null) { - var typeAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlTypeAttribute), Configuration.CodeTypeReferenceOptions), + var typeAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlTypeAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(XmlSchemaName.Name)), new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(XmlSchemaName.Namespace))); if (IsAnonymous && (this is not ClassModel classModel || classModel.BaseClass == null)) @@ -167,7 +161,7 @@ protected void GenerateSerializableAttribute(CodeTypeDeclaration typeDeclaration if (Configuration.GenerateSerializableAttribute) { var serializableAttribute = - new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute), Configuration.CodeTypeReferenceOptions)); + new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(SerializableAttribute), Configuration)); typeDeclaration.CustomAttributes.Add(serializableAttribute); } } @@ -315,7 +309,7 @@ public override CodeTypeDeclaration Generate() var propertyChangedEvent = new CodeMemberEvent() { Name = "PropertyChanged", - Type = new CodeTypeReference(typeof(PropertyChangedEventHandler), Configuration.CodeTypeReferenceOptions), + Type = CodeUtilities.CreateTypeReference(typeof(PropertyChangedEventHandler), Configuration), Attributes = MemberAttributes.Public, }; classDeclaration.Members.Add(propertyChangedEvent); @@ -375,7 +369,7 @@ public override CodeTypeDeclaration Generate() var docs = new List { new DocumentationModel { Language = "en", Text = "Gets or sets the text value." }, new DocumentationModel { Language = "de", Text = "Ruft den Text ab oder legt diesen fest." } }; - var attribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlTextAttribute), Configuration.CodeTypeReferenceOptions)); + var attribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlTextAttribute), Configuration)); if (BaseClass is SimpleModel simpleModel) { @@ -411,7 +405,7 @@ public override CodeTypeDeclaration Generate() if (Configuration.EnableDataBinding) { - classDeclaration.BaseTypes.Add(new CodeTypeReference(typeof(INotifyPropertyChanged), Configuration.CodeTypeReferenceOptions)); + classDeclaration.BaseTypes.Add(CodeUtilities.CreateTypeReference(typeof(INotifyPropertyChanged), Configuration)); } if (Configuration.EntityFramework && !(BaseClass is ClassModel)) @@ -463,7 +457,7 @@ public override CodeTypeDeclaration Generate() // hack to generate automatic property text.Name += " { get; set; }"; text.Attributes = MemberAttributes.Public; - var xmlTextAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlTextAttribute), Configuration.CodeTypeReferenceOptions)); + var xmlTextAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlTextAttribute), Configuration)); text.CustomAttributes.Add(xmlTextAttribute); classDeclaration.Members.Add(text); @@ -479,18 +473,18 @@ public override CodeTypeDeclaration Generate() if (Configuration.GenerateDebuggerStepThroughAttribute) classDeclaration.CustomAttributes.Add( - new CodeAttributeDeclaration(new CodeTypeReference(typeof(DebuggerStepThroughAttribute), Configuration.CodeTypeReferenceOptions))); + new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(DebuggerStepThroughAttribute), Configuration))); if (Configuration.GenerateDesignerCategoryAttribute) { classDeclaration.CustomAttributes.Add( - new CodeAttributeDeclaration(new CodeTypeReference(typeof(DesignerCategoryAttribute), Configuration.CodeTypeReferenceOptions), + new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(DesignerCategoryAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression("code")))); } if (RootElementName != null) { - var rootAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlRootAttribute), Configuration.CodeTypeReferenceOptions), + var rootAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlRootAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(RootElementName.Name)), new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(RootElementName.Namespace))); classDeclaration.CustomAttributes.Add(rootAttribute); @@ -499,7 +493,7 @@ public override CodeTypeDeclaration Generate() var derivedTypes = GetAllDerivedTypes(); foreach (var derivedType in derivedTypes.OrderBy(t => t.Name)) { - var includeAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlIncludeAttribute), Configuration.CodeTypeReferenceOptions), + var includeAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlIncludeAttribute), Configuration), new CodeAttributeArgument(new CodeTypeOfExpression(derivedType.GetReferenceFor(Namespace)))); classDeclaration.CustomAttributes.Add(includeAttribute); } @@ -777,7 +771,7 @@ private void AddDocs(CodeTypeMember member) private CodeAttributeDeclaration CreateDefaultValueAttribute(CodeTypeReference typeReference, CodeExpression defaultValueExpression) { - var defaultValueAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultValueAttribute), Configuration.CodeTypeReferenceOptions)); + var defaultValueAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(DefaultValueAttribute), Configuration)); if (typeReference.BaseType == "System.Decimal") { defaultValueAttribute.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(typeof(decimal)))); @@ -800,7 +794,7 @@ public void AddInterfaceMembersTo(CodeTypeDeclaration typeDeclaration) if (isNullableValueType && Configuration.GenerateNullables) { - var nullableType = new CodeTypeReference(typeof(Nullable<>), Configuration.CodeTypeReferenceOptions); + var nullableType = CodeUtilities.CreateTypeReference(typeof(Nullable<>), Configuration); nullableType.TypeArguments.Add(typeReference); typeReference = nullableType; } @@ -845,7 +839,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi if (IsNillableValueType) { - var nullableType = new CodeTypeReference(typeof(Nullable<>), Configuration.CodeTypeReferenceOptions); + var nullableType = CodeUtilities.CreateTypeReference(typeof(Nullable<>), Configuration); nullableType.TypeArguments.Add(typeReference); backingField = new CodeMemberField(nullableType, OwningType.GetUniqueFieldName(this)); } @@ -857,8 +851,8 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi }; } - var ignoreAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlIgnoreAttribute), Configuration.CodeTypeReferenceOptions)); - var notMappedAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(NotMappedAttribute), Configuration.CodeTypeReferenceOptions)); + var ignoreAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlIgnoreAttribute), Configuration)); + var notMappedAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(NotMappedAttribute), Configuration)); backingField.CustomAttributes.Add(ignoreAttribute); if (requiresBackingField) @@ -877,16 +871,14 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi if (IsNillableValueType) { - var nullableType = new CodeTypeReference(typeof(Nullable<>), Configuration.CodeTypeReferenceOptions); + var nullableType = CodeUtilities.CreateTypeReference(typeof(Nullable<>), Configuration); nullableType.TypeArguments.Add(typeReference); member = new CodeMemberField(nullableType, propertyName); } else if (isNullableValueType && !IsAttribute && Configuration.UseShouldSerializePattern) { - var nullableType = new CodeTypeReference(typeof(Nullable<>), Configuration.CodeTypeReferenceOptions) - { - TypeArguments = { typeReference } - }; + var nullableType = CodeUtilities.CreateTypeReference(typeof(Nullable<>), Configuration); + nullableType.TypeArguments.Add(typeReference); member = new CodeMemberField(nullableType, propertyName); typeDeclaration.Members.Add(new CodeMemberMethod @@ -924,7 +916,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi if (IsNillableValueType) { - var nullableType = new CodeTypeReference(typeof(Nullable<>), Configuration.CodeTypeReferenceOptions); + var nullableType = CodeUtilities.CreateTypeReference(typeof(Nullable<>), Configuration); nullableType.TypeArguments.Add(typeReference); member = new CodeMemberField(nullableType, Name); } @@ -947,7 +939,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi if (!IsNullable && Configuration.DataAnnotationMode != DataAnnotationMode.None) { - var requiredAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(RequiredAttribute), Configuration.CodeTypeReferenceOptions)); + var requiredAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(RequiredAttribute), Configuration)); member.CustomAttributes.Add(requiredAttribute); } @@ -990,7 +982,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi if (generateNullablesProperty) { - var nullableType = new CodeTypeReference(typeof(Nullable<>), Configuration.CodeTypeReferenceOptions); + var nullableType = CodeUtilities.CreateTypeReference(typeof(Nullable<>), Configuration); nullableType.TypeArguments.Add(typeReference); var nullableMember = new CodeMemberProperty { @@ -1049,8 +1041,8 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi typeDeclaration.Members.Add(nullableMember); - var editorBrowsableAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(EditorBrowsableAttribute), Configuration.CodeTypeReferenceOptions)); - editorBrowsableAttribute.Arguments.Add(new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(EditorBrowsableState), CodeTypeReferenceOptions.GlobalReference)), "Never"))); + var editorBrowsableAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(EditorBrowsableAttribute), Configuration)); + editorBrowsableAttribute.Arguments.Add(new CodeAttributeArgument(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(CodeUtilities.CreateTypeReference(typeof(EditorBrowsableState), Configuration)), "Never"))); specifiedMember?.CustomAttributes.Add(editorBrowsableAttribute); member.CustomAttributes.Add(editorBrowsableAttribute); if (Configuration.EntityFramework) { member.CustomAttributes.Add(notMappedAttribute); } @@ -1062,7 +1054,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi { var specifiedProperty = new CodeMemberProperty { - Type = new CodeTypeReference(typeof(bool), Configuration.CodeTypeReferenceOptions), + Type = CodeUtilities.CreateTypeReference(typeof(bool), Configuration), Name = Name + "Specified", HasSet = false, HasGet = true, @@ -1137,7 +1129,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi // HACK: repackage as ArrayItemAttribute foreach (var propertyAttribute in propertyAttributes) { - var arrayItemAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlArrayItemAttribute), Configuration.CodeTypeReferenceOptions), + var arrayItemAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlArrayItemAttribute), Configuration), propertyAttribute.Arguments.Cast().Where(x => !string.Equals(x.Name, "Order", StringComparison.Ordinal)).ToArray()); var namespacePresent = arrayItemAttribute.Arguments.OfType().Any(a => a.Name == "Namespace"); if (!namespacePresent && !arrayItemProperty.XmlSchemaName.IsEmpty && !string.IsNullOrEmpty(arrayItemProperty.XmlSchemaName.Namespace)) @@ -1148,7 +1140,7 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi if (IsKey) { - var keyAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(KeyAttribute), Configuration.CodeTypeReferenceOptions)); + var keyAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(KeyAttribute), Configuration)); member.CustomAttributes.Add(keyAttribute); } @@ -1166,7 +1158,7 @@ private IEnumerable GetAttributes(bool isArray) if (IsKey && XmlSchemaName == null) { - attributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlIgnoreAttribute), Configuration.CodeTypeReferenceOptions))); + attributes.Add(new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlIgnoreAttribute), Configuration))); return attributes; } @@ -1174,14 +1166,14 @@ private IEnumerable GetAttributes(bool isArray) { if (IsAny) { - var anyAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlAnyAttributeAttribute), Configuration.CodeTypeReferenceOptions)); + var anyAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlAnyAttributeAttribute), Configuration)); if (Order != null) anyAttribute.Arguments.Add(new CodeAttributeArgument("Order", new CodePrimitiveExpression(Order.Value))); attributes.Add(anyAttribute); } else { - attributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlAttributeAttribute), Configuration.CodeTypeReferenceOptions), + attributes.Add(new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlAttributeAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(XmlSchemaName.Name)))); } } @@ -1189,7 +1181,7 @@ private IEnumerable GetAttributes(bool isArray) { if (IsAny) { - var anyAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlAnyElementAttribute), Configuration.CodeTypeReferenceOptions)); + var anyAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlAnyElementAttribute), Configuration)); if (Order != null) anyAttribute.Arguments.Add(new CodeAttributeArgument("Order", new CodePrimitiveExpression(Order.Value))); attributes.Add(anyAttribute); @@ -1200,7 +1192,7 @@ private IEnumerable GetAttributes(bool isArray) { foreach (var substitute in Substitutes) { - var substitutedAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlElementAttribute), Configuration.CodeTypeReferenceOptions), + var substitutedAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlElementAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(substitute.Element.QualifiedName.Name)), new CodeAttributeArgument("Type", new CodeTypeOfExpression(substitute.Type.GetReferenceFor(OwningType.Namespace))), new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(substitute.Element.QualifiedName.Namespace))); @@ -1215,7 +1207,7 @@ private IEnumerable GetAttributes(bool isArray) } } - var attribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlElementAttribute), Configuration.CodeTypeReferenceOptions), + var attribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlElementAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(XmlSchemaName.Name))); if (Order != null) { @@ -1227,7 +1219,7 @@ private IEnumerable GetAttributes(bool isArray) } else { - var arrayAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlArrayAttribute), Configuration.CodeTypeReferenceOptions), + var arrayAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlArrayAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(XmlSchemaName.Name))); if (Order != null) arrayAttribute.Arguments.Add(new CodeAttributeArgument("Order", new CodePrimitiveExpression(Order.Value))); @@ -1252,13 +1244,13 @@ private IEnumerable GetAttributes(bool isArray) } attribute.Arguments.Add(new CodeAttributeArgument("Form", - new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(XmlSchemaForm), Configuration.CodeTypeReferenceOptions)), + new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(CodeUtilities.CreateTypeReference(typeof(XmlSchemaForm), Configuration)), "Qualified"))); } else if (Form == XmlSchemaForm.Unqualified && !IsAttribute && !IsAny && XmlNamespace == null) { attribute.Arguments.Add(new CodeAttributeArgument("Form", - new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(XmlSchemaForm), Configuration.CodeTypeReferenceOptions)), + new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(CodeUtilities.CreateTypeReference(typeof(XmlSchemaForm), Configuration)), "Unqualified"))); } } @@ -1336,7 +1328,7 @@ public override CodeTypeDeclaration Generate() if (val.Name != val.Value) // illegal identifier chars in value { - var enumAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlEnumAttribute), Configuration.CodeTypeReferenceOptions), + var enumAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlEnumAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(val.Value))); member.CustomAttributes.Add(enumAttribute); } @@ -1356,7 +1348,7 @@ public override CodeTypeDeclaration Generate() if (RootElementName != null) { - var rootAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlRootAttribute), Configuration.CodeTypeReferenceOptions), + var rootAttribute = new CodeAttributeDeclaration(CodeUtilities.CreateTypeReference(typeof(XmlRootAttribute), Configuration), new CodeAttributeArgument(new CodePrimitiveExpression(RootElementName.Name)), new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(RootElementName.Namespace))); enumDeclaration.CustomAttributes.Add(rootAttribute); @@ -1388,14 +1380,14 @@ public SimpleModel(GeneratorConfiguration configuration) public static string GetCollectionDefinitionName(string typeName, GeneratorConfiguration configuration) { var type = configuration.CollectionType; - var typeRef = new CodeTypeReference(type, configuration.CodeTypeReferenceOptions); + var typeRef = CodeUtilities.CreateTypeReference(type, configuration); return GetFullTypeName(typeName, typeRef, type); } public static string GetCollectionImplementationName(string typeName, GeneratorConfiguration configuration) { var type = configuration.CollectionImplementationType ?? configuration.CollectionType; - var typeRef = new CodeTypeReference(type, configuration.CodeTypeReferenceOptions); + var typeRef = CodeUtilities.CreateTypeReference(type, configuration); return GetFullTypeName(typeName, typeRef, type); } @@ -1449,7 +1441,7 @@ public override CodeTypeReference GetReferenceFor(NamespaceModel referencingName type = collectionType; } - return new CodeTypeReference(type, Configuration.CodeTypeReferenceOptions); + return CodeUtilities.CreateTypeReference(type, Configuration); } public override CodeExpression GetDefaultValueFor(string defaultString, bool attribute) @@ -1475,7 +1467,7 @@ public override CodeExpression GetDefaultValueFor(string defaultString, bool att } else if (type == typeof(DateTime)) { - var rv = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(new CodeTypeReference(typeof(DateTime), Configuration.CodeTypeReferenceOptions)), + var rv = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(CodeUtilities.CreateTypeReference(typeof(DateTime), Configuration)), "Parse", new CodePrimitiveExpression(defaultString)); return rv; } @@ -1518,7 +1510,7 @@ public IEnumerable GetRestrictionAttributes() if (minInclusive != null && maxInclusive != null) { yield return new CodeAttributeDeclaration( - new CodeTypeReference(typeof(RangeAttribute), Configuration.CodeTypeReferenceOptions), + CodeUtilities.CreateTypeReference(typeof(RangeAttribute), Configuration), new CodeAttributeArgument(new CodeTypeOfExpression(minInclusive.Type)), new CodeAttributeArgument(new CodePrimitiveExpression(minInclusive.Value)), new CodeAttributeArgument(new CodePrimitiveExpression(maxInclusive.Value))); diff --git a/XmlSchemaClassGenerator/XmlSchemaClassGenerator.csproj b/XmlSchemaClassGenerator/XmlSchemaClassGenerator.csproj index f39fbbbf..f7a6049a 100644 --- a/XmlSchemaClassGenerator/XmlSchemaClassGenerator.csproj +++ b/XmlSchemaClassGenerator/XmlSchemaClassGenerator.csproj @@ -51,6 +51,7 @@ +