Skip to content

Commit

Permalink
Resolve Null Reference issues
Browse files Browse the repository at this point in the history
  • Loading branch information
moh-hassan committed Aug 28, 2021
1 parent d09cfd8 commit 349b6a5
Show file tree
Hide file tree
Showing 19 changed files with 70 additions and 107 deletions.
16 changes: 2 additions & 14 deletions Directory.Build.props
Expand Up @@ -16,7 +16,7 @@
<PackageReleaseNotes>https://github.com/moh-hassan/odata2poco/blob/master/ReleaseNotes.md </PackageReleaseNotes>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<NoWarn>$(NoWarn);1570;1572;1573;1587;NU5128</NoWarn>
<LangVersion>8.0</LangVersion>
<LangVersion>9.0</LangVersion>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<Version Condition="'$(VersionSuffix)' != ''">$(VersionSuffix)</Version>
<Version Condition="'$(VersionSuffix)' == ''">0.0.0</Version>
Expand All @@ -33,19 +33,7 @@
<IsWindows Condition="'$(OS)' == 'Windows_NT'">true</IsWindows>
</PropertyGroup>

<!-- version -->
<!--<PropertyGroup>
<Version>3.4.0-preview1</Version>
<AssemblyVersion>3.4.0.0</AssemblyVersion>
</PropertyGroup>-->


<ItemGroup Condition="'$(IsTestProject)' == 'true'">
<PackageReference Include="nunit" Version="3.11.0" />
<PackageReference Include="NUnit3TestAdapter" Version="3.13.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.0.1" />
</ItemGroup>


<ItemGroup>
<None Include="$(SolutionDir)license.txt" Pack="true" PackagePath=""/>
<None Include="$(SolutionDir)art\ODataLogo-128.png" Pack="true" PackagePath="" />
Expand Down
2 changes: 1 addition & 1 deletion Fake/projectTestData.cs
Expand Up @@ -9,7 +9,7 @@ public static string BaseDirectory
get
{
var assembly = Assembly.GetExecutingAssembly();
var codebase = new Uri(assembly.CodeBase);
var codebase = new Uri(assembly.Location);
var path = codebase.LocalPath;
return Path.GetDirectoryName(path);
}
Expand Down
Expand Up @@ -24,9 +24,9 @@
<ProjectReference Include="..\OData2PocoLib\OData2Poco.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Update="nunit" Version="3.13.2" />
<PackageReference Update="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="nunit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
</ItemGroup>

</Project>
6 changes: 3 additions & 3 deletions OData2Poco.CommandLine.Test/ProgramTests.cs
Expand Up @@ -80,10 +80,10 @@ public async Task PocoSettingTest(string url, string version, int n)
//Arrange
var a = $"-r {url} -v -a key tab req -n -b";
//Act
var tuble = await RunCommand(a);
var output = tuble.Item2;
var tuple = await RunCommand(a);
var output = tuple.Item2;
//Assert
Assert.AreEqual(0, tuble.Item1);
Assert.AreEqual(0, tuple.Item1);

Assert.That(output, Does.Contain("public partial class Product"));
Assert.That(output, Does.Contain("[Table(\"Products\")]")); //-a tab/ -t
Expand Down
4 changes: 2 additions & 2 deletions OData2Poco.CommandLine/ilmerge.targets
Expand Up @@ -19,8 +19,8 @@

<Target Name="ILMerge" AfterTargets="Build" Condition="'$(OS)' == 'Windows_NT' and '$(Configuration)' == 'Release'">
<ItemGroup>
<ILMergePackage Include="$(NuGetPackageRoot)\ilmerge\3.0.21\**\ilmerge.exe" />
<ILMergePackage Include="/home/travis/.nuget/packages/ilmerge/3.0.21/**/ilmerge.exe" Condition=" '$(OS)' == 'Unix' "/>
<ILMergePackage Include="$(NuGetPackageRoot)\ilmerge\3.0.41\**\ilmerge.exe" />
<ILMergePackage Include="/home/travis/.nuget/packages/ilmerge/3.0.41/**/ilmerge.exe" Condition=" '$(OS)' == 'Unix' "/>
<!--<ILMergePackage Include="$(SolutionDir)tools\ilmerge\tools\net452\ilmerge.exe" />-->
</ItemGroup>

Expand Down
6 changes: 3 additions & 3 deletions OData2Poco.Tests/OData2Poco.Tests.csproj
Expand Up @@ -37,8 +37,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Update="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Update="nunit" Version="3.13.2" />
<PackageReference Update="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="nunit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion OData2PocoLib/Api/O2P.cs
Expand Up @@ -13,7 +13,7 @@ public class O2P
internal MetaDataInfo MetaData { get; set; }
public string MetaDataAsString => MetaData.MetaDataAsString;
public string MetaDataVersion => MetaData.MetaDataVersion;
public string SchemaNamespace => MetaData.SchemaNamespace;
public string? SchemaNamespace => MetaData.SchemaNamespace;
public Dictionary<string, string> ServiceHeader => MetaData.ServiceHeader;

