Skip to content

Commit

Permalink
Fix sonar issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Ganss committed Sep 24, 2018
1 parent 9462e05 commit bda2431
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 59 deletions.
2 changes: 1 addition & 1 deletion XmlSchemaClassGenerator.Console/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

namespace XmlSchemaClassGenerator.Console
{
class Program
static class Program
{
static void Main(string[] args)
{
Expand Down
17 changes: 14 additions & 3 deletions XmlSchemaClassGenerator/FileOutputWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,21 @@ public override void Write(CodeNamespace cn)

protected virtual void WriteFile(string path, CodeCompileUnit cu)
{
using (var fs = new FileStream(path, FileMode.Create))
using (var writer = new StreamWriter(fs))
FileStream fs = null;

try
{
fs = new FileStream(path, FileMode.Create);
using (var writer = new StreamWriter(fs))
{
fs = null;
Write(writer, cu);
}
}
finally
{
Write(writer, cu);
if (fs != null)
fs.Dispose();
}
}
}
Expand Down
34 changes: 14 additions & 20 deletions XmlSchemaClassGenerator/ModelBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public ModelBuilder(GeneratorConfiguration configuration, XmlSchemaSet set)
{
var schema = globalType.GetSchema();
var source = string.IsNullOrEmpty(schema?.SourceUri) ? null : new Uri(schema.SourceUri);
var type = CreateTypeModel(source, globalType, globalType.QualifiedName);
CreateTypeModel(source, globalType, globalType.QualifiedName);
}

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

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

Types[rootElement.QualifiedName] = derivedClassModel;

derivedClassModel.BaseClass = (ClassModel)type;
derivedClassModel.BaseClass = classModel;
((ClassModel)derivedClassModel.BaseClass).DerivedTypes.Add(derivedClassModel);

derivedClassModel.RootElementName = rootElement.QualifiedName;
Expand Down Expand Up @@ -131,10 +131,10 @@ private TypeModel CreateTypeModel(Uri source, XmlSchemaAnnotated type, XmlQualif
}
else if (type is XmlSchemaSimpleType simpleType)
{
return CreateTypeModel(source, simpleType, namespaceModel, qualifiedName, docs);
return CreateTypeModel(simpleType, namespaceModel, qualifiedName, docs);
}

throw new Exception($"Cannot build declaration for {qualifiedName}");
throw new NotSupportedException($"Cannot build declaration for {qualifiedName}");
}

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

XmlSchemaParticle particle = null;
if (classModel.BaseClass != null)
{
if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension complexContent)
{
particle = ((XmlSchemaComplexContentExtension)complexType.ContentModel.Content).Particle;
particle = complexContent.Particle;
}

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

Expand All @@ -257,21 +255,17 @@ private TypeModel CreateTypeModel(Uri source, XmlSchemaComplexType complexType,
XmlSchemaObjectCollection attributes = null;
if (classModel.BaseClass != null)
{
if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
if (complexType.ContentModel.Content is XmlSchemaComplexContentExtension complexContent)
{
attributes = ((XmlSchemaComplexContentExtension)complexType.ContentModel.Content).Attributes;
attributes = complexContent.Attributes;
}
else if (complexType.ContentModel.Content is XmlSchemaSimpleContentExtension)
else if (complexType.ContentModel.Content is XmlSchemaSimpleContentExtension simpleContent)
{
attributes = ((XmlSchemaSimpleContentExtension)complexType.ContentModel.Content).Attributes;
attributes = simpleContent.Attributes;
}

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

Expand Down Expand Up @@ -309,7 +303,7 @@ private TypeModel CreateTypeModel(Uri source, XmlSchemaComplexType complexType,
return classModel;
}

private TypeModel CreateTypeModel(Uri source, XmlSchemaSimpleType simpleType, NamespaceModel namespaceModel, XmlQualifiedName qualifiedName, List<DocumentationModel> docs)
private TypeModel CreateTypeModel(XmlSchemaSimpleType simpleType, NamespaceModel namespaceModel, XmlQualifiedName qualifiedName, List<DocumentationModel> docs)
{
var restrictions = new List<RestrictionModel>();

Expand Down Expand Up @@ -714,7 +708,7 @@ private string BuildNamespace(Uri source, string xmlNamespace)
return result;
}

throw new Exception(string.Format("Namespace {0} not provided through map or generator.", xmlNamespace));
throw new ArgumentException(string.Format("Namespace {0} not provided through map or generator.", xmlNamespace));
}

private string ToTitleCase(string s)
Expand Down
22 changes: 21 additions & 1 deletion XmlSchemaClassGenerator/NamespaceKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace XmlSchemaClassGenerator
{
public class NamespaceKey : IComparable<NamespaceKey>, IEquatable<NamespaceKey>, IComparable
public sealed class NamespaceKey : IComparable<NamespaceKey>, IEquatable<NamespaceKey>, IComparable
{
private const UriComponents CompareComponentsAbs = UriComponents.Host | UriComponents.Scheme | UriComponents.Path;
private const UriFormat CompareFormat = UriFormat.Unescaped;
Expand Down Expand Up @@ -95,5 +95,25 @@ int IComparable.CompareTo(object obj)
{
return CompareTo((NamespaceKey)obj);
}

public static bool operator ==(NamespaceKey left, NamespaceKey right)
{
if (left is null)
return right is null;
return left.Equals(right);
}

public static bool operator >(NamespaceKey left, NamespaceKey right)
{
return left.CompareTo(right) > 0;
}
public static bool operator <(NamespaceKey left, NamespaceKey right)
{
return left.CompareTo(right) < 0;
}
public static bool operator !=(NamespaceKey left, NamespaceKey right)
{
return !(left == right);
}
}
}
3 changes: 0 additions & 3 deletions XmlSchemaClassGenerator/NamingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ public static class NamingExtensions
['\x1D'] = "GroupSeparator",
['\x1E'] = "RecordSeparator",
['\x1F'] = "UnitSeparator",
//invalidChars['\x20'] = "Space";
['\x21'] = "ExclamationMark",
['\x22'] = "Quote",
['\x23'] = "Hash",
Expand All @@ -56,7 +55,6 @@ public static class NamingExtensions
['\x2A'] = "Asterisk",
['\x2B'] = "Plus",
['\x2C'] = "Comma",
//invalidChars['\x2D'] = "Minus";
['\x2E'] = "Period",
['\x2F'] = "Slash",
['\x3A'] = "Colon",
Expand All @@ -70,7 +68,6 @@ public static class NamingExtensions
['\x5C'] = "Backslash",
['\x5D'] = "RightSquareBracket",
['\x5E'] = "Caret",
//invalidChars['\x5F'] = "Underscore";
['\x60'] = "Backquote",
['\x7B'] = "LeftCurlyBrace",
['\x7C'] = "Pipe",
Expand Down
45 changes: 14 additions & 31 deletions XmlSchemaClassGenerator/TypeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public static void AddDescription(CodeAttributeDeclarationCollection attributes,
private static DocumentationModel GetSingleDoc(IEnumerable<DocumentationModel> docs)
{
if (docs.Count() == 1) return docs.Single();
var englishDoc = docs.Where(d => string.IsNullOrEmpty(d.Language) || d.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
var englishDoc = docs.FirstOrDefault(d => string.IsNullOrEmpty(d.Language) || d.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase));
if (englishDoc != null) return englishDoc;
return docs.FirstOrDefault();
}
Expand Down Expand Up @@ -150,14 +150,11 @@ protected void GenerateTypeAttribute(CodeTypeDeclaration typeDeclaration)
var typeAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(XmlTypeAttribute), Configuration.CodeTypeReferenceOptions),
new CodeAttributeArgument(new CodePrimitiveExpression(XmlSchemaName.Name)),
new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(XmlSchemaName.Namespace)));
if (IsAnonymous)
if (IsAnonymous && (!(this is ClassModel classModel) || classModel.BaseClass == null))
{
// don't generate AnonymousType if it's derived class, otherwise XmlSerializer will
// complain with "InvalidOperationException: Cannot include anonymous type '...'"
if (!(this is ClassModel classModel) || classModel.BaseClass == null)
{
typeAttribute.Arguments.Add(new CodeAttributeArgument("AnonymousType", new CodePrimitiveExpression(true)));
}
typeAttribute.Arguments.Add(new CodeAttributeArgument("AnonymousType", new CodePrimitiveExpression(true)));
}
typeDeclaration.CustomAttributes.Add(typeAttribute);
}
Expand All @@ -175,11 +172,17 @@ protected void GenerateSerializableAttribute(CodeTypeDeclaration typeDeclaration

public virtual CodeTypeReference GetReferenceFor(NamespaceModel referencingNamespace, bool collection, bool forInit = false)
{
var name = referencingNamespace == Namespace ? Name : string.Format("{2}{0}.{1}", Namespace.Name, Name, ((referencingNamespace ?? Namespace).IsAmbiguous ? "global::" : string.Empty));
string name;
if (referencingNamespace == Namespace)
name = Name;
else
name = string.Format("{2}{0}.{1}", Namespace.Name, Name, ((referencingNamespace ?? Namespace).IsAmbiguous ? "global::" : string.Empty));

if (collection)
{
name = forInit ? SimpleModel.GetCollectionImplementationName(name, Configuration) : SimpleModel.GetCollectionDefinitionName(name, Configuration);
}

return new CodeTypeReference(name);
}

Expand Down Expand Up @@ -650,12 +653,10 @@ public void AddInterfaceMembersTo(CodeTypeDeclaration typeDeclaration)
{
CodeTypeMember member;

var typeClassModel = TypeClassModel;
var isArray = IsArray;
var propertyType = PropertyType;
var isNullableValueType = IsNullableValueType;
var typeReference = TypeReference;
var simpleType = propertyType as SimpleModel;

if (isNullableValueType && Configuration.GenerateNullables)
{
Expand Down Expand Up @@ -699,7 +700,6 @@ public void AddMembersTo(CodeTypeDeclaration typeDeclaration, bool withDataBindi
var propertyType = PropertyType;
var isNullableValueType = IsNullableValueType;
var typeReference = TypeReference;
var simpleType = propertyType as SimpleModel;

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

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

if (IsNullable)
if (IsNullable && ((defaultValueExpression is CodePrimitiveExpression) || (defaultValueExpression is CodeFieldReferenceExpression)))
{
if ((defaultValueExpression is CodePrimitiveExpression) || (defaultValueExpression is CodeFieldReferenceExpression))
{
var defaultValueAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultValueAttribute), Configuration.CodeTypeReferenceOptions),
new CodeAttributeArgument(defaultValueExpression));
member.CustomAttributes.Add(defaultValueAttribute);
}
var defaultValueAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(DefaultValueAttribute), Configuration.CodeTypeReferenceOptions),
new CodeAttributeArgument(defaultValueExpression));
member.CustomAttributes.Add(defaultValueAttribute);
}
}

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

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

if (Configuration.GenerateNullables)
{
// public X? Name
// {
// get { return NameSpecified ? NameValue : null; }
// set
// {
// NameValue = value.GetValueOrDefault();
// NameSpecified = value.HasValue;
// }
// }

var nullableType = new CodeTypeReference(typeof(Nullable<>), Configuration.CodeTypeReferenceOptions);
nullableType.TypeArguments.Add(typeReference);
var nullableMember = new CodeMemberProperty
Expand Down Expand Up @@ -1110,8 +1095,6 @@ public override CodeTypeDeclaration Generate()
if (val.IsDeprecated)
{
// From .NET 3.5 XmlSerializer doesn't serialize objects with [Obsolete] >(
//var deprecatedAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute)));
//member.CustomAttributes.Add(deprecatedAttribute);

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

0 comments on commit bda2431

Please sign in to comment.