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 all 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.7.7] - 2024-02-01

### Changed

- Fixed AOT trimming warnings the URI template parameters resolution. [microsoft/kiota#4065](https://github.com/microsoft/kiota/issues/4065).

## [1.7.6] - 2024-01-24

### Changed
Expand Down
14 changes: 7 additions & 7 deletions Microsoft.Kiota.Abstractions.Tests/RequestInformationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ public void SetsIntValuesInQueryParameters()
UrlTemplate = "http://localhost/me{?items}"
};
// Act
requestInfo.AddQueryParameters(new GetQueryParameters { Items = new object []{1,2}});
requestInfo.AddQueryParameters(new GetQueryParameters { Items = new object[] { 1, 2 } });
// Assert
Assert.Equal("http://localhost/me?items=1,2", requestInfo.URI.ToString());
}
Expand All @@ -544,15 +544,15 @@ public void SetsBooleanValuesInQueryParameters()
UrlTemplate = "http://localhost/me{?items}"
};
// Act
requestInfo.AddQueryParameters(new GetQueryParameters { Items = new object [] { true, false } });
requestInfo.AddQueryParameters(new GetQueryParameters { Items = new object[] { true, false } });
// Assert
Assert.Equal("http://localhost/me?items=true,false", requestInfo.URI.ToString());
}

[Fact]
public void SetsDateTimeOffsetValuesInQueryParameters()
{
var requestInfo = new RequestInformation
var requestInfo = new RequestInformation
{
HttpMethod = Method.GET,
UrlTemplate = "http://localhost/me{?items}"
Expand Down Expand Up @@ -615,7 +615,7 @@ public void SetsTimeValuesInQueryParameters()
};

// Act
var date1 = new Time(10,0,0);
var date1 = new Time(10, 0, 0);
var date2 = new Time(11, 1, 1);

requestInfo.AddQueryParameters(new GetQueryParameters { Items = new object[] { date1, date2 } });
Expand Down Expand Up @@ -654,15 +654,15 @@ public void DoesNotExpandSecondLayerArrays()
};

// Act
requestInfo.AddQueryParameters(new GetQueryParameters { Items = new object[]{new int[]{1,2,3,4} } });
requestInfo.AddQueryParameters(new GetQueryParameters { Items = [new int[] { 1, 2, 3, 4 }] });
// Assert
Assert.Equal("http://localhost/me?items=System.Int32%5B%5D", requestInfo.URI.OriginalString);
Assert.Throws<ArgumentException>(() => requestInfo.URI.OriginalString);
}


}



/// <summary>The messages in a mailbox or folder. Read-only. Nullable.</summary>
internal class GetQueryParameters
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.Kiota.Abstractions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<PackageProjectUrl>https://aka.ms/kiota/docs</PackageProjectUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<Deterministic>true</Deterministic>
<VersionPrefix>1.7.6</VersionPrefix>
<VersionPrefix>1.7.7</VersionPrefix>
<VersionSuffix></VersionSuffix>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<SignAssembly>false</SignAssembly>
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
24 changes: 11 additions & 13 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,7 +112,7 @@ 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>
Expand Down Expand Up @@ -174,12 +172,12 @@ public void AddQueryParameters<T>(T source)
}
}

private static object ExpandArray(Array collection)
private static object[] ExpandArray(Array collection)
{
var passedArray = new string[collection.Length];
var passedArray = new object[collection.Length];
for(var i = 0; i < collection.Length; i++)
{
passedArray[i] = GetSanitizedValue(collection.GetValue(i)!).ToString()!;
passedArray[i] = GetSanitizedValue(collection.GetValue(i)!);
}
return passedArray;
}
Expand All @@ -190,11 +188,11 @@ private static object ReplaceEnumValueByStringRepresentation(object source)
{
return enumValueName;
}

return source;
}
#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
4 changes: 3 additions & 1 deletion src/serialization/KiotaSerializer.Deserialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ 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

// Some clients enforce async stream processing.
writer.WriteAsync(source).GetAwaiter().GetResult();
writer.Flush();
stream.Position = 0;
return stream;
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