public string CodeText { get; set; }
Expand Down
22 changes: 7 additions & 15 deletions OData2PocoLib/CustAttributes/AttributeFactory.cs
Expand Up @@ -49,29 +49,21 @@ public AttributeFactory Init(PocoSetting? setting=null)
return this;
}

private INamedAttribute GetAttributeObject(string attName) => _pocoAttributesList[attName];
private INamedAttribute? GetAttributeObject(string attName) => _pocoAttributesList[attName];


public List<string> GetAttributes(object property, string attName)
{
if (attName.StartsWith("[") && property is PropertyTemplate)
return new List<string> { attName };

INamedAttribute attributeObject = GetAttributeObject(attName);
switch (property)
var attributeObject = GetAttributeObject(attName);
return property switch
{
case PropertyTemplate p:
return attributeObject != null
? attributeObject.GetAttributes(p)
: new List<string>();

case ClassTemplate c:
return attributeObject != null
? attributeObject.GetAttributes(c)
: new List<string>();
default:
throw new Exception($"{property.GetType()} isn't supported for named attributes");
}
PropertyTemplate p => attributeObject != null ? attributeObject.GetAttributes(p) : new List<string>(),
ClassTemplate c => attributeObject != null ? attributeObject.GetAttributes(c) : new List<string>(),
_ => throw new Exception($"{property.GetType()} isn't supported for named attributes")
};
}

public List<string> GetAttributes(object property, List<string> attNames)
Expand Down
4 changes: 2 additions & 2 deletions OData2PocoLib/CustAttributes/PocoAttributesList.cs
Expand Up @@ -10,7 +10,7 @@ namespace OData2Poco.CustAttributes
public class PocoAttributesList : IEnumerable<INamedAttribute>
{
readonly List<INamedAttribute> _namedAttributes; //= new List<ICustomeAttribute>();
public INamedAttribute this[string index] => GetAttributeObject(index);
public INamedAttribute? this[string index] => GetAttributeObject(index);

public PocoAttributesList()
{
Expand All @@ -33,7 +33,7 @@ IEnumerator IEnumerable.GetEnumerator()
return GetEnumerator();
}

public INamedAttribute GetAttributeObject(string attName)
public INamedAttribute? GetAttributeObject(string attName)
{
return _namedAttributes.FirstOrDefault(x => x.Name == attName);
}
Expand Down
28 changes: 6 additions & 22 deletions OData2PocoLib/Extensions/StringExtensions.cs
Expand Up @@ -54,16 +54,12 @@ public static string ToCamelCase(this string text)
}
public static string ChangeCase(this string text, CaseEnum caseEnum)
{
switch (caseEnum)
return caseEnum switch
{
case CaseEnum.Pas:
return text.ToPascalCase();
case CaseEnum.Camel:
return text.ToCamelCase();
default:
return text;

}
CaseEnum.Pas => text.ToPascalCase(),
CaseEnum.Camel => text.ToCamelCase(),
_ => text
};
}
/// <summary>
/// remove extra white spaces and keeping CRLF if needed
Expand Down Expand Up @@ -143,19 +139,7 @@ public static bool ValidateJson(this string json)
}
}

/// <summary>
/// Convert Json string to Typed object
/// </summary>
/// <param name="json"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T ToObject<T>(this string json)
{
var deserializedObject = JsonConvert.DeserializeObject<T>(json);
return deserializedObject;

}


public static string Quote(this string text, char c = '"') => $"{c}{text}{c}";

public static string UnQuote(this string text)
Expand Down
14 changes: 7 additions & 7 deletions OData2PocoLib/Helper.cs
Expand Up @@ -96,7 +96,7 @@ public static string GetServiceVersion(Dictionary<string, string> header)
/// </summary>
/// <param name="metadataString">XML MetaData</param>
/// <returns></returns>
public static string GetNameSpace(string metadataString)
public static string? GetNameSpace(string metadataString)
{
if (string.IsNullOrEmpty(metadataString)) return "MyNameSpace";
var reader = XmlReader.Create(new StringReader(metadataString));
Expand All @@ -117,17 +117,17 @@ public static bool CompareStringIgnoringSpaceCr(string text1, string text2)
string fixedStringOne = text1.TrimAllSpace(); // Regex.Replace(text1.Trim(), @"\s+", " ");
string fixedStringTwo = text2.TrimAllSpace(); // Regex.Replace(text2.Trim(), @"\s+", " ");
//Debug.WriteLine("{0}\n{1}\n",fixedStringOne,fixedStringTwo);
bool isEqual = String.Equals(fixedStringOne, fixedStringTwo, StringComparison.OrdinalIgnoreCase);
bool isEqual = string.Equals(fixedStringOne, fixedStringTwo, StringComparison.OrdinalIgnoreCase);
return isEqual;
}

