Skip to content

Commit

Permalink
Extensions for client and response (#2221)
Browse files Browse the repository at this point in the history
* Added new extensions
* Added polyfills
  • Loading branch information
alexeyzimarev authored Jun 17, 2024
1 parent bc0262e commit bfabd65
Show file tree
Hide file tree
Showing 84 changed files with 1,032 additions and 499 deletions.
12 changes: 2 additions & 10 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ resharper_wrap_array_initializer_style = chop_always
resharper_wrap_before_arrow_with_expressions = true
resharper_wrap_chained_binary_expressions = chop_if_long
resharper_wrap_object_and_collection_initializer_style = chop_always
resharper_invert_if_highlighting = none

# Microsoft .NET properties
csharp_using_directive_placement = outside_namespace
Expand All @@ -45,17 +46,7 @@ csharp_preferred_modifier_order = public, private, protected, internal, new, abs
csharp_style_var_elsewhere = true:suggestion
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
dotnet_naming_rule.unity_serialized_field_rule.import_to_resharper = True
dotnet_naming_rule.unity_serialized_field_rule.resharper_description = Unity serialized field
dotnet_naming_rule.unity_serialized_field_rule.resharper_guid = 5f0fdb63-c892-4d2c-9324-15c80b22a7ef
dotnet_naming_rule.unity_serialized_field_rule.severity = warning
dotnet_naming_rule.unity_serialized_field_rule.style = lower_camel_case_style
dotnet_naming_rule.unity_serialized_field_rule.symbols = unity_serialized_field_symbols
dotnet_naming_style.lower_camel_case_style.capitalization = camel_case
dotnet_naming_symbols.unity_serialized_field_symbols.applicable_accessibilities = *
dotnet_naming_symbols.unity_serialized_field_symbols.applicable_kinds =
dotnet_naming_symbols.unity_serialized_field_symbols.resharper_applicable_kinds = unity_serialised_field
dotnet_naming_symbols.unity_serialized_field_symbols.resharper_required_modifiers = instance
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none
Expand All @@ -81,6 +72,7 @@ resharper_suggest_var_or_type_simple_types_highlighting = hint
resharper_web_config_module_not_resolved_highlighting = warning
resharper_web_config_type_not_resolved_highlighting = warning
resharper_web_config_wrong_module_highlighting = warning
resharper_redundant_using_directive_highlighting = error

[*.{appxmanifest,asax,ascx,aspx,axaml,build,cg,cginc,compute,cs,cshtml,dtd,fs,fsi,fsscript,fsx,hlsl,hlsli,hlslinc,master,ml,mli,nuspec,paml,razor,resw,resx,shader,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}]
indent_style = space
Expand Down
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

<PropertyGroup Condition="'$(TargetFramework)' == 'net471' Or '$(TargetFramework)' == 'netstandard2.0' Or '$(TargetFramework)' == 'net48'">
<AddSystemTextJson>true</AddSystemTextJson>
<AddNullable>true</AddNullable>
<AddPolyfills>true</AddPolyfills>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All"/>
Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public CsvHelperSerializer() : this(new CsvConfiguration(CultureInfo.InvariantCu
}

foreach (var record in csvReader.GetRecords(itemType)) {
method.Invoke(result, new[] { record });
method.Invoke(result, [record]);
}

return result;
Expand Down
8 changes: 4 additions & 4 deletions src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class JsonNetSerializer : IRestSerializer, ISerializer, IDeserializer {
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};

[ThreadStatic] static WriterBuffer? writerBuffer;
[ThreadStatic] static WriterBuffer? _writerBuffer;

readonly JsonSerializer _serializer;

Expand All @@ -52,11 +52,11 @@ public class JsonNetSerializer : IRestSerializer, ISerializer, IDeserializer {
public string? Serialize(object? obj) {
if (obj == null) return null;

using var writerBuffer = JsonNetSerializer.writerBuffer ??= new WriterBuffer(_serializer);
using var buffer = _writerBuffer ??= new WriterBuffer(_serializer);

_serializer.Serialize(writerBuffer.GetJsonTextWriter(), obj, obj.GetType());
_serializer.Serialize(buffer.GetJsonTextWriter(), obj, obj.GetType());

return writerBuffer.GetStringWriter().ToString();
return buffer.GetStringWriter().ToString();
}

public string? Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value);
Expand Down
2 changes: 2 additions & 0 deletions src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

using System.Globalization;
using RestSharp.Extensions;
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
// ReSharper disable MemberCanBePrivate.Global

// ReSharper disable once CheckNamespace
namespace RestSharp.Serializers;
Expand Down
10 changes: 4 additions & 6 deletions src/RestSharp.Serializers.Xml/XmlDeserializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using System.Xml;
using System.Xml.Linq;
using RestSharp.Extensions;
// ReSharper disable VirtualMemberNeverOverridden.Global

namespace RestSharp.Serializers.Xml;

Expand All @@ -37,7 +38,7 @@ public class XmlDeserializer : IXmlDeserializer, IWithRootElement, IWithDateForm
if (string.IsNullOrEmpty(response.Content))
return default;

var doc = XDocument.Parse(response.Content);
var doc = XDocument.Parse(response.Content!);
var root = doc.Root;
var rootElement = response.RootElement ?? RootElement;

Expand Down Expand Up @@ -161,8 +162,7 @@ protected virtual object Map(object x, XElement? root) {
var asType = type.AsType();

if (asType == typeof(bool)) {
var toConvert = value.ToString()!
.ToLower(Culture);
var toConvert = value.ToString()!.ToLower(Culture);

prop.SetValue(x, XmlConvert.ToBoolean(toConvert), null);
}
Expand Down Expand Up @@ -227,9 +227,7 @@ protected virtual object Map(object x, XElement? root) {
else if (asType == typeof(Guid)) {
var raw = value.ToString();

value = string.IsNullOrEmpty(raw)
? Guid.Empty
: new Guid(value.ToString()!);
value = string.IsNullOrEmpty(raw) ? Guid.Empty : new Guid(value.ToString()!);

prop.SetValue(x, value, null);
}
Expand Down
1 change: 1 addition & 0 deletions src/RestSharp.Serializers.Xml/XmlSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public XmlSerializer() { }
/// Specify the namespaced to be used when serializing
/// </summary>
/// <param name="namespace">XML namespace</param>
[PublicAPI]
public XmlSerializer(string @namespace) => Namespace = @namespace;

/// <summary>
Expand Down
30 changes: 16 additions & 14 deletions src/RestSharp/AsyncHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ static class AsyncHelpers {
/// Executes a task synchronously on the calling thread by installing a temporary synchronization context that queues continuations
/// </summary>
/// <param name="task">Callback for asynchronous task to run</param>
public static void RunSync(Func<Task> task) {
static void RunSync(Func<Task> task) {
var currentContext = SynchronizationContext.Current;
var customContext = new CustomSynchronizationContext(task);

Expand Down Expand Up @@ -80,19 +80,6 @@ public override void Post(SendOrPostCallback function, object? state) {
/// Enqueues the function to be executed and executes all resulting continuations until it is completely done
/// </summary>
public void Run() {
async void PostCallback(object? _) {
try {
await _task().ConfigureAwait(false);
}
catch (Exception exception) {
_caughtException = ExceptionDispatchInfo.Capture(exception);
throw;
}
finally {
Post(_ => _done = true, null);
}
}

Post(PostCallback, null);

while (!_done) {
Expand All @@ -107,6 +94,21 @@ async void PostCallback(object? _) {
_workItemsWaiting.WaitOne();
}
}

return;

async void PostCallback(object? _) {
try {
await _task().ConfigureAwait(false);
}
catch (Exception exception) {
_caughtException = ExceptionDispatchInfo.Capture(exception);
throw;
}
finally {
Post(_ => _done = true, null);
}
}
}

/// <summary>
Expand Down
4 changes: 3 additions & 1 deletion src/RestSharp/Authenticators/OAuth/OAuth1Authenticator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@
using RestSharp.Authenticators.OAuth;
using RestSharp.Extensions;
using System.Web;
// ReSharper disable PropertyCanBeMadeInitOnly.Global

// ReSharper disable NotResolvedInText
// ReSharper disable CheckNamespace

namespace RestSharp.Authenticators;

/// <seealso href="http://tools.ietf.org/html/rfc5849">RFC: The OAuth 1.0 Protocol</seealso>
// ReSharper disable once ClassWithVirtualMembersNeverInherited.Global
public class OAuth1Authenticator : IAuthenticator {
public virtual string? Realm { get; set; }
public virtual OAuthParameterHandling ParameterHandling { get; set; }
Expand Down Expand Up @@ -246,7 +248,7 @@ internal static void AddOAuthData(
var url = client.BuildUri(request).ToString();
var queryStringStart = url.IndexOf('?');

if (queryStringStart != -1) url = url.Substring(0, queryStringStart);
if (queryStringStart != -1) url = url[..queryStringStart];

var method = request.Method.ToString().ToUpperInvariant();
var parameters = new WebPairCollection();
Expand Down
4 changes: 2 additions & 2 deletions src/RestSharp/Authenticators/OAuth/OAuthTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ static class OAuthTools {
/// <summary>
/// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986.
/// </summary>
static readonly string[] UriRfc3986CharsToEscape = { "!", "*", "'", "(", ")" };
static readonly string[] UriRfc3986CharsToEscape = ["!", "*", "'", "(", ")"];

static readonly string[] UriRfc3968EscapedHex = { "%21", "%2A", "%27", "%28", "%29" };
static readonly string[] UriRfc3968EscapedHex = ["%21", "%2A", "%27", "%28", "%29"];

static OAuthTools() {
var bytes = new byte[4];
Expand Down
16 changes: 8 additions & 8 deletions src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,14 @@ WebPairCollection GenerateAuthParameters(string timestamp, string nonce)

WebPairCollection GenerateXAuthParameters(string timestamp, string nonce)
=> [
new("x_auth_username", Ensure.NotNull(ClientUsername, nameof(ClientUsername))),
new("x_auth_password", Ensure.NotNull(ClientPassword, nameof(ClientPassword))),
new("x_auth_mode", "client_auth"),
new("oauth_consumer_key", Ensure.NotNull(ConsumerKey, nameof(ConsumerKey)), true),
new("oauth_signature_method", SignatureMethod.ToRequestValue()),
new("oauth_timestamp", timestamp),
new("oauth_nonce", nonce),
new("oauth_version", Version ?? "1.0")
new WebPair("x_auth_username", Ensure.NotNull(ClientUsername, nameof(ClientUsername))),
new WebPair("x_auth_password", Ensure.NotNull(ClientPassword, nameof(ClientPassword))),
new WebPair("x_auth_mode", "client_auth"),
new WebPair("oauth_consumer_key", Ensure.NotNull(ConsumerKey, nameof(ConsumerKey)), true),
new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()),
new WebPair("oauth_timestamp", timestamp),
new WebPair("oauth_nonce", nonce),
new WebPair("oauth_version", Version ?? "1.0")
];

internal class OAuthParameters {
Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp/Authenticators/OAuth/WebPairCollection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
namespace RestSharp.Authenticators.OAuth;

class WebPairCollection : IList<WebPair> {
readonly List<WebPair> _parameters = new();
readonly List<WebPair> _parameters = [];

public IEnumerator<WebPair> GetEnumerator() => _parameters.GetEnumerator();

Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp/BuildUriExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ string EncodeParameter(Parameter parameter)
}

static void DoBuildUriValidations(IRestClient client, RestRequest request) {
if (client.Options.BaseUrl == null && !request.Resource.ToLowerInvariant().StartsWith("http"))
if (client.Options.BaseUrl == null && !request.Resource.StartsWith("http", StringComparison.InvariantCultureIgnoreCase))
throw new ArgumentOutOfRangeException(
nameof(request),
"Request resource doesn't contain a valid scheme for an empty base URL of the client"
Expand Down
10 changes: 3 additions & 7 deletions src/RestSharp/ContentType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class ContentType : IEquatable<ContentType> {

public override string ToString() => Value;

public static implicit operator ContentType(string? contentType) => contentType == null ? Undefined : new(contentType);
public static implicit operator ContentType(string? contentType) => contentType == null ? Undefined : new ContentType(contentType);

public static implicit operator string(ContentType contentType) => contentType.Value;

Expand All @@ -59,13 +59,9 @@ public class ContentType : IEquatable<ContentType> {
{ DataFormat.Binary, Binary }
};

public static readonly string[] JsonAccept = {
Json, "text/json", "text/x-json", "text/javascript"
};
public static readonly string[] JsonAccept = [Json, "text/json", "text/x-json", "text/javascript"];

public static readonly string[] XmlAccept = {
Xml, "text/xml"
};
public static readonly string[] XmlAccept = [Xml, "text/xml"];

readonly string _value;

Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp/Ensure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ public static string NotEmptyString(object? value, [InvokerParameterName] string
var s = value as string ?? value?.ToString();
return string.IsNullOrWhiteSpace(s) ? throw new ArgumentNullException(name) : s!;
}
}
}
1 change: 0 additions & 1 deletion src/RestSharp/Enum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Net;

namespace RestSharp;

Expand Down
Loading

0 comments on commit bfabd65

Please sign in to comment.