Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix RequestInformation by removing GetType, prefer typeof(T) #184

Merged
merged 8 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/Microsoft.Kiota.Abstractions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<Copyright>© Microsoft Corporation. All rights reserved.</Copyright>
<AssemblyTitle>Kiota Abstractions Library for dotnet</AssemblyTitle>
<Authors>Microsoft</Authors>
<TargetFrameworks>netstandard2.0;netstandard2.1;net5.0;</TargetFrameworks>
<TargetFrameworks>netstandard2.0;netstandard2.1;net6.0;net7.0;net8.0;</TargetFrameworks>
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
<LangVersion>latest</LangVersion>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<PackageIconUrl>http://go.microsoft.com/fwlink/?LinkID=288890</PackageIconUrl>
Expand Down Expand Up @@ -34,7 +34,7 @@
<PackageReadmeFile>README.md</PackageReadmeFile>
<NoWarn>$(NoWarn);NU5048;NETSDK1138</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFrameworkVersion)' == 'net5.0'">
<PropertyGroup Condition="$([System.Text.RegularExpressions.Regex]::IsMatch($(TargetFrameworkVersion), 'net\\d\\.\\d'))">
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>

Expand Down
2 changes: 1 addition & 1 deletion src/MultipartBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public void Serialize(ISerializationWriter writer)
{
throw new InvalidOperationException(nameof(RequestAdapter.SerializationWriterFactory));
}
if(!_parts.Any())
if(_parts.Count == 0)
{
throw new InvalidOperationException("No parts to serialize");
}
Expand Down
4 changes: 2 additions & 2 deletions src/RequestHeaders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void Add(string headerName, params string[] headerValues)
throw new ArgumentNullException(nameof(headerName));
if(headerValues == null)
throw new ArgumentNullException(nameof(headerValues));
if(!headerValues.Any())
if(headerValues.Length == 0)
return;
if(_singleValueHeaders.Contains(headerName))
_headers[headerName] = new HashSet<string> { headerValues[0] };
Expand Down Expand Up @@ -79,7 +79,7 @@ public bool Remove(string headerName, string headerValue)
if(_headers.TryGetValue(headerName, out var values))
{
var result = values.Remove(headerValue);
if(!values.Any())
if(values.Count == 0)
_headers.Remove(headerName);
return result;
}
Expand Down
26 changes: 12 additions & 14 deletions src/RequestInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using Microsoft.Kiota.Abstractions.Extensions;
using Microsoft.Kiota.Abstractions.Serialization;
Expand Down Expand Up @@ -114,11 +112,11 @@ public Uri URI
};

/// <summary>
/// Sanitizes objects in order to appear appropiately in the URL
/// Sanitizes objects in order to appear appropriately in the URL
/// </summary>
/// <param name="value">Object to be sanitized</param>
/// <returns>Sanitized object</returns>
private static object GetSanitizedValue(object value) => value switch
private static string GetSanitizedValue(object value) => value switch
{
bool boolean => boolean.ToString().ToLower(),// pass in a lowercase string as the final url will be uppercase due to the way ToString() works for booleans
DateTimeOffset dateTimeOffset => dateTimeOffset.ToString("o"),// Default to ISO 8601 for datetimeoffsets in the url.
Expand Down Expand Up @@ -174,27 +172,27 @@ public void AddQueryParameters<T>(T source)
}
}

private static object ExpandArray(Array collection)
private static string[] ExpandArray(Array collection)
{
var passedArray = new string[collection.Length];
baywet marked this conversation as resolved.
Show resolved Hide resolved
for(var i = 0; i < collection.Length; i++)
{
passedArray[i] = GetSanitizedValue(collection.GetValue(i)!).ToString()!;
passedArray[i] = GetSanitizedValue(collection.GetValue(i)!)!;
}
return passedArray;
}

private static object ReplaceEnumValueByStringRepresentation(object source)
private static string ReplaceEnumValueByStringRepresentation(object source)
{
if(source is Enum enumValue && GetEnumName(enumValue) is string enumValueName)
{
return enumValueName;
}

return source;
return source.ToString()!;
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
}
#if NET5_0_OR_GREATER
private static string? GetEnumName<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(T value) where T : Enum
private static string? GetEnumName<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>(T value) where T : Enum
#else
private static string? GetEnumName<T>(T value) where T : Enum
#endif
Expand All @@ -204,7 +202,7 @@ private static object ReplaceEnumValueByStringRepresentation(object source)
if(Enum.GetName(type, value) is not { } name)
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
throw new ArgumentException($"Invalid Enum value {value} for enum of type {type}");

if(type.GetMember(name).FirstOrDefault()?.GetCustomAttribute<EnumMemberAttribute>() is { } attribute)
if(type.GetField(name)?.GetCustomAttribute<EnumMemberAttribute>() is { } attribute)
return attribute.Value;

return name.ToFirstCharacterLowerCase();
Expand All @@ -225,7 +223,7 @@ public void AddHeaders(RequestHeaders headers)
/// The Request Body.
/// </summary>
public Stream Content { get; set; } = Stream.Null;
private readonly Dictionary<string, IRequestOption> _requestOptions = new Dictionary<string, IRequestOption>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, IRequestOption> _requestOptions = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets the options for this request. Options are unique by type. If an option of the same type is added twice, the last one wins.
/// </summary>
Expand All @@ -246,8 +244,8 @@ public void AddRequestOptions(IEnumerable<IRequestOption> options)
/// <param name="options">Options to remove.</param>
public void RemoveRequestOptions(params IRequestOption[] options)
{
if(!options?.Any() ?? false) throw new ArgumentNullException(nameof(options));
foreach(var optionName in options!.Where(x => x != null).Select(x => x.GetType().FullName))
if(options.Length == 0) throw new ArgumentNullException(nameof(options));
foreach(var optionName in options.Where(x => x != null).Select(x => x.GetType().FullName))
_requestOptions.Remove(optionName!);
}

