Skip to content

Commit bda2431

Browse files
author
Michael Ganss
committed
Fix sonar issues
1 parent 9462e05 commit bda2431

File tree

6 files changed

+64
-59
lines changed

6 files changed

+64
-59
lines changed

XmlSchemaClassGenerator.Console/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
namespace XmlSchemaClassGenerator.Console
1515
{
16-
class Program
16+
static class Program
1717
{
1818
static void Main(string[] args)
1919
{

XmlSchemaClassGenerator/FileOutputWriter.cs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,21 @@ public override void Write(CodeNamespace cn)
2727

2828
protected virtual void WriteFile(string path, CodeCompileUnit cu)
2929
{
30-
using (var fs = new FileStream(path, FileMode.Create))
31-
using (var writer = new StreamWriter(fs))
30+
FileStream fs = null;
31+
32+
try
33+
{
34+
fs = new FileStream(path, FileMode.Create);
35+
using (var writer = new StreamWriter(fs))
36+
{
37+
fs = null;
38+
Write(writer, cu);
39+
}
40+
}
41+
finally
3242
{
33-
Write(writer, cu);
43+
if (fs != null)
44+
fs.Dispose();
3445
}
3546
}
3647
}

XmlSchemaClassGenerator/ModelBuilder.cs

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public ModelBuilder(GeneratorConfiguration configuration, XmlSchemaSet set)
4848
{
4949
var schema = globalType.GetSchema();
5050
var source = string.IsNullOrEmpty(schema?.SourceUri) ? null : new Uri(schema.SourceUri);
51-
var type = CreateTypeModel(source, globalType, globalType.QualifiedName);
51+
CreateTypeModel(source, globalType, globalType.QualifiedName);
5252
}
5353

5454
foreach (var rootElement in set.GlobalElements.Values.Cast<XmlSchemaElement>())
@@ -60,7 +60,7 @@ public ModelBuilder(GeneratorConfiguration configuration, XmlSchemaSet set)
6060

6161
if (type.RootElementName != null)
6262
{
63-
if (type is ClassModel)
63+
if (type is ClassModel classModel)
6464
{
6565
// There is already another global element with this type.
6666
// Need to create an empty derived class.
@@ -81,7 +81,7 @@ public ModelBuilder(GeneratorConfiguration configuration, XmlSchemaSet set)
8181

8282
Types[rootElement.QualifiedName] = derivedClassModel;
8383

84-
derivedClassModel.BaseClass = (ClassModel)type;
84+
derivedClassModel.BaseClass = classModel;
8585
((ClassModel)derivedClassModel.BaseClass).DerivedTypes.Add(derivedClassModel);
8686

8787
derivedClassModel.RootElementName = rootElement.QualifiedName;
@@ -131,10 +131,10 @@ private TypeModel CreateTypeModel(Uri source, XmlSchemaAnnotated type, XmlQualif
131131
}
132132
else if (type is XmlSchemaSimpleType simpleType)
133133
{
134-
return CreateTypeModel(source, simpleType, namespaceModel, qualifiedName, docs);
134+
return CreateTypeModel(simpleType, namespaceModel, qualifiedName, docs);
135135
}
136136

137-
throw new Exception($"Cannot build declaration for {qualifiedName}");
137+
throw new NotSupportedException($"Cannot build declaration for {qualifiedName}");
138138
}
139139

140140
private TypeModel CreateTypeModel(Uri source, XmlSchemaGroup group, NamespaceModel namespaceModel, XmlQualifiedName qualifiedName, List<DocumentationModel> docs)
@@ -225,21 +225,19 @@ private TypeModel CreateTypeModel(Uri source, XmlSchemaComplexType complexType,
225225
{
226226
var baseModel = CreateTypeModel(source, complexType.BaseXmlSchemaType, complexType.BaseXmlSchemaType.QualifiedName);
227227
classModel.BaseClass = baseModel;
228-
if (baseModel is ClassModel) { ((ClassModel)classModel.BaseClass).DerivedTypes.Add(classModel); }
228+
if (baseModel is ClassModel baseClassModel) { baseClassModel.DerivedTypes.Add(classModel); }
229229
}
230230

231231
XmlSchemaParticle particle = null;
232232
if (classModel.BaseClass != null)
233233
{
234-
if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
234+
if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension complexContent)
235235
{
236-
particle = ((XmlSchemaComplexContentExtension)complexType.ContentModel.Content).Particle;
236+
particle = complexContent.Particle;
237237
}
238238

239239
// If it's a restriction, do not duplicate elements on the derived class, they're already in the base class.
240240
// See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
241-
//else if (complexType.ContentModel.Content is XmlSchemaComplexContentRestriction)
242-
// particle = ((XmlSchemaComplexContentRestriction)complexType.ContentModel.Content).Particle;
243241
}
244242
else particle = complexType.ContentTypeParticle;
245243

@@ -257,21 +255,17 @@ private TypeModel CreateTypeModel(Uri source, XmlSchemaComplexType complexType,
257255
XmlSchemaObjectCollection attributes = null;
258256
if (classModel.BaseClass != null)
259257
{
260-
if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
258+
if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension complexContent)
261259
{
262-
attributes = ((XmlSchemaComplexContentExtension)complexType.ContentModel.Content).Attributes;
260+
attributes = complexContent.Attributes;
263261
}
264-
else if (complexType.ContentModel.Content is XmlSchemaSimpleContentExtension)
262+
else if (complexType.ContentModel.Content is XmlSchemaSimpleContentExtension simpleContent)
265263
{
266-
attributes = ((XmlSchemaSimpleContentExtension)complexType.ContentModel.Content).Attributes;
264+
attributes = simpleContent.Attributes;
267265
}
268266

269267
// If it's a restriction, do not duplicate attributes on the derived class, they're already in the base class.
270268
// See https://msdn.microsoft.com/en-us/library/f3z3wh0y.aspx
271-
//else if (complexType.ContentModel.Content is XmlSchemaComplexContentRestriction)
272-
// attributes = ((XmlSchemaComplexContentRestriction)complexType.ContentModel.Content).Attributes;
273-
//else if (complexType.ContentModel.Content is XmlSchemaSimpleContentRestriction)
274-
// attributes = ((XmlSchemaSimpleContentRestriction)complexType.ContentModel.Content).Attributes;
275269
}
276270
else { attributes = complexType.Attributes; }
277271

@@ -309,7 +303,7 @@ private TypeModel CreateTypeModel(Uri source, XmlSchemaComplexType complexType,
309303
return classModel;
310304
}
311305

312-
private TypeModel CreateTypeModel(Uri source, XmlSchemaSimpleType simpleType, NamespaceModel namespaceModel, XmlQualifiedName qualifiedName, List<DocumentationModel> docs)
306+
private TypeModel CreateTypeModel(XmlSchemaSimpleType simpleType, NamespaceModel namespaceModel, XmlQualifiedName qualifiedName, List<DocumentationModel> docs)
313307
{
314308
var restrictions = new List<RestrictionModel>();
315309

@@ -714,7 +708,7 @@ private string BuildNamespace(Uri source, string xmlNamespace)
714708
return result;
715709
}
716710

717-
throw new Exception(string.Format("Namespace {0} not provided through map or generator.", xmlNamespace));
711+
throw new ArgumentException(string.Format("Namespace {0} not provided through map or generator.", xmlNamespace));
718712
}
719713

720714
private string ToTitleCase(string s)

XmlSchemaClassGenerator/NamespaceKey.cs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace XmlSchemaClassGenerator
88
{
9-
public class NamespaceKey : IComparable<NamespaceKey>, IEquatable<NamespaceKey>, IComparable
9+
public sealed class NamespaceKey : IComparable<NamespaceKey>, IEquatable<NamespaceKey>, IComparable
1010
{
1111
private const UriComponents CompareComponentsAbs = UriComponents.Host | UriComponents.Scheme | UriComponents.Path;
1212
private const UriFormat CompareFormat = UriFormat.Unescaped;
@@ -95,5 +95,25 @@ int IComparable.CompareTo(object obj)
9595
{
9696
return CompareTo((NamespaceKey)obj);
9797
}
98+
99+
public static bool operator ==(NamespaceKey left, NamespaceKey right)
100+
{
101+
if (left is null)
102+
return right is null;
103+
return left.Equals(right);
104+
}
105+
106+
public static bool operator >(NamespaceKey left, NamespaceKey right)
107+
{
108+
return left.CompareTo(right) > 0;
109+
}
110+
public static bool operator <(NamespaceKey left, NamespaceKey right)
111+
{
112+
return left.CompareTo(right) < 0;
113+
}
114+
public static bool operator !=(NamespaceKey left, NamespaceKey right)
115+
{
116+
return !(left == right);
117+
}
98118
}
99119
}

XmlSchemaClassGenerator/NamingExtensions.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@ public static class NamingExtensions
4343
['\x1D'] = "GroupSeparator",
4444
['\x1E'] = "RecordSeparator",
4545
['\x1F'] = "UnitSeparator",
46-
//invalidChars['\x20'] = "Space";
4746
['\x21'] = "ExclamationMark",
4847
['\x22'] = "Quote",
4948
['\x23'] = "Hash",
@@ -56,7 +55,6 @@ public static class NamingExtensions
5655
['\x2A'] = "Asterisk",
5756
['\x2B'] = "Plus",
5857
['\x2C'] = "Comma",
59-
//invalidChars['\x2D'] = "Minus";
6058
['\x2E'] = "Period",
6159
['\x2F'] = "Slash",
6260
['\x3A'] = "Colon",
@@ -70,7 +68,6 @@ public static class NamingExtensions
7068
['\x5C'] = "Backslash",
7169
['\x5D'] = "RightSquareBracket",
7270
['\x5E'] = "Caret",
73-
//invalidChars['\x5F'] = "Underscore";
7471
['\x60'] = "Backquote",
7572
['\x7B'] = "LeftCurlyBrace",
7673
['\x7C'] = "Pipe",

XmlSchemaClassGenerator/TypeModel.cs

Lines changed: 14 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ public static void AddDescription(CodeAttributeDeclarationCollection attributes,
102102
private static DocumentationModel GetSingleDoc(IEnumerable<DocumentationModel> docs)
103103
{
104104
if (docs.Count() == 1) return docs.Single();
105-
var englishDoc = docs.Where(d => string.IsNullOrEmpty(d.Language) || d.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
105+
var englishDoc = docs.FirstOrDefault(d => string.IsNullOrEmpty(d.Language) || d.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase));
106106
if (englishDoc != null) return englishDoc;
107107
return docs.FirstOrDefault();
108108
}
@@ -150,14 +150,11 @@ protected void GenerateTypeAttribute(CodeTypeDeclaration typeDeclaration)
150150
var typeAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlTypeAttribute), Configuration.CodeTypeReferenceOptions),
151151
new CodeAttributeArgument(new CodePrimitiveExpression(XmlSchemaName.Name)),
152152
new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(XmlSchemaName.Namespace)));
153-
if (IsAnonymous)
153+
if (IsAnonymous && (!(this is ClassModel classModel) || classModel.BaseClass == null))
154154
{
155155
// don't generate AnonymousType if it's derived class, otherwise XmlSerializer will
156156
// complain with "InvalidOperationException: Cannot include anonymous type '...'"
157-
if (!(this is ClassModel classModel) || classModel.BaseClass == null)
158-
{
159-
typeAttribute.Arguments.Add(new CodeAttributeArgument("AnonymousType", new CodePrimitiveExpression(true)));
160-
}
157+
typeAttribute.Arguments.Add(new CodeAttributeArgument("AnonymousType", new CodePrimitiveExpression(true)));
161158
}
162159
typeDeclaration.CustomAttributes.Add(typeAttribute);
163160
}
@@ -175,11 +172,17 @@ protected void GenerateSerializableAttribute(CodeTypeDeclaration typeDeclaration
175172

176173
public virtual CodeTypeReference GetReferenceFor(NamespaceModel referencingNamespace, bool collection, bool forInit = false)
177174
{
178-
var name = referencingNamespace == Namespace ? Name : string.Format("{2}{0}.{1}", Namespace.Name, Name, ((referencingNamespace ?? Namespace).IsAmbiguous ? "global::" : string.Empty));
175+
string name;
176+
if (referencingNamespace == Namespace)
177+
name = Name;
178+
else
179+
name = string.Format("{2}{0}.{1}", Namespace.Name, Name, ((referencingNamespace ?? Namespace).IsAmbiguous ? "global::" : string.Empty));
180+
179181
if (collection)
180182
{
181183
name = forInit ? SimpleModel.GetCollectionImplementationName(name, Configuration) : SimpleModel.GetCollectionDefinitionName(name, Configuration);
182184
}
185+
183186
return new CodeTypeReference(name);
184187
}
185188

@@ -650,12 +653,10 @@ public void AddInterfaceMembersTo(CodeTypeDeclaration typeDeclaration)
650653
{
651654
CodeTypeMember member;
652655

653-
var typeClassModel = TypeClassModel;
654656
var isArray = IsArray;
655657
var propertyType = PropertyType;
656658
var isNullableValueType = IsNullableValueType;
657659
var typeReference = TypeReference;
658-
var simpleType = propertyType as SimpleModel;
659660

660661
if (isNullableValueType && Configuration.GenerateNullables)
661662
{
@@ -699,7 +700,6 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi
699700
var propertyType = PropertyType;
700701
var isNullableValueType = IsNullableValueType;
701702
var typeReference = TypeReference;
702-
var simpleType = propertyType as SimpleModel;
703703

704704
var requiresBackingField = withDataBinding || DefaultValue != null || IsCollection || isArray;
705705
var backingField = new CodeMemberField(typeReference, OwningType.GetUniqueFieldName(this))
@@ -758,14 +758,11 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi
758758

759759
member.Name += GetAccessors(member.Name, backingField.Name, propertyType.GetPropertyValueTypeCode(), false, withDataBinding);
760760

761-
if (IsNullable)
761+
if (IsNullable && ((defaultValueExpression is CodePrimitiveExpression) || (defaultValueExpression is CodeFieldReferenceExpression)))
762762
{
763-
if ((defaultValueExpression is CodePrimitiveExpression) || (defaultValueExpression is CodeFieldReferenceExpression))
764-
{
765-
var defaultValueAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultValueAttribute), Configuration.CodeTypeReferenceOptions),
766-
new CodeAttributeArgument(defaultValueExpression));
767-
member.CustomAttributes.Add(defaultValueAttribute);
768-
}
763+
var defaultValueAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultValueAttribute), Configuration.CodeTypeReferenceOptions),
764+
new CodeAttributeArgument(defaultValueExpression));
765+
member.CustomAttributes.Add(defaultValueAttribute);
769766
}
770767
}
771768