public static string GetEmbeddedResource(string ns, string res)
{
using (var reader = new StreamReader(Assembly.GetExecutingAssembly()
.GetManifestResourceStream($"{ns}.{res}") ?? throw new InvalidOperationException()))
{
return reader.ReadToEnd();
}
using var reader = new StreamReader(Assembly
.GetExecutingAssembly()
.GetManifestResourceStream($"{ns}.{res}")
?? throw new InvalidOperationException());
return reader.ReadToEnd();
}
/// <summary>
/// find plugin dlls at runtime
Expand Down
10 changes: 5 additions & 5 deletions OData2PocoLib/Http/TokenEndPoint.cs
Expand Up @@ -48,9 +48,8 @@ public TokenEndpoint(OdataConnectionString odataConnectionString)

private string SetTokenParams(OdataConnectionString odataConnectionString)
{
var tokenParams = "";
var clientParams = $"grant_type=client_credentials&client_id={odataConnectionString.UserName}&client_secret={odataConnectionString.Password}";
tokenParams = string.IsNullOrEmpty(odataConnectionString.TokenParams)
string tokenParams = string.IsNullOrEmpty(odataConnectionString.TokenParams)
? clientParams
: $"{clientParams}&{odataConnectionString.TokenParams}";

Expand All @@ -76,10 +75,11 @@ private string SetTokenParams(OdataConnectionString odataConnectionString)
access_token : bi05REFMcXdodUhZbkhRNjNHZUNYYyIsImtpZCI6Ik4tbEMwbi05REFMcXdod...
*/
public async Task<string?> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
public async Task<string?> GetToken(Uri authenticationUrl,
Dictionary<string, string> authenticationCredentials)
{
var client = new HttpClient();
var content = new FormUrlEncodedContent(authenticationCredentials);
var content = new FormUrlEncodedContent(authenticationCredentials!);
var response = await client.PostAsync(authenticationUrl, content);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception($"Fail to get access_token, Http status code: ({(int)response.StatusCode}) {response.StatusCode}");
Expand Down Expand Up @@ -107,7 +107,7 @@ internal DateTime ExpiresOn()
{
if (string.IsNullOrEmpty(content) || string.IsNullOrEmpty(key))
return null;
var token = JObject.Parse(content).SelectToken(key);
var token = JObject.Parse(content!).SelectToken(key);
return token?.ToString();

}
Expand Down
2 changes: 1 addition & 1 deletion OData2PocoLib/MetaDataInfo.cs
Expand Up @@ -8,7 +8,7 @@ public class MetaDataInfo
public string MetaDataAsString { get; set; } = null!;
public string MetaDataVersion { get; set; } = null!;
public string ServiceVersion { get; set; } = null!;//for http media
public string SchemaNamespace { get; set; } = null!;
public string? SchemaNamespace { get; set; } = null!;
public Dictionary<string, string> ServiceHeader { get; set; }
public Media MediaType { get; set; }

Expand Down
15 changes: 7 additions & 8 deletions OData2PocoLib/MetaDataReader.cs
Expand Up @@ -34,7 +34,8 @@ public static async Task<MetaDataInfo> LoadMetaDataHttpAsync(OdataConnectionStri
if (client.Response != null)
foreach (var entry in client.Response.Headers)
{
string value = entry.Value.FirstOrDefault();
var value = entry.Value.FirstOrDefault();
if (value == null) continue;
string key = entry.Key;
metaData.ServiceHeader.Add(key, value);
}
Expand Down Expand Up @@ -67,13 +68,11 @@ public static async Task<MetaDataInfo> LoadMetadataAsync(OdataConnectionString o
MetaDataInfo metaData;
if (!odataConnString.ServiceUrl.StartsWith("http"))
{
using (StreamReader reader = new StreamReader(odataConnString.ServiceUrl))
{
var xml = await reader.ReadToEndAsync();
metaData = LoadMetaDataFromXml(xml);
metaData.ServiceUrl = odataConnString.ServiceUrl;
return metaData;
}
using StreamReader reader = new StreamReader(odataConnString.ServiceUrl);
var xml = await reader.ReadToEndAsync();
metaData = LoadMetaDataFromXml(xml);
metaData.ServiceUrl = odataConnString.ServiceUrl;
return metaData;
}

metaData = await LoadMetaDataHttpAsync(odataConnString);
Expand Down
8 changes: 4 additions & 4 deletions OData2PocoLib/OData2Poco.csproj
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461;net45</TargetFrameworks>
<TargetFrameworks>net5.0;netstandard2.0;net461;net45</TargetFrameworks>
<RootNamespace>OData2Poco</RootNamespace>
<AssemblyName>OData2Poco</AssemblyName>
<Authors>Mohamed Hassan</Authors>
Expand All @@ -9,7 +9,7 @@
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<Nullable>enable</Nullable>
<WarningsAsErrors>CS8600;CS8602;CS8603</WarningsAsErrors>
<!--<WarningsAsErrors>CS8600;CS8602;CS8603</WarningsAsErrors>-->
<Description>
"OData2Poco is a class library supporting netstandard2 and .NET 4.5+ to generate plain-old CLR objects (POCO) from OData feeds that implement both V1-3 and V4 OData protocol,based on the metadata of the service stored on the server. POCO classes can be used in typed RESTful client OData services"
</Description>
Expand All @@ -30,7 +30,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.Data.Edm" Version="5.8.4" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.1 " />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />

</ItemGroup>

Expand Down Expand Up @@ -67,7 +67,7 @@
<DefineConstants> $(DefineConstants);EDM7 </DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.OData.Edm" Version="7.5.1" />
<PackageReference Include="Microsoft.OData.Edm" Version="7.9.1" />
</ItemGroup>
</When>
<Otherwise>
Expand Down
2 changes: 1 addition & 1 deletion OData2PocoLib/PocoClassGeneratorCs.cs
Expand Up @@ -37,7 +37,7 @@ private PocoClassGeneratorCs(IPocoGenerator pocoGen, PocoSetting setting)
private string? CodeText { get; set; }

//key is fullName: <namespace.className>
public ClassTemplate this[string key] => ClassList.FirstOrDefault(x => x.FullName == key);
public ClassTemplate? this[string key] => ClassList.FirstOrDefault(x => x.FullName == key);
public List<ClassTemplate> ClassList { get; set; }
public PocoSetting PocoSetting { get; set; }

Expand Down
15 changes: 8 additions & 7 deletions OData2PocoLib/V3/Poco.cs
Expand Up @@ -349,8 +349,7 @@ private string GetClrTypeName(IEdmTypeReference edmTypeReference)
if (!edmTypeReference.IsCollection()) return clrTypeName;
if (!(edmType is IEdmCollectionType edmCollectionType)) return clrTypeName;
var elementTypeReference = edmCollectionType.ElementType;
var primitiveElementType = elementTypeReference.Definition as IEdmPrimitiveType;
if (primitiveElementType == null)
if (!(elementTypeReference.Definition is IEdmPrimitiveType primitiveElementType))
{
if (!(elementTypeReference.Definition is IEdmSchemaElement schemaElement)) return clrTypeName;
clrTypeName = schemaElement.FullName();
Expand All @@ -375,7 +374,7 @@ private bool CheckError(IEdmTypeReference edmTypeReference)
{
var edmType = edmTypeReference.Definition;
if (!edmType.Errors().Any()) return false;
var error = edmType.Errors().Select(x => $"Location: {x.ErrorLocation.ToString()}, {x.ErrorMessage }").FirstOrDefault();
var error = edmType.Errors().Select(x => $"Location: {x.ErrorLocation}, {x.ErrorMessage }").FirstOrDefault();
_logger.Trace($"edmTypeReference Error: {error.Dump()}");
_logger.Warn($"Invalid Type Reference: {edmType}");
SchemaErrors.Add($"Invalid Type Reference: {edmType}");
Expand All @@ -385,13 +384,15 @@ private bool CheckError(IEdmTypeReference edmTypeReference)

#region Helper Methods

internal IEdmSchemaType GetSchemaType(string name, string nameSpace)
internal IEdmSchemaType? GetSchemaType(string name, string nameSpace)
{
return (IEdmSchemaType)Model.SchemaElements.FirstOrDefault(x => x.Name == name && x.Namespace == nameSpace);
return (IEdmSchemaType?)Model.SchemaElements
.FirstOrDefault(x => x.Name == name && x.Namespace == nameSpace);
}
internal IEdmSchemaType GetSchemaType(string fullName)
internal IEdmSchemaType? GetSchemaType(string fullName)
{
return (IEdmSchemaType)Model.SchemaElements.FirstOrDefault(x => x.FullName() == fullName);
return (IEdmSchemaType?)Model.SchemaElements
.FirstOrDefault(x => x.FullName() == fullName);
}
IEnumerable<IEdmSchemaType> GetSchemaElements(IEdmModel model)
{
Expand Down

0 comments on commit 349b6a5

Please sign in to comment.