Expand Down Expand Up @@ -291,7 +289,7 @@ public void SetStreamContent(Stream content, string contentType)
Content = content;
Headers.TryAdd(ContentTypeHeader, contentType);
}
private static ActivitySource _activitySource = new(typeof(RequestInformation).Namespace!);
private static readonly ActivitySource _activitySource = new(typeof(RequestInformation).Namespace!);
/// <summary>
/// Sets the request body from a model with the specified content type.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/authentication/AllowedHostsValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public IEnumerable<string> AllowedHosts
/// </returns>
public bool IsUrlHostValid(Uri uri)
{
return !_allowedHosts.Any() || _allowedHosts.Contains(uri.Host);
return _allowedHosts.Count == 0 || _allowedHosts.Contains(uri.Host);
}

private static void ValidateHosts(IEnumerable<string> hostsToValidate)
Expand Down
2 changes: 1 addition & 1 deletion src/serialization/ISerializationWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public interface ISerializationWriter : IDisposable
/// <param name="key">The key to be used for the written value. May be null.</param>
/// <param name="value">The enum value to be written.</param>
#if NET5_0_OR_GREATER
void WriteEnumValue<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] T>(string? key, T? value) where T : struct, Enum;
void WriteEnumValue<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>(string? key, T? value) where T : struct, Enum;
#else
void WriteEnumValue<T>(string? key, T? value) where T : struct, Enum;
#endif
Expand Down
2 changes: 1 addition & 1 deletion src/serialization/KiotaSerializer.Deserialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ private static Stream GetStreamFromString(string source)
{
var stream = new MemoryStream();
using var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true);
writer.WriteAsync(source).GetAwaiter().GetResult(); // so the asp.net projects don't get an error
baywet marked this conversation as resolved.
Show resolved Hide resolved
writer.Write(source);
writer.Flush();
stream.Position = 0;
return stream;
Expand Down
2 changes: 1 addition & 1 deletion src/serialization/KiotaSerializer.Serialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public static string SerializeAsString<T>(string contentType, IEnumerable<T> val
private static string GetStringFromStream(Stream stream)
{
using var reader = new StreamReader(stream);
return reader.ReadToEndAsync().ConfigureAwait(false).GetAwaiter().GetResult(); // so the asp.net projects don't get an error
IEvangelist marked this conversation as resolved.
Show resolved Hide resolved
return reader.ReadToEnd();
}
private static ISerializationWriter GetSerializationWriter(string contentType, object value)
{
Expand Down
8 changes: 4 additions & 4 deletions src/serialization/ParseNodeFactoryRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ public IParseNode GetRootParseNode(string contentType, Stream content)
_ = content ?? throw new ArgumentNullException(nameof(content));

var vendorSpecificContentType = contentType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First();
if(ContentTypeAssociatedFactories.ContainsKey(vendorSpecificContentType))
return ContentTypeAssociatedFactories[vendorSpecificContentType].GetRootParseNode(vendorSpecificContentType, content);
if(ContentTypeAssociatedFactories.TryGetValue(vendorSpecificContentType, out var vendorFactory))
return vendorFactory.GetRootParseNode(vendorSpecificContentType, content);

var cleanedContentType = contentTypeVendorCleanupRegex.Replace(vendorSpecificContentType, string.Empty);
if(ContentTypeAssociatedFactories.ContainsKey(cleanedContentType))
return ContentTypeAssociatedFactories[cleanedContentType].GetRootParseNode(cleanedContentType, content);
if(ContentTypeAssociatedFactories.TryGetValue(cleanedContentType, out var factory))
return factory.GetRootParseNode(cleanedContentType, content);

throw new InvalidOperationException($"Content type {cleanedContentType} does not have a factory registered to be parsed");
}
Expand Down
2 changes: 1 addition & 1 deletion src/serialization/ParseNodeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static IDictionary<string, Action<IParseNode>> MergeDeserializersForInter
{
throw new ArgumentNullException(nameof(targets));
}
if(!targets.Any())
if(targets.Length == 0)
{
throw new ArgumentException("At least one target must be provided.", nameof(targets));
}
Expand Down
8 changes: 4 additions & 4 deletions src/serialization/SerializationWriterFactoryRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ public ISerializationWriter GetSerializationWriter(string contentType)
throw new ArgumentNullException(nameof(contentType));

var vendorSpecificContentType = contentType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).First();
if(ContentTypeAssociatedFactories.ContainsKey(vendorSpecificContentType))
return ContentTypeAssociatedFactories[vendorSpecificContentType].GetSerializationWriter(vendorSpecificContentType);
if(ContentTypeAssociatedFactories.TryGetValue(vendorSpecificContentType, out var vendorFactory))
return vendorFactory.GetSerializationWriter(vendorSpecificContentType);

var cleanedContentType = ParseNodeFactoryRegistry.contentTypeVendorCleanupRegex.Replace(vendorSpecificContentType, string.Empty);
if(ContentTypeAssociatedFactories.ContainsKey(cleanedContentType))
return ContentTypeAssociatedFactories[cleanedContentType].GetSerializationWriter(cleanedContentType);
if(ContentTypeAssociatedFactories.TryGetValue(cleanedContentType, out var factory))
return factory.GetSerializationWriter(cleanedContentType);

throw new InvalidOperationException($"Content type {cleanedContentType} does not have a factory registered to be parsed");
}
Expand Down
Loading