@@ -777,8 +774,6 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi
777774
if (IsDeprecated)
778775
{
779776
// From .NET 3.5 XmlSerializer doesn't serialize objects with [Obsolete] >(
780-
//var deprecatedAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute)));
781-
//member.CustomAttributes.Add(deprecatedAttribute);
782777
}
783778

784779
if (isNullableValueType)
@@ -802,16 +797,6 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi
802797

803798
if (Configuration.GenerateNullables)
804799
{
805-
// public X? Name
806-
// {
807-
// get { return NameSpecified ? NameValue : null; }
808-
// set
809-
// {
810-
// NameValue = value.GetValueOrDefault();
811-
// NameSpecified = value.HasValue;
812-
// }
813-
// }
814-
815800
var nullableType = new CodeTypeReference(typeof(Nullable<>), Configuration.CodeTypeReferenceOptions);
816801
nullableType.TypeArguments.Add(typeReference);
817802
var nullableMember = new CodeMemberProperty
@@ -1110,8 +1095,6 @@ public override CodeTypeDeclaration Generate()
11101095
if (val.IsDeprecated)
11111096
{
11121097
// From .NET 3.5 XmlSerializer doesn't serialize objects with [Obsolete] >(
1113-
//var deprecatedAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute)));
1114-
//member.CustomAttributes.Add(deprecatedAttribute);
11151098

11161099
var obsolete = new DocumentationModel { Language = "en", Text = "[Obsolete]" };
11171100
docs.Add(obsolete);

0 commit comments

Comments
 (0)