diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 8c1faff17..9eeea5b38 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Upload - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: Event File path: ${{ github.event_path }} @@ -28,21 +28,28 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup .NET - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | 8.0.x 9.0.x + - + name: Setup .NET 10 + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 10.0.x + dotnet-quality: 'preview' - name: Run tests run: dotnet test -c Debug -f ${{ matrix.dotnet }} - name: Upload Test Results if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: Test Results Windows ${{ matrix.dotnet }} path: | @@ -59,21 +66,28 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Setup .NET - uses: actions/setup-dotnet@v4 + uses: actions/setup-dotnet@v5 with: dotnet-version: | 8.0.x 9.0.x + - + name: Setup .NET 10 + uses: actions/setup-dotnet@v5 + with: + dotnet-version: | + 10.0.x + dotnet-quality: 'preview' - name: Run tests run: dotnet test -f ${{ matrix.dotnet }} - name: Upload Test Results if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v5 with: name: Test Results Ubuntu ${{ matrix.dotnet }} path: | diff --git a/Directory.Packages.props b/Directory.Packages.props index ed1fd4b2e..9da81daba 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -2,16 +2,23 @@ true - - 8.0.3 + + 10.0.0-rc.2.25502.107 + 10.0.0-rc.2.25502.107 - - 9.0.0 + + 9.0.10 + + + 8.0.21 + + + 9.0.10 - + diff --git a/benchmarks/RestSharp.Benchmarks/Requests/AddObjectToRequestParametersBenchmarks.cs b/benchmarks/RestSharp.Benchmarks/Requests/AddObjectToRequestParametersBenchmarks.cs index 072877d4b..355667196 100644 --- a/benchmarks/RestSharp.Benchmarks/Requests/AddObjectToRequestParametersBenchmarks.cs +++ b/benchmarks/RestSharp.Benchmarks/Requests/AddObjectToRequestParametersBenchmarks.cs @@ -20,7 +20,7 @@ public void GlobalSetup() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; var dateTime = DateTime.Parse("01/01/2013 03:03:12"); - _data = new Data(@string, int.MaxValue, strings, ints, dateTime, strings); + _data = new(@string, int.MaxValue, strings, ints, dateTime, strings); } [Benchmark(Baseline = true)] diff --git a/gen/SourceGenerator/Extensions.cs b/gen/SourceGenerator/Extensions.cs index f529412a1..0e740eb6e 100644 --- a/gen/SourceGenerator/Extensions.cs +++ b/gen/SourceGenerator/Extensions.cs @@ -15,20 +15,22 @@ namespace SourceGenerator; static class Extensions { - public static IEnumerable FindClasses(this Compilation compilation, Func predicate) - => compilation.SyntaxTrees - .Select(tree => compilation.GetSemanticModel(tree)) - .SelectMany(model => model.SyntaxTree.GetRoot().DescendantNodes().OfType()) - .Where(predicate); + extension(Compilation compilation) { + public IEnumerable FindClasses(Func predicate) + => compilation.SyntaxTrees + .Select(tree => compilation.GetSemanticModel(tree)) + .SelectMany(model => model.SyntaxTree.GetRoot().DescendantNodes().OfType()) + .Where(predicate); - public static IEnumerable FindAnnotatedClasses(this Compilation compilation, string attributeName, bool strict) { - return compilation.FindClasses( - syntax => syntax.AttributeLists.Any(list => list.Attributes.Any(CheckAttribute)) - ); + public IEnumerable FindAnnotatedClasses(string attributeName, bool strict) { + return compilation.FindClasses( + syntax => syntax.AttributeLists.Any(list => list.Attributes.Any(CheckAttribute)) + ); - bool CheckAttribute(AttributeSyntax attr) { - var name = attr.Name.ToString(); - return strict ? name == attributeName : name.StartsWith(attributeName); + bool CheckAttribute(AttributeSyntax attr) { + var name = attr.Name.ToString(); + return strict ? name == attributeName : name.StartsWith(attributeName); + } } } diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 85288d985..549702c46 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,7 +1,7 @@ - netstandard2.0;net471;net48;net8.0;net9.0 + netstandard2.0;net471;net48;net8.0;net9.0;net10.0 restsharp.png Apache-2.0 https://restsharp.dev diff --git a/src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs b/src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs index f2ea1cc7c..54e82ab2a 100644 --- a/src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs +++ b/src/RestSharp.Serializers.CsvHelper/CsvHelperSerializer.cs @@ -18,7 +18,7 @@ public class CsvHelperSerializer(CsvConfiguration configuration) : IDeserializer public ContentType ContentType { get; set; } = ContentType.Csv; - public CsvHelperSerializer() : this(new CsvConfiguration(CultureInfo.InvariantCulture)) { } + public CsvHelperSerializer() : this(new(CultureInfo.InvariantCulture)) { } public T? Deserialize(RestResponse response) { try { diff --git a/src/RestSharp.Serializers.CsvHelper/RestClientExtensions.cs b/src/RestSharp.Serializers.CsvHelper/RestClientExtensions.cs index d71b6b38a..4d6456b76 100644 --- a/src/RestSharp.Serializers.CsvHelper/RestClientExtensions.cs +++ b/src/RestSharp.Serializers.CsvHelper/RestClientExtensions.cs @@ -4,8 +4,10 @@ namespace RestSharp.Serializers.CsvHelper; [PublicAPI] public static class RestClientExtensions { - public static SerializerConfig UseCsvHelper(this SerializerConfig config) => config.UseSerializer(); + extension(SerializerConfig config) { + public SerializerConfig UseCsvHelper() => config.UseSerializer(); - public static SerializerConfig UseCsvHelper(this SerializerConfig config, CsvConfiguration configuration) - => config.UseSerializer(() => new CsvHelperSerializer(configuration)); + public SerializerConfig UseCsvHelper(CsvConfiguration configuration) + => config.UseSerializer(() => new CsvHelperSerializer(configuration)); + } } diff --git a/src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs b/src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs index 2b41db918..d5ee33046 100644 --- a/src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs +++ b/src/RestSharp.Serializers.NewtonsoftJson/JsonNetSerializer.cs @@ -52,7 +52,7 @@ public class JsonNetSerializer : IRestSerializer, ISerializer, IDeserializer { public string? Serialize(object? obj) { if (obj == null) return null; - using var buffer = _writerBuffer ??= new WriterBuffer(_serializer); + using var buffer = _writerBuffer ??= new(_serializer); _serializer.Serialize(buffer.GetJsonTextWriter(), obj, obj.GetType()); diff --git a/src/RestSharp.Serializers.NewtonsoftJson/RestClientExtensions.cs b/src/RestSharp.Serializers.NewtonsoftJson/RestClientExtensions.cs index f228ac07f..7f6e6ffec 100644 --- a/src/RestSharp.Serializers.NewtonsoftJson/RestClientExtensions.cs +++ b/src/RestSharp.Serializers.NewtonsoftJson/RestClientExtensions.cs @@ -16,19 +16,20 @@ namespace RestSharp.Serializers.NewtonsoftJson; [PublicAPI] public static class RestClientExtensions { - /// - /// Use Newtonsoft.Json serializer with default settings - /// /// - /// - public static SerializerConfig UseNewtonsoftJson(this SerializerConfig config) => config.UseSerializer(() => new JsonNetSerializer()); + extension(SerializerConfig config) { + /// + /// Use Newtonsoft.Json serializer with default settings + /// + /// + public SerializerConfig UseNewtonsoftJson() => config.UseSerializer(() => new JsonNetSerializer()); - /// - /// Use Newtonsoft.Json serializer with custom settings - /// - /// - /// Newtonsoft.Json serializer settings - /// - public static SerializerConfig UseNewtonsoftJson(this SerializerConfig config, JsonSerializerSettings settings) - => config.UseSerializer(() => new JsonNetSerializer(settings)); + /// + /// Use Newtonsoft.Json serializer with custom settings + /// + /// Newtonsoft.Json serializer settings + /// + public SerializerConfig UseNewtonsoftJson(JsonSerializerSettings settings) + => config.UseSerializer(() => new JsonNetSerializer(settings)); + } } \ No newline at end of file diff --git a/src/RestSharp.Serializers.NewtonsoftJson/WriterBuffer.cs b/src/RestSharp.Serializers.NewtonsoftJson/WriterBuffer.cs index 7d77a5adc..a1505a869 100644 --- a/src/RestSharp.Serializers.NewtonsoftJson/WriterBuffer.cs +++ b/src/RestSharp.Serializers.NewtonsoftJson/WriterBuffer.cs @@ -13,7 +13,6 @@ // limitations under the License. using System.Globalization; -using System.Text; namespace RestSharp.Serializers.NewtonsoftJson; @@ -22,9 +21,9 @@ sealed class WriterBuffer : IDisposable { readonly JsonTextWriter _jsonTextWriter; public WriterBuffer(JsonSerializer jsonSerializer) { - _stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); + _stringWriter = new(new(256), CultureInfo.InvariantCulture); - _jsonTextWriter = new JsonTextWriter(_stringWriter) { + _jsonTextWriter = new(_stringWriter) { Formatting = jsonSerializer.Formatting, CloseOutput = false }; } diff --git a/src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs b/src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs index fb1474d7b..598f446b5 100644 --- a/src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs +++ b/src/RestSharp.Serializers.Xml/SerializeAsAttribute.cs @@ -27,12 +27,6 @@ namespace RestSharp.Serializers; /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false)] public sealed class SerializeAsAttribute : Attribute { - public SerializeAsAttribute() { - NameStyle = NameStyle.AsIs; - Index = int.MaxValue; - Culture = CultureInfo.InvariantCulture; - } - /// /// The name to use for the serialized element /// @@ -51,17 +45,17 @@ public SerializeAsAttribute() { /// /// The culture to use when serializing /// - public CultureInfo Culture { get; set; } + public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; /// /// Transforms the casing of the name based on the selected value. /// - public NameStyle NameStyle { get; set; } + public NameStyle NameStyle { get; set; } = NameStyle.AsIs; /// /// The order to serialize the element. Default is int.MaxValue. /// - public int Index { get; set; } + public int Index { get; set; } = int.MaxValue; /// /// Called by the attribute when NameStyle is speficied diff --git a/src/RestSharp.Serializers.Xml/XmlDeserializer.cs b/src/RestSharp.Serializers.Xml/XmlDeserializer.cs index ee2fbf8af..99959b221 100644 --- a/src/RestSharp.Serializers.Xml/XmlDeserializer.cs +++ b/src/RestSharp.Serializers.Xml/XmlDeserializer.cs @@ -24,9 +24,7 @@ namespace RestSharp.Serializers.Xml; public class XmlDeserializer : IXmlDeserializer, IWithRootElement, IWithDateFormat { - public XmlDeserializer() => Culture = CultureInfo.InvariantCulture; - - public CultureInfo Culture { get; set; } + public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; public string? RootElement { get; set; } @@ -75,7 +73,7 @@ static void RemoveNamespace(XDocument xdoc) { a => a.IsNamespaceDeclaration ? null : a.Name.Namespace != XNamespace.None - ? new XAttribute(XNamespace.None.GetName(a.Name.LocalName), a.Value) + ? new(XNamespace.None.GetName(a.Name.LocalName), a.Value) : a ) ); @@ -227,7 +225,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(value.ToString()!); prop.SetValue(x, value, null); } diff --git a/src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs b/src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs index aef613233..3b6d557b0 100644 --- a/src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs +++ b/src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs @@ -17,13 +17,15 @@ namespace RestSharp.Authenticators.OAuth.Extensions; static class StringExtensions { - public static bool EqualsIgnoreCase(this string left, string right) => string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase); + extension(string left) { + public bool EqualsIgnoreCase(string right) => string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase); - public static string Then(this string input, string value) => string.Concat(input, value); + public string Then(string value) => string.Concat(left, value); - public static Uri AsUri(this string value) => new(value); + public Uri AsUri() => new(left); - public static byte[] GetBytes(this string input) => Encoding.UTF8.GetBytes(input); + public byte[] GetBytes() => Encoding.UTF8.GetBytes(left); - public static string PercentEncode(this string s) => string.Join("", s.GetBytes().Select(x => $"%{x:X2}")); + public string PercentEncode() => string.Join("", left.GetBytes().Select(x => $"%{x:X2}")); + } } \ No newline at end of file diff --git a/src/RestSharp/Authenticators/OAuth/OAuthTools.cs b/src/RestSharp/Authenticators/OAuth/OAuthTools.cs index 4c70eab8e..1c4f7ab92 100644 --- a/src/RestSharp/Authenticators/OAuth/OAuthTools.cs +++ b/src/RestSharp/Authenticators/OAuth/OAuthTools.cs @@ -44,7 +44,7 @@ static OAuthTools() { var bytes = new byte[4]; Rng.GetBytes(bytes); - Random = new Random(BitConverter.ToInt32(bytes, 0)); + Random = new(BitConverter.ToInt32(bytes, 0)); } /// @@ -60,7 +60,7 @@ public static string GetNonce() { for (var i = 0; i < nonce.Length; i++) nonce[i] = chars[Random.Next(0, chars.Length)]; } - return new string(nonce); + return new(nonce); } /// diff --git a/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs b/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs index 894bb24f9..d1818ec55 100644 --- a/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs +++ b/src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs @@ -62,7 +62,7 @@ public OAuthParameters BuildRequestTokenSignature(string method, WebPairCollecti var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters); - return new OAuthParameters { + return new() { Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret), Parameters = authParameters }; @@ -91,7 +91,7 @@ public OAuthParameters BuildAccessTokenSignature(string method, WebPairCollectio var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters); - return new OAuthParameters { + return new() { Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret), Parameters = authParameters }; @@ -120,7 +120,7 @@ public OAuthParameters BuildClientAuthAccessTokenSignature(string method, WebPai var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters); - return new OAuthParameters { + return new() { Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret), Parameters = authParameters }; @@ -133,7 +133,7 @@ public OAuthParameters BuildProtectedResourceSignature(string method, WebPairCol allParameters.AddRange(parameters); // Include url parameters in query pool - var uri = new Uri(Ensure.NotEmptyString(RequestUrl, nameof(RequestUrl))); + var uri = new Uri(Ensure.NotEmptyString(RequestUrl, nameof(RequestUrl))); var urlParameters = HttpUtility.ParseQueryString(uri.Query); allParameters.AddRange(urlParameters.AllKeys.Select(x => new WebPair(x!, urlParameters[x]!))); @@ -146,7 +146,7 @@ public OAuthParameters BuildProtectedResourceSignature(string method, WebPairCol var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters); - return new OAuthParameters { + return new() { Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret), Parameters = authParameters }; @@ -167,14 +167,14 @@ WebPairCollection GenerateAuthParameters(string timestamp, string nonce) WebPairCollection GenerateXAuthParameters(string timestamp, string nonce) => [ - 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") + 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") ]; internal class OAuthParameters { diff --git a/src/RestSharp/Authenticators/OAuth/WebPairCollection.cs b/src/RestSharp/Authenticators/OAuth/WebPairCollection.cs index 29134488f..550d0e7d6 100644 --- a/src/RestSharp/Authenticators/OAuth/WebPairCollection.cs +++ b/src/RestSharp/Authenticators/OAuth/WebPairCollection.cs @@ -27,11 +27,11 @@ class WebPairCollection : IList { public void AddRange(IEnumerable collection) => AddCollection(collection); - public void Add(string name, string value) => Add(new WebPair(name, value)); + public void Add(string name, string value) => Add(new(name, value)); public WebPairCollection AddNotEmpty(string name, string? value, bool encode = false) { if (value != null) - Add(new WebPair(name, value, encode)); + Add(new(name, value, encode)); return this; } diff --git a/src/RestSharp/BuildUriExtensions.cs b/src/RestSharp/BuildUriExtensions.cs index ba6676230..6bf976244 100644 --- a/src/RestSharp/BuildUriExtensions.cs +++ b/src/RestSharp/BuildUriExtensions.cs @@ -16,71 +16,71 @@ namespace RestSharp; public static class BuildUriExtensions { - /// - /// Builds the URI for the request - /// /// Client instance - /// Request instance - /// - public static Uri BuildUri(this IRestClient client, RestRequest request) { - DoBuildUriValidations(client, request); + extension(IRestClient client) { + /// + /// Builds the URI for the request + /// + /// Request instance + /// + public Uri BuildUri(RestRequest request) { + DoBuildUriValidations(client, request); - var (uri, resource) = client.Options.BaseUrl.GetUrlSegmentParamsValues( - request.Resource, - client.Options.Encode, - request.Parameters, - client.DefaultParameters - ); - var mergedUri = uri.MergeBaseUrlAndResource(resource); - var query = client.GetRequestQuery(request); - return mergedUri.AddQueryString(query); - } + var (uri, resource) = client.Options.BaseUrl.GetUrlSegmentParamsValues( + request.Resource, + client.Options.Encode, + request.Parameters, + client.DefaultParameters + ); + var mergedUri = uri.MergeBaseUrlAndResource(resource); + var query = client.GetRequestQuery(request); + return mergedUri.AddQueryString(query); + } - /// - /// Builds the URI for the request without query parameters. - /// - /// Client instance - /// Request instance - /// - public static Uri BuildUriWithoutQueryParameters(this IRestClient client, RestRequest request) { - DoBuildUriValidations(client, request); + /// + /// Builds the URI for the request without query parameters. + /// + /// Request instance + /// + public Uri BuildUriWithoutQueryParameters(RestRequest request) { + DoBuildUriValidations(client, request); - var (uri, resource) = client.Options.BaseUrl.GetUrlSegmentParamsValues( - request.Resource, - client.Options.Encode, - request.Parameters, - client.DefaultParameters - ); - return uri.MergeBaseUrlAndResource(resource); - } + var (uri, resource) = client.Options.BaseUrl.GetUrlSegmentParamsValues( + request.Resource, + client.Options.Encode, + request.Parameters, + client.DefaultParameters + ); + return uri.MergeBaseUrlAndResource(resource); + } - /// - /// Gets the query string for the request. - /// - /// Client instance - /// Request instance - /// - [PublicAPI] - public static string? GetRequestQuery(this IRestClient client, RestRequest request) { - var parametersCollections = new ParametersCollection[] { request.Parameters, client.DefaultParameters }; + /// + /// Gets the query string for the request. + /// + /// Request instance + /// + [PublicAPI] + public string? GetRequestQuery(RestRequest request) { + var parametersCollections = new ParametersCollection[] { request.Parameters, client.DefaultParameters }; - var parameters = parametersCollections.SelectMany(x => x.GetQueryParameters(request.Method)).ToList(); + var parameters = parametersCollections.SelectMany(x => x.GetQueryParameters(request.Method)).ToList(); - return parameters.Count == 0 ? null : string.Join("&", parameters.Select(EncodeParameter).ToArray()); + return parameters.Count == 0 ? null : string.Join("&", parameters.Select(EncodeParameter).ToArray()); - string GetString(string name, string? value, Func? encode) { - var val = encode != null && value != null ? encode(value) : value; - return val == null ? name : $"{name}={val}"; - } + string GetString(string name, string? value, Func? encode) { + var val = encode != null && value != null ? encode(value) : value; + return val == null ? name : $"{name}={val}"; + } - string EncodeParameter(Parameter parameter) - => !parameter.Encode - ? GetString(parameter.Name!, parameter.Value?.ToString(), null) - : GetString( - client.Options.EncodeQuery(parameter.Name!, client.Options.Encoding), - parameter.Value?.ToString(), - x => client.Options.EncodeQuery(x, client.Options.Encoding) - ); + string EncodeParameter(Parameter parameter) + => !parameter.Encode + ? GetString(parameter.Name!, parameter.Value?.ToString(), null) + : GetString( + client.Options.EncodeQuery(parameter.Name!, client.Options.Encoding), + parameter.Value?.ToString(), + x => client.Options.EncodeQuery(x, client.Options.Encoding) + ); + } } static void DoBuildUriValidations(IRestClient client, RestRequest request) { diff --git a/src/RestSharp/ContentType.cs b/src/RestSharp/ContentType.cs index 6425dec89..8f8d70554 100644 --- a/src/RestSharp/ContentType.cs +++ b/src/RestSharp/ContentType.cs @@ -41,7 +41,7 @@ public class ContentType : IEquatable { public override string ToString() => Value; - public static implicit operator ContentType(string? contentType) => contentType == null ? Undefined : new ContentType(contentType); + public static implicit operator ContentType(string? contentType) => contentType == null ? Undefined : new(contentType); public static implicit operator string(ContentType contentType) => contentType.Value; diff --git a/src/RestSharp/Extensions/StringExtensions.cs b/src/RestSharp/Extensions/StringExtensions.cs index 6980d3a45..637177a67 100644 --- a/src/RestSharp/Extensions/StringExtensions.cs +++ b/src/RestSharp/Extensions/StringExtensions.cs @@ -36,114 +36,117 @@ static partial class StringExtensions { static readonly Regex AddSpacesRegex2 = AddSpaces2(); static readonly Regex AddSpacesRegex3 = AddSpaces3(); - internal static string UrlDecode(this string input) => HttpUtility.UrlDecode(input); + extension(string input) { + internal string UrlDecode() => HttpUtility.UrlDecode(input); - /// - /// Uses Uri.EscapeDataString() based on recommendations on MSDN - /// http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx - /// - internal static string UrlEncode(this string input) { - const int maxLength = 32766; + /// + /// Uses Uri.EscapeDataString() based on recommendations on MSDN + /// http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx + /// + internal string UrlEncode() { + const int maxLength = 32766; - if (input == null) throw new ArgumentNullException(nameof(input)); + if (input == null) throw new ArgumentNullException(nameof(input)); - if (input.Length <= maxLength) return Uri.EscapeDataString(input); + if (input.Length <= maxLength) return Uri.EscapeDataString(input); - var sb = new StringBuilder(input.Length * 2); - var index = 0; + var sb = new StringBuilder(input.Length * 2); + var index = 0; - while (index < input.Length) { - var length = Math.Min(input.Length - index, maxLength); + while (index < input.Length) { + var length = Math.Min(input.Length - index, maxLength); - while (CharUnicodeInfo.GetUnicodeCategory(input[index + length - 1]) == UnicodeCategory.Surrogate) { - length--; - } + while (CharUnicodeInfo.GetUnicodeCategory(input[index + length - 1]) == UnicodeCategory.Surrogate) { + length--; + } - var subString = input.Substring(index, length); + var subString = input.Substring(index, length); - sb.Append(Uri.EscapeDataString(subString)); - index += subString.Length; - } + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } - return sb.ToString(); - } + return sb.ToString(); + } - internal static string? UrlEncode(this string? input, Encoding encoding) { - var encoded = HttpUtility.UrlEncode(input, encoding); - return encoded?.Replace("+", "%20"); + internal string? UrlEncode(Encoding encoding) { + var encoded = HttpUtility.UrlEncode(input, encoding); + return encoded?.Replace("+", "%20"); + } } - internal static string RemoveUnderscoresAndDashes(this string input) => input.Replace("_", "").Replace("-", ""); + extension(string input) { + internal string RemoveUnderscoresAndDashes() => input.Replace("_", "").Replace("-", ""); - internal static string ToPascalCase(this string lowercaseAndUnderscoredWord, CultureInfo culture) - => ToPascalCase(lowercaseAndUnderscoredWord, true, culture); + internal string ToPascalCase(CultureInfo culture) => ToPascalCase(input, true, culture); - internal static string ToPascalCase(this string text, bool removeUnderscores, CultureInfo culture) { - if (string.IsNullOrEmpty(text)) return text; + internal string ToPascalCase(bool removeUnderscores, CultureInfo culture) { + if (string.IsNullOrEmpty(input)) return input; - text = text.Replace('_', ' '); + input = input.Replace('_', ' '); - var joinString = removeUnderscores ? string.Empty : "_"; - var words = text.Split(' '); + var joinString = removeUnderscores ? string.Empty : "_"; + var words = input.Split(' '); - return words - .Where(x => x.Length > 0) - .Select(CaseWord) - .JoinToString(joinString); + return words + .Where(x => x.Length > 0) + .Select(CaseWord) + .JoinToString(joinString); - string CaseWord(string word) { - var restOfWord = word[1..]; - var firstChar = char.ToUpper(word[0], culture); + string CaseWord(string word) { + var restOfWord = word[1..]; + var firstChar = char.ToUpper(word[0], culture); - if (restOfWord.IsUpperCase()) restOfWord = restOfWord.ToLower(culture); + if (restOfWord.IsUpperCase()) restOfWord = restOfWord.ToLower(culture); - return string.Concat(firstChar, restOfWord); + return string.Concat(firstChar, restOfWord); + } } - } - internal static string ToCamelCase(this string lowercaseAndUnderscoredWord, CultureInfo culture) - => MakeInitialLowerCase(ToPascalCase(lowercaseAndUnderscoredWord, culture), culture); + internal string ToCamelCase(CultureInfo culture) + => MakeInitialLowerCase(ToPascalCase(input, culture), culture); - internal static IEnumerable GetNameVariants(this string name, CultureInfo culture) { - if (string.IsNullOrEmpty(name)) yield break; + internal IEnumerable GetNameVariants(CultureInfo culture) { + if (string.IsNullOrEmpty(input)) yield break; - yield return name; + yield return input; - // try camel cased name - yield return name.ToCamelCase(culture); + // try camel cased name + yield return input.ToCamelCase(culture); - // try lower cased name - yield return name.ToLower(culture); + // try lower cased name + yield return input.ToLower(culture); - // try name with underscores - yield return name.AddUnderscores(); + // try name with underscores + yield return input.AddUnderscores(); - // try name with underscores with lower case - yield return name.AddUnderscores().ToLower(culture); + // try name with underscores with lower case + yield return input.AddUnderscores().ToLower(culture); - // try name with dashes - yield return name.AddDashes(); + // try name with dashes + yield return input.AddDashes(); - // try name with dashes with lower case - yield return name.AddDashes().ToLower(culture); + // try name with dashes with lower case + yield return input.AddDashes().ToLower(culture); - // try name with underscore prefix - yield return name.AddUnderscorePrefix(); + // try name with underscore prefix + yield return input.AddUnderscorePrefix(); - // try name with proper camel case - yield return name.AddUnderscores().ToCamelCase(culture); + // try name with proper camel case + yield return input.AddUnderscores().ToCamelCase(culture); - // try name with underscore prefix, using proper camel case - yield return name.ToCamelCase(culture).AddUnderscorePrefix(); + // try name with underscore prefix, using proper camel case + yield return input.ToCamelCase(culture).AddUnderscorePrefix(); - // try name with underscore prefix, using camel case - yield return name.AddUnderscores().ToCamelCase(culture).AddUnderscorePrefix(); + // try name with underscore prefix, using camel case + yield return input.AddUnderscores().ToCamelCase(culture).AddUnderscorePrefix(); - // try name with spaces - yield return name.AddSpaces(); + // try name with spaces + yield return input.AddSpaces(); - // try name with spaces with lower case - yield return name.AddSpaces().ToLower(culture); + // try name with spaces with lower case + yield return input.AddSpaces().ToLower(culture); + } } internal static bool IsEmpty([NotNullWhen(false)] this string? value) => string.IsNullOrWhiteSpace(value); @@ -152,38 +155,40 @@ internal static IEnumerable GetNameVariants(this string name, CultureInf internal static string JoinToString(this IEnumerable strings, string separator) => string.Join(separator, strings); - static string MakeInitialLowerCase(this string word, CultureInfo culture) => string.Concat(word[..1].ToLower(culture), word[1..]); - - static string AddUnderscores(this string pascalCasedWord) - => AddUnderscoresRegex1.Replace( - AddUnderscoresRegex2.Replace( - AddUnderscoresRegex3.Replace(pascalCasedWord, "$1_$2"), - "$1_$2" - ), - "_" - ); - - static string AddDashes(this string pascalCasedWord) - => AddDashesRegex1.Replace( - AddDashesRegex2.Replace( - AddDashesRegex3.Replace(pascalCasedWord, "$1-$2"), - "$1-$2" - ), - "-" - ); - - static bool IsUpperCase(this string inputString) => IsUpperCaseRegex.IsMatch(inputString); - - static string AddUnderscorePrefix(this string pascalCasedWord) => $"_{pascalCasedWord}"; - - static string AddSpaces(this string pascalCasedWord) - => AddSpacesRegex1.Replace( - AddSpacesRegex2.Replace( - AddSpacesRegex3.Replace(pascalCasedWord, "$1 $2"), - "$1 $2" - ), - " " - ); + extension(string word) { + string MakeInitialLowerCase(CultureInfo culture) => string.Concat(word[..1].ToLower(culture), word[1..]); + + string AddUnderscores() + => AddUnderscoresRegex1.Replace( + AddUnderscoresRegex2.Replace( + AddUnderscoresRegex3.Replace(word, "$1_$2"), + "$1_$2" + ), + "_" + ); + + string AddDashes() + => AddDashesRegex1.Replace( + AddDashesRegex2.Replace( + AddDashesRegex3.Replace(word, "$1-$2"), + "$1-$2" + ), + "-" + ); + + bool IsUpperCase() => IsUpperCaseRegex.IsMatch(word); + + string AddUnderscorePrefix() => $"_{word}"; + + string AddSpaces() + => AddSpacesRegex1.Replace( + AddSpacesRegex2.Replace( + AddSpacesRegex3.Replace(word, "$1 $2"), + "$1 $2" + ), + " " + ); + } const string RIsUpperCase = "^[A-Z]+$"; const string RAddUnderscore1 = @"[-\s]"; diff --git a/src/RestSharp/Parameters/FileParameter.cs b/src/RestSharp/Parameters/FileParameter.cs index dfb4d25d1..d490d9fd3 100644 --- a/src/RestSharp/Parameters/FileParameter.cs +++ b/src/RestSharp/Parameters/FileParameter.cs @@ -65,7 +65,7 @@ public static FileParameter Create( ContentType? contentType = null, FileParameterOptions? options = null ) { - return new FileParameter(name, filename, GetFile, contentType, options ?? new FileParameterOptions()); + return new(name, filename, GetFile, contentType, options ?? new FileParameterOptions()); Stream GetFile() { var stream = new MemoryStream(); @@ -105,7 +105,7 @@ public static FileParameter FromFile( var fileName = Path.GetFileName(fullPath); var parameterName = name ?? fileName; - return new FileParameter(parameterName, fileName, GetFile, contentType, options ?? new FileParameterOptions()); + return new(parameterName, fileName, GetFile, contentType, options ?? new FileParameterOptions()); Stream GetFile() => File.OpenRead(fullPath); } diff --git a/src/RestSharp/Parameters/ObjectParser.cs b/src/RestSharp/Parameters/ObjectParser.cs index db9a03d9d..3f3464d97 100644 --- a/src/RestSharp/Parameters/ObjectParser.cs +++ b/src/RestSharp/Parameters/ObjectParser.cs @@ -42,7 +42,7 @@ ParsedParameter GetValue(PropertyInfo propertyInfo, object? value) { var attribute = propertyInfo.GetCustomAttribute(); var name = attribute?.Name ?? propertyInfo.Name; var val = ParseValue(attribute?.Format, value); - return new ParsedParameter(name, val, attribute?.Encode ?? true); + return new(name, val, attribute?.Encode ?? true); } IEnumerable GetArray(PropertyInfo propertyInfo, object? value) { @@ -54,7 +54,7 @@ IEnumerable GetArray(PropertyInfo propertyInfo, object? value) var queryType = attribute?.ArrayQueryType ?? RequestArrayQueryType.CommaSeparated; var encode = attribute?.Encode ?? true; - if (array.Length <= 0 || elementType == null) return new ParsedParameter[] { new(name, null, encode) }; + if (array.Length <= 0 || elementType == null) return [new(name, null, encode)]; // convert the array to an array of strings var values = array @@ -62,7 +62,7 @@ IEnumerable GetArray(PropertyInfo propertyInfo, object? value) .Select(item => ParseValue(attribute?.Format, item)); return queryType switch { - RequestArrayQueryType.CommaSeparated => new[] { new ParsedParameter(name, string.Join(",", values), encode) }, + RequestArrayQueryType.CommaSeparated => [new(name, string.Join(",", values), encode)], RequestArrayQueryType.ArrayParameters => values.Select(x => new ParsedParameter($"{name}[]", x, encode)), _ => throw new ArgumentOutOfRangeException() }; diff --git a/src/RestSharp/Parameters/ParametersCollectionExtensions.cs b/src/RestSharp/Parameters/ParametersCollectionExtensions.cs index 83b6eefa6..7be33e8b9 100644 --- a/src/RestSharp/Parameters/ParametersCollectionExtensions.cs +++ b/src/RestSharp/Parameters/ParametersCollectionExtensions.cs @@ -16,17 +16,19 @@ namespace RestSharp; static class ParametersCollectionExtensions { - internal static IEnumerable GetQueryParameters(this ParametersCollection parameters, Method method) { - Func condition = - !IsPost(method) - ? p => p.Type is ParameterType.GetOrPost or ParameterType.QueryString - : p => p.Type is ParameterType.QueryString; + extension(ParametersCollection parameters) { + internal IEnumerable GetQueryParameters(Method method) { + Func condition = + !IsPost(method) + ? p => p.Type is ParameterType.GetOrPost or ParameterType.QueryString + : p => p.Type is ParameterType.QueryString; - return parameters.Where(p => condition(p)); - } + return parameters.Where(p => condition(p)); + } - internal static IEnumerable GetContentParameters(this ParametersCollection parameters, Method method) - => IsPost(method) ? parameters.GetParameters() : []; + internal IEnumerable GetContentParameters(Method method) + => IsPost(method) ? parameters.GetParameters() : []; + } static bool IsPost(Method method) => method is Method.Post or Method.Put or Method.Patch; } diff --git a/src/RestSharp/Polyfills/Index.cs b/src/RestSharp/Polyfills/Index.cs index 6599a38fa..972b842e6 100644 --- a/src/RestSharp/Polyfills/Index.cs +++ b/src/RestSharp/Polyfills/Index.cs @@ -49,24 +49,12 @@ public Index(int value, bool fromEnd = false) { /// Create an Index from the start at the position indicated by the value. /// The index value from the start. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Index FromStart(int value) { - if (value < 0) { - throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); - } - - return new Index(value); - } + public static Index FromStart(int value) => value < 0 ? throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative") : new Index(value); /// Create an Index from the end at the position indicated by the value. /// The index value from the end. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Index FromEnd(int value) { - if (value < 0) { - throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative"); - } - - return new Index(~value); - } + public static Index FromEnd(int value) => value < 0 ? throw new ArgumentOutOfRangeException(nameof(value), "value must be non-negative") : new Index(~value); /// Returns the index value. public int Value { diff --git a/src/RestSharp/Polyfills/Range.cs b/src/RestSharp/Polyfills/Range.cs index 15a45b036..49634660e 100644 --- a/src/RestSharp/Polyfills/Range.cs +++ b/src/RestSharp/Polyfills/Range.cs @@ -47,16 +47,16 @@ public override bool Equals(object? value) public override int GetHashCode() => Start.GetHashCode() * 31 + End.GetHashCode(); /// Converts the value of the current Range object to its equivalent string representation. - public override string ToString() => Start + ".." + End; + public override string ToString() => $"{Start}..{End}"; /// Create a Range object starting from start index to the end of the collection. - public static Range StartAt(Index start) => new Range(start, Index.End); + public static Range StartAt(Index start) => new(start, Index.End); /// Create a Range object starting from first element in the collection to the end Index. - public static Range EndAt(Index end) => new Range(Index.Start, end); + public static Range EndAt(Index end) => new(Index.Start, end); /// Create a Range object starting from first element to the end. - public static Range All => new Range(Index.Start, Index.End); + public static Range All => new(Index.Start, Index.End); /// Calculate the start offset and length of range object using a collection length. /// The length of the collection that the range will be used with. length has to be a positive value. diff --git a/src/RestSharp/Request/BodyExtensions.cs b/src/RestSharp/Request/BodyExtensions.cs index 1c6a592e9..958f97289 100644 --- a/src/RestSharp/Request/BodyExtensions.cs +++ b/src/RestSharp/Request/BodyExtensions.cs @@ -18,10 +18,12 @@ namespace RestSharp; using System.Diagnostics.CodeAnalysis; static class BodyExtensions { - public static bool TryGetBodyParameter(this RestRequest request, [NotNullWhen(true)] out BodyParameter? bodyParameter) { - bodyParameter = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody) as BodyParameter; - return bodyParameter != null; - } + extension(RestRequest request) { + public bool TryGetBodyParameter([NotNullWhen(true)] out BodyParameter? bodyParameter) { + bodyParameter = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody) as BodyParameter; + return bodyParameter != null; + } - public static bool HasFiles(this RestRequest request) => request.Files.Count > 0; + public bool HasFiles() => request.Files.Count > 0; + } } diff --git a/src/RestSharp/Request/PropertyCache.Populator.RequestProperty.cs b/src/RestSharp/Request/PropertyCache.Populator.RequestProperty.cs index 7fce7d197..0c6f59814 100644 --- a/src/RestSharp/Request/PropertyCache.Populator.RequestProperty.cs +++ b/src/RestSharp/Request/PropertyCache.Populator.RequestProperty.cs @@ -58,7 +58,7 @@ internal static RequestProperty From(PropertyInfo property) { var propertyName = requestPropertyAttribute.Name ?? property.Name; - return new RequestProperty( + return new( propertyName, requestPropertyAttribute.Format, requestPropertyAttribute.ArrayQueryType, diff --git a/src/RestSharp/Request/PropertyCache.Populator.cs b/src/RestSharp/Request/PropertyCache.Populator.cs index 5074122bb..4057ac999 100644 --- a/src/RestSharp/Request/PropertyCache.Populator.cs +++ b/src/RestSharp/Request/PropertyCache.Populator.cs @@ -74,7 +74,7 @@ internal static Populator From(PropertyInfo property) { var populate = GetPopulate(getObject, property); - return new Populator(property.Name, populate); + return new(property.Name, populate); } static Action> GetPopulate(Func getFormattable, RequestProperty requestProperty) diff --git a/src/RestSharp/Request/RequestContent.cs b/src/RestSharp/Request/RequestContent.cs index 997cfd177..03af0bdcf 100644 --- a/src/RestSharp/Request/RequestContent.cs +++ b/src/RestSharp/Request/RequestContent.cs @@ -74,7 +74,7 @@ StreamContent ToStreamContent(FileParameter fileParameter) { var dispositionHeader = fileParameter.Options.DisableFilenameEncoding ? ContentDispositionHeaderValue.Parse($"form-data; name=\"{fileParameter.Name}\"; filename=\"{fileParameter.FileName}\"") - : new ContentDispositionHeaderValue("form-data") { Name = $"\"{fileParameter.Name}\"", FileName = $"\"{fileParameter.FileName}\"" }; + : new("form-data") { Name = $"\"{fileParameter.Name}\"", FileName = $"\"{fileParameter.FileName}\"" }; if (!fileParameter.Options.DisableFilenameStar) dispositionHeader.FileNameStar = fileParameter.FileName; streamContent.Headers.ContentDisposition = dispositionHeader; @@ -125,7 +125,7 @@ MultipartFormDataContent CreateMultipartFormDataContent() { var boundary = GetOrSetFormBoundary(); var mpContent = new MultipartFormDataContent(boundary); var contentType = new MediaTypeHeaderValue("multipart/form-data"); - contentType.Parameters.Add(new NameValueHeaderValue(nameof(boundary), GetBoundary(boundary, request.MultipartFormQuoteBoundary))); + contentType.Parameters.Add(new(nameof(boundary), GetBoundary(boundary, request.MultipartFormQuoteBoundary))); mpContent.Headers.ContentType = contentType; return mpContent; } diff --git a/src/RestSharp/Request/RestRequest.cs b/src/RestSharp/Request/RestRequest.cs index eaad89972..786f11304 100644 --- a/src/RestSharp/Request/RestRequest.cs +++ b/src/RestSharp/Request/RestRequest.cs @@ -26,9 +26,6 @@ namespace RestSharp; /// Container for data used to make requests /// public class RestRequest { - Func? _advancedResponseHandler; - Func? _responseWriter; - /// /// Default constructor /// @@ -212,13 +209,13 @@ public RestRequest(Uri resource, Method method = Method.Get) /// Set this to write response to Stream rather than reading into memory. /// public Func? ResponseWriter { - get => _responseWriter; + get; set { if (AdvancedResponseWriter != null) { throw new ArgumentException("AdvancedResponseWriter is not null. Only one response writer can be used."); } - _responseWriter = value; + field = value; } } @@ -226,13 +223,13 @@ public RestRequest(Uri resource, Method method = Method.Get) /// Set this to handle the response stream yourself, based on the response details /// public Func? AdvancedResponseWriter { - get => _advancedResponseHandler; + get; set { if (ResponseWriter != null) { throw new ArgumentException("ResponseWriter is not null. Only one response writer can be used."); } - _advancedResponseHandler = value; + field = value; } } diff --git a/src/RestSharp/Request/RestRequestExtensions.Body.cs b/src/RestSharp/Request/RestRequestExtensions.Body.cs index dad5d006a..39e0a1cde 100644 --- a/src/RestSharp/Request/RestRequestExtensions.Body.cs +++ b/src/RestSharp/Request/RestRequestExtensions.Body.cs @@ -15,106 +15,104 @@ namespace RestSharp; public static partial class RestRequestExtensions { - /// - /// Adds a body parameter to the request - /// /// Request instance - /// Object to be used as the request body, or string for plain content - /// Optional: content type - /// - /// Thrown if request body type cannot be resolved - /// This method will try to figure out the right content type based on the request data format and the provided content type - public static RestRequest AddBody(this RestRequest request, object obj, ContentType? contentType = null) { - if (contentType == null) { - return request.RequestFormat switch { - DataFormat.Json => request.AddJsonBody(obj, contentType), - DataFormat.Xml => request.AddXmlBody(obj, contentType), - DataFormat.Binary => request.AddParameter(new BodyParameter("", obj, ContentType.Binary)), - _ => request.AddParameter(new BodyParameter("", obj.ToString()!, ContentType.Plain)) - }; + extension(RestRequest request) { + /// + /// Adds a body parameter to the request + /// + /// Object to be used as the request body, or string for plain content + /// Optional: content type + /// + /// Thrown if request body type cannot be resolved + /// This method will try to figure out the right content type based on the request data format and the provided content type + public RestRequest AddBody(object obj, ContentType? contentType = null) { + if (contentType == null) { + return request.RequestFormat switch { + DataFormat.Json => request.AddJsonBody(obj, contentType), + DataFormat.Xml => request.AddXmlBody(obj, contentType), + DataFormat.Binary => request.AddParameter(new BodyParameter("", obj, ContentType.Binary)), + _ => request.AddParameter(new BodyParameter("", obj.ToString()!, ContentType.Plain)) + }; + } + + return + obj is string str ? request.AddStringBody(str, contentType) : + obj is byte[] bytes ? request.AddParameter(new BodyParameter("", bytes, contentType, DataFormat.Binary)) : + contentType.Value.Contains("xml") ? request.AddXmlBody(obj, contentType) : + contentType.Value.Contains("json") ? request.AddJsonBody(obj, contentType) : + throw new ArgumentException("Non-string body found with unsupported content type", nameof(obj)); } - return - obj is string str ? request.AddStringBody(str, contentType) : - obj is byte[] bytes ? request.AddParameter(new BodyParameter("", bytes, contentType, DataFormat.Binary)) : - contentType.Value.Contains("xml") ? request.AddXmlBody(obj, contentType) : - contentType.Value.Contains("json") ? request.AddJsonBody(obj, contentType) : - throw new ArgumentException("Non-string body found with unsupported content type", nameof(obj)); - } + /// + /// Adds a string body and figures out the content type from the data format specified. You can, for example, add a JSON string + /// using this method as request body, using DataFormat.Json/> + /// + /// String body + /// for the content + /// + public RestRequest AddStringBody(string body, DataFormat dataFormat) { + var contentType = ContentType.FromDataFormat(dataFormat); + request.RequestFormat = dataFormat; + return request.AddParameter(new BodyParameter("", body, contentType)); + } - /// - /// Adds a string body and figures out the content type from the data format specified. You can, for example, add a JSON string - /// using this method as request body, using DataFormat.Json/> - /// - /// Request instance - /// String body - /// for the content - /// - public static RestRequest AddStringBody(this RestRequest request, string body, DataFormat dataFormat) { - var contentType = ContentType.FromDataFormat(dataFormat); - request.RequestFormat = dataFormat; - return request.AddParameter(new BodyParameter("", body, contentType)); - } + /// + /// Adds a string body to the request using the specified content type. + /// + /// String body + /// Content type of the body + /// + public RestRequest AddStringBody(string body, ContentType contentType) + => request.AddParameter(new BodyParameter(body, Ensure.NotNull(contentType, nameof(contentType)))); - /// - /// Adds a string body to the request using the specified content type. - /// - /// Request instance - /// String body - /// Content type of the body - /// - public static RestRequest AddStringBody(this RestRequest request, string body, ContentType contentType) - => request.AddParameter(new BodyParameter(body, Ensure.NotNull(contentType, nameof(contentType)))); + /// + /// Adds a JSON body parameter to the request from a string + /// + /// Force serialize the top-level string + /// Optional: content type. Default is ContentType.Json + /// JSON string to be used as a body + /// + public RestRequest AddJsonBody(string jsonString, bool forceSerialize, ContentType? contentType = null) { + request.RequestFormat = DataFormat.Json; - /// - /// Adds a JSON body parameter to the request from a string - /// - /// Request instance - /// Force serialize the top-level string - /// Optional: content type. Default is ContentType.Json - /// JSON string to be used as a body - /// - public static RestRequest AddJsonBody(this RestRequest request, string jsonString, bool forceSerialize, ContentType? contentType = null) { - request.RequestFormat = DataFormat.Json; + return !forceSerialize + ? request.AddStringBody(jsonString, DataFormat.Json) + : request.AddParameter(new JsonParameter(jsonString, contentType)); + } - return !forceSerialize - ? request.AddStringBody(jsonString, DataFormat.Json) - : request.AddParameter(new JsonParameter(jsonString, contentType)); - } + /// + /// Adds a JSON body parameter to the request + /// + /// Object that will be serialized to JSON + /// Optional: content type. Default is ContentType.Json + /// + public RestRequest AddJsonBody(T obj, ContentType? contentType = null) where T : class { + request.RequestFormat = DataFormat.Json; - /// - /// Adds a JSON body parameter to the request - /// - /// Request instance - /// Object that will be serialized to JSON - /// Optional: content type. Default is ContentType.Json - /// - public static RestRequest AddJsonBody(this RestRequest request, T obj, ContentType? contentType = null) where T : class { - request.RequestFormat = DataFormat.Json; + return obj is string str + ? request.AddStringBody(str, DataFormat.Json) + : request.AddParameter(new JsonParameter(obj, contentType)); + } - return obj is string str - ? request.AddStringBody(str, DataFormat.Json) - : request.AddParameter(new JsonParameter(obj, contentType)); - } + /// + /// Adds an XML body parameter to the request + /// + /// Object that will be serialized to XML + /// Optional: content type. Default is ContentType.Xml + /// Optional: XML namespace + /// + public RestRequest AddXmlBody(T obj, ContentType? contentType = null, string xmlNamespace = "") + where T : class { + request.RequestFormat = DataFormat.Xml; - /// - /// Adds an XML body parameter to the request - /// - /// Request instance - /// Object that will be serialized to XML - /// Optional: content type. Default is ContentType.Xml - /// Optional: XML namespace - /// - public static RestRequest AddXmlBody(this RestRequest request, T obj, ContentType? contentType = null, string xmlNamespace = "") - where T : class { - request.RequestFormat = DataFormat.Xml; + return obj is string str + ? request.AddStringBody(str, DataFormat.Xml) + : request.AddParameter(new XmlParameter(obj, xmlNamespace, contentType)); + } - return obj is string str - ? request.AddStringBody(str, DataFormat.Xml) - : request.AddParameter(new XmlParameter(obj, xmlNamespace, contentType)); + RestRequest AddBodyParameter(string? name, object value) + => name != null && name.Contains('/') + ? request.AddBody(value, name) + : request.AddParameter(new BodyParameter(name, value, ContentType.Plain)); } - static RestRequest AddBodyParameter(this RestRequest request, string? name, object value) - => name != null && name.Contains('/') - ? request.AddBody(value, name) - : request.AddParameter(new BodyParameter(name, value, ContentType.Plain)); } \ No newline at end of file diff --git a/src/RestSharp/Request/RestRequestExtensions.File.cs b/src/RestSharp/Request/RestRequestExtensions.File.cs index 816916adf..4674338ac 100644 --- a/src/RestSharp/Request/RestRequestExtensions.File.cs +++ b/src/RestSharp/Request/RestRequestExtensions.File.cs @@ -15,77 +15,74 @@ namespace RestSharp; public static partial class RestRequestExtensions { - /// - /// Adds a file parameter to the request body. The file will be read from disk as a stream. - /// /// Request instance - /// Parameter name - /// Full path to the file - /// Optional: content type - /// File parameter header options - /// - public static RestRequest AddFile( - this RestRequest request, - string name, - string path, - ContentType? contentType = null, - FileParameterOptions? options = null - ) - => request.AddFile(FileParameter.FromFile(path, name, contentType, options)); + extension(RestRequest request) { + /// + /// Adds a file parameter to the request body. The file will be read from disk as a stream. + /// + /// Parameter name + /// Full path to the file + /// Optional: content type + /// File parameter header options + /// + public RestRequest AddFile( + string name, + string path, + ContentType? contentType = null, + FileParameterOptions? options = null + ) + => request.AddFile(FileParameter.FromFile(path, name, contentType, options)); - /// - /// Adds bytes to the request as file attachment - /// - /// Request instance - /// Parameter name - /// File content as bytes - /// File name - /// Optional: content type. Default is "application/octet-stream" - /// File parameter header options - /// - public static RestRequest AddFile( - this RestRequest request, - string name, - byte[] bytes, - string fileName, - ContentType? contentType = null, - FileParameterOptions? options = null - ) - => request.AddFile(FileParameter.Create(name, bytes, fileName, contentType, options)); + /// + /// Adds bytes to the request as file attachment + /// + /// Parameter name + /// File content as bytes + /// File name + /// Optional: content type. Default is "application/octet-stream" + /// File parameter header options + /// + public RestRequest AddFile( + string name, + byte[] bytes, + string fileName, + ContentType? contentType = null, + FileParameterOptions? options = null + ) + => request.AddFile(FileParameter.Create(name, bytes, fileName, contentType, options)); - /// - /// Adds a file attachment to the request, where the file content will be retrieved from a given stream - /// - /// Request instance - /// Parameter name - /// Function that returns a stream with the file content - /// File name - /// Optional: content type. Default is "application/octet-stream" - /// File parameter header options - /// - public static RestRequest AddFile( - this RestRequest request, - string name, - Func getFile, - string fileName, - ContentType? contentType = null, - FileParameterOptions? options = null - ) - => request.AddFile(FileParameter.Create(name, getFile, fileName, contentType, options)); + /// + /// Adds a file attachment to the request, where the file content will be retrieved from a given stream + /// + /// Parameter name + /// Function that returns a stream with the file content + /// File name + /// Optional: content type. Default is "application/octet-stream" + /// File parameter header options + /// + public RestRequest AddFile( + string name, + Func getFile, + string fileName, + ContentType? contentType = null, + FileParameterOptions? options = null + ) + => request.AddFile(FileParameter.Create(name, getFile, fileName, contentType, options)); - internal static void ValidateParameters(this RestRequest request) { - if (!request.AlwaysSingleFileAsContent) return; + internal void ValidateParameters() { + if (!request.AlwaysSingleFileAsContent) return; - var postParametersExists = request.Parameters.GetContentParameters(request.Method).Any(); - var bodyParametersExists = request.Parameters.Any(p => p.Type == ParameterType.RequestBody); + var postParametersExists = request.Parameters.GetContentParameters(request.Method).Any(); + var bodyParametersExists = request.Parameters.Any(p => p.Type == ParameterType.RequestBody); - if (request.AlwaysMultipartFormData) - throw new ArgumentException("Failed to put file as content because flag AlwaysMultipartFormData is enabled"); + if (request.AlwaysMultipartFormData) + throw new ArgumentException("Failed to put file as content because flag AlwaysMultipartFormData is enabled"); - if (postParametersExists) - throw new ArgumentException("Failed to put file as content because POST parameters were added"); + if (postParametersExists) + throw new ArgumentException("Failed to put file as content because POST parameters were added"); - if (bodyParametersExists) - throw new ArgumentException("Failed to put file as content because body parameters were added"); + if (bodyParametersExists) + throw new ArgumentException("Failed to put file as content because body parameters were added"); + } } } \ No newline at end of file diff --git a/src/RestSharp/Request/RestRequestExtensions.Headers.cs b/src/RestSharp/Request/RestRequestExtensions.Headers.cs index d3e6b7815..2838db65f 100644 --- a/src/RestSharp/Request/RestRequestExtensions.Headers.cs +++ b/src/RestSharp/Request/RestRequestExtensions.Headers.cs @@ -15,93 +15,89 @@ namespace RestSharp; public static partial class RestRequestExtensions { - /// - /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource. - /// /// Request instance - /// Header name - /// Header values - /// - public static RestRequest AddHeader(this RestRequest request, string name, string[] values) { - foreach (var value in values) { - AddHeader(request, name, value); + extension(RestRequest request) { + /// + /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource. + /// + /// Header name + /// Header values + /// + public RestRequest AddHeader(string name, string[] values) { + foreach (var value in values) { + AddHeader(request, name, value); + } + + return request; } - return request; - } + /// + /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource. + /// + /// Header name + /// Header value + /// + public RestRequest AddHeader(string name, string value) + => request.AddParameter(new HeaderParameter(name, value)); - /// - /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource. - /// - /// Request instance - /// Header name - /// Header value - /// - public static RestRequest AddHeader(this RestRequest request, string name, string value) - => request.AddParameter(new HeaderParameter(name, value)); + /// + /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource. + /// + /// Header name + /// Header value + /// + public RestRequest AddHeader(string name, T value) where T : struct + => request.AddHeader(name, Ensure.NotNull(value.ToString(), nameof(value))); - /// - /// Adds a header to the request. RestSharp will try to separate request and content headers when calling the resource. - /// - /// Request instance - /// Header name - /// Header value - /// - public static RestRequest AddHeader(this RestRequest request, string name, T value) where T : struct - => request.AddHeader(name, Ensure.NotNull(value.ToString(), nameof(value))); + /// + /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource. + /// The existing header with the same name will be replaced. + /// + /// Header name + /// Header value + /// + public RestRequest AddOrUpdateHeader(string name, string value) + => request.AddOrUpdateParameter(new HeaderParameter(name, value)); - /// - /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource. - /// The existing header with the same name will be replaced. - /// - /// Request instance - /// Header name - /// Header value - /// - public static RestRequest AddOrUpdateHeader(this RestRequest request, string name, string value) - => request.AddOrUpdateParameter(new HeaderParameter(name, value)); + /// + /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource. + /// The existing header with the same name will be replaced. + /// + /// Header name + /// Header value + /// + public RestRequest AddOrUpdateHeader(string name, T value) where T : struct + => request.AddOrUpdateHeader(name, Ensure.NotNull(value.ToString(), nameof(value))); - /// - /// Adds or updates the request header. RestSharp will try to separate request and content headers when calling the resource. - /// The existing header with the same name will be replaced. - /// - /// Request instance - /// Header name - /// Header value - /// - public static RestRequest AddOrUpdateHeader(this RestRequest request, string name, T value) where T : struct - => request.AddOrUpdateHeader(name, Ensure.NotNull(value.ToString(), nameof(value))); + /// + /// Adds multiple headers to the request, using the key-value pairs provided. + /// + /// Collection of key-value pairs, where key will be used as header name, and value as header value + /// + public RestRequest AddHeaders(ICollection> headers) { + CheckAndThrowsDuplicateKeys(headers); - /// - /// Adds multiple headers to the request, using the key-value pairs provided. - /// - /// Request instance - /// Collection of key-value pairs, where key will be used as header name, and value as header value - /// - public static RestRequest AddHeaders(this RestRequest request, ICollection> headers) { - CheckAndThrowsDuplicateKeys(headers); + foreach (var header in headers) { + request.AddHeader(header.Key, header.Value); + } - foreach (var header in headers) { - request.AddHeader(header.Key, header.Value); + return request; } - return request; - } + /// + /// Adds or updates multiple headers to the request, using the key-value pairs provided. Existing headers with the same name will be replaced. + /// + /// Collection of key-value pairs, where key will be used as header name, and value as header value + /// + public RestRequest AddOrUpdateHeaders(ICollection> headers) { + CheckAndThrowsDuplicateKeys(headers); - /// - /// Adds or updates multiple headers to the request, using the key-value pairs provided. Existing headers with the same name will be replaced. - /// - /// Request instance - /// Collection of key-value pairs, where key will be used as header name, and value as header value - /// - public static RestRequest AddOrUpdateHeaders(this RestRequest request, ICollection> headers) { - CheckAndThrowsDuplicateKeys(headers); + foreach (var pair in headers) { + request.AddOrUpdateHeader(pair.Key, pair.Value); + } - foreach (var pair in headers) { - request.AddOrUpdateHeader(pair.Key, pair.Value); + return request; } - - return request; } static void CheckAndThrowsDuplicateKeys(ICollection> headers) { diff --git a/src/RestSharp/Request/RestRequestExtensions.Object.cs b/src/RestSharp/Request/RestRequestExtensions.Object.cs index 173035790..fbfd2715f 100644 --- a/src/RestSharp/Request/RestRequestExtensions.Object.cs +++ b/src/RestSharp/Request/RestRequestExtensions.Object.cs @@ -15,51 +15,51 @@ namespace RestSharp; public static partial class RestRequestExtensions { - /// - /// Gets object properties and adds each property as a form data parameter - /// /// Request instance - /// Object to add as form data - /// Properties to include, or nothing to include everything. The array will be sorted. - /// - public static RestRequest AddObject(this RestRequest request, T obj, params string[] includedProperties) where T : class { - var props = obj.GetProperties(includedProperties); + extension(RestRequest request) { + /// + /// Gets object properties and adds each property as a form data parameter + /// + /// Object to add as form data + /// Properties to include, or nothing to include everything. The array will be sorted. + /// + public RestRequest AddObject(T obj, params string[] includedProperties) where T : class { + var props = obj.GetProperties(includedProperties); - foreach (var prop in props) { - request.AddParameter(prop.Name, prop.Value, prop.Encode); - } + foreach (var prop in props) { + request.AddParameter(prop.Name, prop.Value, prop.Encode); + } - return request; - } + return request; + } - /// - /// Gets object properties and adds each property as a form data parameter - /// - /// - /// This method gets public instance properties from the provided type - /// rather than from itself, which allows for caching of properties and - /// other optimizations. If you don't know the type at runtime, or wish to use properties not - /// available from the provided type parameter, consider using - /// - /// Request instance - /// Object to add as form data - /// Properties to include, or nothing to include everything. The array will be sorted. - /// - public static RestRequest AddObjectStatic(this RestRequest request, T obj, params string[] includedProperties) where T : class - => request.AddParameters(PropertyCache.GetParameters(obj, includedProperties)); + /// + /// Gets object properties and adds each property as a form data parameter + /// + /// + /// This method gets public instance properties from the provided type + /// rather than from itself, which allows for caching of properties and + /// other optimizations. If you don't know the type at runtime, or wish to use properties not + /// available from the provided type parameter, consider using + /// + /// Object to add as form data + /// Properties to include, or nothing to include everything. The array will be sorted. + /// + public RestRequest AddObjectStatic(T obj, params string[] includedProperties) where T : class + => request.AddParameters(PropertyCache.GetParameters(obj, includedProperties)); - /// - /// Gets object properties and adds each property as a form data parameter - /// - /// - /// This method gets public instance properties from the provided type - /// rather than from itself, which allows for caching of properties and - /// other optimizations. If you don't know the type at runtime, or wish to use properties not - /// available from the provided type parameter, consider using - /// - /// Request instance - /// Object to add as form data - /// - public static RestRequest AddObjectStatic(this RestRequest request, T obj) where T : class - => request.AddParameters(PropertyCache.GetParameters(obj)); + /// + /// Gets object properties and adds each property as a form data parameter + /// + /// + /// This method gets public instance properties from the provided type + /// rather than from itself, which allows for caching of properties and + /// other optimizations. If you don't know the type at runtime, or wish to use properties not + /// available from the provided type parameter, consider using + /// + /// Object to add as form data + /// + public RestRequest AddObjectStatic(T obj) where T : class + => request.AddParameters(PropertyCache.GetParameters(obj)); + } } \ No newline at end of file diff --git a/src/RestSharp/Request/RestRequestExtensions.Query.cs b/src/RestSharp/Request/RestRequestExtensions.Query.cs index 96ffae191..265dc360d 100644 --- a/src/RestSharp/Request/RestRequestExtensions.Query.cs +++ b/src/RestSharp/Request/RestRequestExtensions.Query.cs @@ -15,27 +15,28 @@ namespace RestSharp; public static partial class RestRequestExtensions { - /// - /// Adds a query string parameter to the request. The request resource should not contain any placeholders for this parameter. - /// The parameter will be added to the request URL as a query string using name=value format. - /// /// Request instance - /// Parameter name - /// Parameter value - /// Encode the value or not, default true - /// - public static RestRequest AddQueryParameter(this RestRequest request, string name, string? value, bool encode = true) - => request.AddParameter(new QueryParameter(name, value, encode)); + extension(RestRequest request) { + /// + /// Adds a query string parameter to the request. The request resource should not contain any placeholders for this parameter. + /// The parameter will be added to the request URL as a query string using name=value format. + /// + /// Parameter name + /// Parameter value + /// Encode the value or not, default true + /// + public RestRequest AddQueryParameter(string name, string? value, bool encode = true) + => request.AddParameter(new QueryParameter(name, value, encode)); - /// - /// Adds a query string parameter to the request. The request resource should not contain any placeholders for this parameter. - /// The parameter will be added to the request URL as a query string using name=value format. - /// - /// Request instance - /// Parameter name - /// Parameter value - /// Encode the value or not, default true - /// - public static RestRequest AddQueryParameter(this RestRequest request, string name, T value, bool encode = true) where T : struct - => request.AddQueryParameter(name, value.ToString(), encode); + /// + /// Adds a query string parameter to the request. The request resource should not contain any placeholders for this parameter. + /// The parameter will be added to the request URL as a query string using name=value format. + /// + /// Parameter name + /// Parameter value + /// Encode the value or not, default true + /// + public RestRequest AddQueryParameter(string name, T value, bool encode = true) where T : struct + => request.AddQueryParameter(name, value.ToString(), encode); + } } \ No newline at end of file diff --git a/src/RestSharp/Request/RestRequestExtensions.Url.cs b/src/RestSharp/Request/RestRequestExtensions.Url.cs index 9470b7af9..ff7d4e829 100644 --- a/src/RestSharp/Request/RestRequestExtensions.Url.cs +++ b/src/RestSharp/Request/RestRequestExtensions.Url.cs @@ -15,27 +15,28 @@ namespace RestSharp; public static partial class RestRequestExtensions { - /// - /// Adds a URL segment parameter to the request. The resource URL must have a placeholder for the parameter for it to work. - /// For example, if you add a URL segment parameter with the name "id", the resource URL should contain {id} in its path. - /// /// Request instance - /// Name of the parameter; must be matching a placeholder in the resource URL as {name} - /// Value of the parameter - /// Encode the value or not, default true - /// - public static RestRequest AddUrlSegment(this RestRequest request, string name, string? value, bool encode = true) - => request.AddParameter(new UrlSegmentParameter(name, value, encode)); + extension(RestRequest request) { + /// + /// Adds a URL segment parameter to the request. The resource URL must have a placeholder for the parameter for it to work. + /// For example, if you add a URL segment parameter with the name "id", the resource URL should contain {id} in its path. + /// + /// Name of the parameter; must be matching a placeholder in the resource URL as {name} + /// Value of the parameter + /// Encode the value or not, default true + /// + public RestRequest AddUrlSegment(string name, string? value, bool encode = true) + => request.AddParameter(new UrlSegmentParameter(name, value, encode)); - /// - /// Adds a URL segment parameter to the request. The resource URL must have a placeholder for the parameter for it to work. - /// For example, if you add a URL segment parameter with the name "id", the resource URL should contain {id} in its path. - /// - /// Request instance - /// Name of the parameter; must be matching a placeholder in the resource URL as {name} - /// Value of the parameter - /// Encode the value or not, default true - /// - public static RestRequest AddUrlSegment(this RestRequest request, string name, T value, bool encode = true) where T : struct - => request.AddUrlSegment(name, value.ToString(), encode); + /// + /// Adds a URL segment parameter to the request. The resource URL must have a placeholder for the parameter for it to work. + /// For example, if you add a URL segment parameter with the name "id", the resource URL should contain {id} in its path. + /// + /// Name of the parameter; must be matching a placeholder in the resource URL as {name} + /// Value of the parameter + /// Encode the value or not, default true + /// + public RestRequest AddUrlSegment(string name, T value, bool encode = true) where T : struct + => request.AddUrlSegment(name, value.ToString(), encode); + } } \ No newline at end of file diff --git a/src/RestSharp/Request/RestRequestExtensions.cs b/src/RestSharp/Request/RestRequestExtensions.cs index 57d2572a8..82323d07b 100644 --- a/src/RestSharp/Request/RestRequestExtensions.cs +++ b/src/RestSharp/Request/RestRequestExtensions.cs @@ -16,132 +16,126 @@ namespace RestSharp; [PublicAPI] public static partial class RestRequestExtensions { - /// - /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) - /// /// - /// Name of the parameter - /// Value of the parameter - /// Encode the value or not, default true - /// This request - public static RestRequest AddParameter(this RestRequest request, string name, string? value, bool encode = true) - => request.AddParameter(new GetOrPostParameter(name, value, encode)); + extension(RestRequest request) { + /// + /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) + /// + /// Name of the parameter + /// Value of the parameter + /// Encode the value or not, default true + /// This request + public RestRequest AddParameter(string name, string? value, bool encode = true) + => request.AddParameter(new GetOrPostParameter(name, value, encode)); - /// - /// Adds a parameter of a given type to the request. It will create a typed parameter instance based on the type argument. - /// It is not recommended to use this overload unless you must, as it doesn't provide any restrictions, and if the name-value-type - /// combination doesn't match, it will throw. - /// - /// Request instance - /// Name of the parameter, must be matching a placeholder in the resource URL as {name} - /// Value of the parameter - /// Enum value specifying what kind of parameter is being added - /// Encode the value or not, default true - /// - public static RestRequest AddParameter(this RestRequest request, string? name, object value, ParameterType type, bool encode = true) - => type == ParameterType.RequestBody - ? request.AddBodyParameter(name, value) - : request.AddParameter(Parameter.CreateParameter(name, value, type, encode)); + /// + /// Adds a parameter of a given type to the request. It will create a typed parameter instance based on the type argument. + /// It is not recommended to use this overload unless you must, as it doesn't provide any restrictions, and if the name-value-type + /// combination doesn't match, it will throw. + /// + /// Name of the parameter, must be matching a placeholder in the resource URL as {name} + /// Value of the parameter + /// Enum value specifying what kind of parameter is being added + /// Encode the value or not, default true + /// + public RestRequest AddParameter(string? name, object value, ParameterType type, bool encode = true) + => type == ParameterType.RequestBody + ? request.AddBodyParameter(name, value) + : request.AddParameter(Parameter.CreateParameter(name, value, type, encode)); - /// - /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT). - /// The value will be converted to string. - /// - /// Request instance - /// Name of the parameter - /// Value of the parameter - /// Encode the value or not, default true - /// This request - public static RestRequest AddParameter(this RestRequest request, string name, T value, bool encode = true) where T : struct - => request.AddParameter(name, value.ToString(), encode); + /// + /// Adds a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT). + /// The value will be converted to string. + /// + /// Name of the parameter + /// Value of the parameter + /// Encode the value or not, default true + /// This request + public RestRequest AddParameter(string name, T value, bool encode = true) where T : struct + => request.AddParameter(name, value.ToString(), encode); - /// - /// Adds or updates a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) - /// - /// Request instance - /// Name of the parameter - /// Value of the parameter - /// Encode the value or not, default true - /// This request - public static RestRequest AddOrUpdateParameter(this RestRequest request, string name, string? value, bool encode = true) - => request.AddOrUpdateParameter(new GetOrPostParameter(name, value, encode)); + /// + /// Adds or updates a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) + /// + /// Name of the parameter + /// Value of the parameter + /// Encode the value or not, default true + /// This request + public RestRequest AddOrUpdateParameter(string name, string? value, bool encode = true) + => request.AddOrUpdateParameter(new GetOrPostParameter(name, value, encode)); - /// - /// Adds or updates a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) - /// - /// Request instance - /// Name of the parameter - /// Value of the parameter - /// Encode the value or not, default true - /// This request - public static RestRequest AddOrUpdateParameter(this RestRequest request, string name, T value, bool encode = true) where T : struct - => request.AddOrUpdateParameter(name, value.ToString(), encode); + /// + /// Adds or updates a HTTP parameter to the request (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) + /// + /// Name of the parameter + /// Value of the parameter + /// Encode the value or not, default true + /// This request + public RestRequest AddOrUpdateParameter(string name, T value, bool encode = true) where T : struct + => request.AddOrUpdateParameter(name, value.ToString(), encode); - static RestRequest AddParameters(this RestRequest request, IEnumerable parameters) { - request.Parameters.AddParameters(parameters); - return request; - } + RestRequest AddParameters(IEnumerable parameters) { + request.Parameters.AddParameters(parameters); + return request; + } - /// - /// Adds or updates request parameter of a given type. It will create a typed parameter instance based on the type argument. - /// Parameter will be added or updated based on its name. If the request has a parameter with the same name, it will be updated. - /// It is not recommended to use this overload unless you must, as it doesn't provide any restrictions, and if the name-value-type - /// combination doesn't match, it will throw. - /// - /// Request instance - /// Name of the parameter, must be matching a placeholder in the resource URL as {name} - /// Value of the parameter - /// Enum value specifying what kind of parameter is being added - /// Encode the value or not, default true - /// - public static RestRequest AddOrUpdateParameter(this RestRequest request, string name, object value, ParameterType type, bool encode = true) { - request.RemoveParameter(name, type); + /// + /// Adds or updates request parameter of a given type. It will create a typed parameter instance based on the type argument. + /// Parameter will be added or updated based on its name. If the request has a parameter with the same name, it will be updated. + /// It is not recommended to use this overload unless you must, as it doesn't provide any restrictions, and if the name-value-type + /// combination doesn't match, it will throw. + /// + /// Name of the parameter, must be matching a placeholder in the resource URL as {name} + /// Value of the parameter + /// Enum value specifying what kind of parameter is being added + /// Encode the value or not, default true + /// + public RestRequest AddOrUpdateParameter(string name, object value, ParameterType type, bool encode = true) { + request.RemoveParameter(name, type); - return type == ParameterType.RequestBody - ? request.AddBodyParameter(name, value) - : request.AddOrUpdateParameter(Parameter.CreateParameter(name, value, type, encode)); - } + return type == ParameterType.RequestBody + ? request.AddBodyParameter(name, value) + : request.AddOrUpdateParameter(Parameter.CreateParameter(name, value, type, encode)); + } - /// - /// Adds or updates request parameter, given the parameter instance, for example or . - /// It will replace an existing parameter with the same name. - /// - /// Request instance - /// Parameter instance - /// - public static RestRequest AddOrUpdateParameter(this RestRequest request, Parameter parameter) - => request.RemoveParameter(parameter.Name, parameter.Type).AddParameter(parameter); + /// + /// Adds or updates request parameter, given the parameter instance, for example or . + /// It will replace an existing parameter with the same name. + /// + /// Parameter instance + /// + public RestRequest AddOrUpdateParameter(Parameter parameter) + => request.RemoveParameter(parameter.Name, parameter.Type).AddParameter(parameter); - /// - /// Adds or updates multiple request parameters, given the parameter instance, for example - /// or . Parameters with the same name will be replaced. - /// - /// Request instance - /// Collection of parameter instances - /// - public static RestRequest AddOrUpdateParameters(this RestRequest request, IEnumerable parameters) { - foreach (var parameter in parameters) request.AddOrUpdateParameter(parameter); + /// + /// Adds or updates multiple request parameters, given the parameter instance, for example + /// or . Parameters with the same name will be replaced. + /// + /// Collection of parameter instances + /// + public RestRequest AddOrUpdateParameters(IEnumerable parameters) { + foreach (var parameter in parameters) request.AddOrUpdateParameter(parameter); - return request; - } + return request; + } - static RestRequest RemoveParameter(this RestRequest request, string? name, ParameterType type) { - var p = request.Parameters.FirstOrDefault(x => x.Name == name && x.Type == type); - return p != null ? request.RemoveParameter(p) : request; - } + RestRequest RemoveParameter(string? name, ParameterType type) { + var p = request.Parameters.FirstOrDefault(x => x.Name == name && x.Type == type); + return p != null ? request.RemoveParameter(p) : request; + } - /// - /// Adds cookie to the cookie container. - /// - /// RestRequest to add the cookies to - /// Cookie name - /// Cookie value - /// Cookie path - /// Cookie domain, must not be an empty string - /// - public static RestRequest AddCookie(this RestRequest request, string name, string value, string path, string domain) { - request.CookieContainer ??= new CookieContainer(); - request.CookieContainer.Add(new Cookie(name, value, path, domain)); - return request; + /// + /// Adds cookie to the cookie container. + /// + /// Cookie name + /// Cookie value + /// Cookie path + /// Cookie domain, must not be an empty string + /// + public RestRequest AddCookie(string name, string value, string path, string domain) { + request.CookieContainer ??= new(); + request.CookieContainer.Add(new Cookie(name, value, path, domain)); + return request; + } } } \ No newline at end of file diff --git a/src/RestSharp/Request/UriExtensions.cs b/src/RestSharp/Request/UriExtensions.cs index 84a0d4977..bc48800cd 100644 --- a/src/RestSharp/Request/UriExtensions.cs +++ b/src/RestSharp/Request/UriExtensions.cs @@ -29,9 +29,9 @@ public static Uri MergeBaseUrlAndResource(this Uri? baseUrl, string? resource) { : throw new ArgumentException("Both BaseUrl and Resource are empty", nameof(resource)); } - var usingBaseUri = baseUrl.AbsoluteUri[^1] == '/' || assembled.IsEmpty() ? baseUrl : new Uri(baseUrl.AbsoluteUri + "/"); + var usingBaseUri = baseUrl.AbsoluteUri[^1] == '/' || assembled.IsEmpty() ? baseUrl : new(baseUrl.AbsoluteUri + "/"); - return assembled != null ? new Uri(usingBaseUri, assembled) : baseUrl; + return assembled != null ? new(usingBaseUri, assembled) : baseUrl; } public static Uri AddQueryString(this Uri uri, string? query) { diff --git a/src/RestSharp/Response/ResponseThrowExtension.cs b/src/RestSharp/Response/ResponseThrowExtension.cs index 7c4e99aa9..01d5167af 100644 --- a/src/RestSharp/Response/ResponseThrowExtension.cs +++ b/src/RestSharp/Response/ResponseThrowExtension.cs @@ -16,17 +16,17 @@ namespace RestSharp; public static class ResponseThrowExtension { - public static RestResponse ThrowIfError(this RestResponse response) { - var exception = response.GetException(); - if (exception != null) throw exception; - - return response; + extension(RestResponse response) { + public RestResponse ThrowIfError() { + var exception = response.GetException(); + return exception != null ? throw exception : response; + } } - public static RestResponse ThrowIfError(this RestResponse response) { - var exception = response.GetException(); - if (exception != null) throw exception; - - return response; + extension(RestResponse response) { + public RestResponse ThrowIfError() { + var exception = response.GetException(); + return exception != null ? throw exception : response; + } } } diff --git a/src/RestSharp/Response/RestResponseExtensions.cs b/src/RestSharp/Response/RestResponseExtensions.cs index 32735f571..ed9b32721 100644 --- a/src/RestSharp/Response/RestResponseExtensions.cs +++ b/src/RestSharp/Response/RestResponseExtensions.cs @@ -15,49 +15,48 @@ namespace RestSharp; public static class RestResponseExtensions { - /// - /// Gets the value of the header with the specified name. - /// /// Response object - /// Name of the header - /// Header value or null if the header is not found in the response - public static string? GetHeaderValue(this RestResponse response, string headerName) - => response.Headers?.FirstOrDefault(x => NameIs(x.Name, headerName))?.Value.ToString(); + extension(RestResponse response) { + /// + /// Gets the value of the header with the specified name. + /// + /// Name of the header + /// Header value or null if the header is not found in the response + public string? GetHeaderValue(string headerName) + => response.Headers?.FirstOrDefault(x => NameIs(x.Name, headerName))?.Value.ToString(); - /// - /// Gets all the values of the header with the specified name. - /// - /// Response object - /// Name of the header - /// Array of header values or empty array if the header is not found in the response - public static string[] GetHeaderValues(this RestResponse response, string headerName) - => response.Headers - ?.Where(x => NameIs(x.Name, headerName)) - .Select(x => x.Value.ToString() ?? "") - .ToArray() ?? - []; + /// + /// Gets all the values of the header with the specified name. + /// + /// Name of the header + /// Array of header values or empty array if the header is not found in the response + public string[] GetHeaderValues(string headerName) + => response.Headers + ?.Where(x => NameIs(x.Name, headerName)) + .Select(x => x.Value.ToString() ?? "") + .ToArray() ?? + []; - /// - /// Gets the value of the content header with the specified name. - /// - /// Response object - /// Name of the header - /// Header value or null if the content header is not found in the response - public static string? GetContentHeaderValue(this RestResponse response, string headerName) - => response.ContentHeaders?.FirstOrDefault(x => NameIs(x.Name, headerName))?.Value.ToString(); + /// + /// Gets the value of the content header with the specified name. + /// + /// Name of the header + /// Header value or null if the content header is not found in the response + public string? GetContentHeaderValue(string headerName) + => response.ContentHeaders?.FirstOrDefault(x => NameIs(x.Name, headerName))?.Value.ToString(); - /// - /// Gets all the values of the content header with the specified name. - /// - /// Response object - /// Name of the header - /// Array of header values or empty array if the content header is not found in the response - public static string[] GetContentHeaderValues(this RestResponse response, string headerName) - => response.ContentHeaders - ?.Where(x => NameIs(x.Name, headerName)) - .Select(x => x.Value.ToString() ?? "") - .ToArray() ?? - []; + /// + /// Gets all the values of the content header with the specified name. + /// + /// Name of the header + /// Array of header values or empty array if the content header is not found in the response + public string[] GetContentHeaderValues(string headerName) + => response.ContentHeaders + ?.Where(x => NameIs(x.Name, headerName)) + .Select(x => x.Value.ToString() ?? "") + .ToArray() ?? + []; + } static bool NameIs(string? name, string headerName) => name != null && name.Equals(headerName, StringComparison.InvariantCultureIgnoreCase); diff --git a/src/RestSharp/RestClient.Async.cs b/src/RestSharp/RestClient.Async.cs index 3bbb3f210..8d064720c 100644 --- a/src/RestSharp/RestClient.Async.cs +++ b/src/RestSharp/RestClient.Async.cs @@ -125,7 +125,7 @@ async Task ExecuteRequestAsync(RestRequest request, CancellationTo HttpResponseMessage? responseMessage; // Make sure we have a cookie container if not provided in the request - var cookieContainer = request.CookieContainer ??= new CookieContainer(); + var cookieContainer = request.CookieContainer ??= new(); var headers = new RequestHeaders() .AddHeaders(request.Parameters) @@ -152,14 +152,14 @@ async Task ExecuteRequestAsync(RestRequest request, CancellationTo } } catch (Exception ex) { - return new HttpResponse(null, url, null, ex, timeoutCts.Token); + return new(null, url, null, ex, timeoutCts.Token); } #pragma warning disable CS0618 // Type or member is obsolete if (request.OnAfterRequest != null) await request.OnAfterRequest(responseMessage).ConfigureAwait(false); #pragma warning restore CS0618 // Type or member is obsolete await OnAfterHttpRequest(request, responseMessage, cancellationToken).ConfigureAwait(false); - return new HttpResponse(responseMessage, url, cookieContainer, null, timeoutCts.Token); + return new(responseMessage, url, cookieContainer, null, timeoutCts.Token); } static async ValueTask OnBeforeRequest(RestRequest request, CancellationToken cancellationToken) { @@ -215,11 +215,11 @@ internal static HttpMethod AsHttpMethod(Method method) #if NET Method.Patch => HttpMethod.Patch, #else - Method.Patch => new HttpMethod("PATCH"), + Method.Patch => new("PATCH"), #endif - Method.Merge => new HttpMethod("MERGE"), - Method.Copy => new HttpMethod("COPY"), - Method.Search => new HttpMethod("SEARCH"), + Method.Merge => new("MERGE"), + Method.Copy => new("COPY"), + Method.Search => new("SEARCH"), _ => throw new ArgumentOutOfRangeException(nameof(method)) }; } \ No newline at end of file diff --git a/src/RestSharp/RestClient.Extensions.Delete.cs b/src/RestSharp/RestClient.Extensions.Delete.cs index 839543519..c92636545 100644 --- a/src/RestSharp/RestClient.Extensions.Delete.cs +++ b/src/RestSharp/RestClient.Extensions.Delete.cs @@ -16,179 +16,164 @@ namespace RestSharp; public static partial class RestClientExtensions { - /// - /// Executes a DELETE-style request asynchronously, authenticating if needed - /// /// - /// Request to be executed - /// Cancellation token - public static Task ExecuteDeleteAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) - => client.ExecuteAsync(request, Method.Delete, cancellationToken); - - /// - /// Executes a DELETE-style request asynchronously, authenticating if needed - /// - /// - /// Request resource - /// Cancellation token - public static Task ExecuteDeleteAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default) - => client.ExecuteAsync(new(resource), Method.Delete, cancellationToken); - - /// - /// Executes a DELETE-style synchronously, authenticating if needed - /// - /// - /// Request resource - public static RestResponse ExecuteDelete(this IRestClient client, string resource) - => AsyncHelpers.RunSync(() => client.ExecuteDeleteAsync(resource)); - - /// - /// Executes a DELETE-style synchronously, authenticating if needed - /// - /// - /// Request to be executed - public static RestResponse ExecuteDelete(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Delete)); - - /// - /// Executes a DELETE-style request asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// The cancellation token - /// Deserialized response content - public static Task> ExecuteDeleteAsync( - this IRestClient client, - RestRequest request, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(request, Method.Delete, cancellationToken); - - /// - /// Executes a DELETE-style request asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request resource - /// The cancellation token - /// Deserialized response content - public static Task> ExecuteDeleteAsync( - this IRestClient client, - string resource, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(new(resource), Method.Delete, cancellationToken); - - /// - /// Executes a DELETE-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// Deserialized response content - public static RestResponse ExecuteDelete(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Delete)); - - /// - /// Executes a DELETE-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request resource - /// Deserialized response content - public static RestResponse ExecuteDelete(this IRestClient client, string resource) - => AsyncHelpers.RunSync(() => client.ExecuteDeleteAsync(resource)); - - /// - /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// Expected result type - /// - public static async Task DeleteAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Delete, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError().Data; + extension(IRestClient client) { + /// + /// Executes a DELETE-style request asynchronously, authenticating if needed + /// + /// Request to be executed + /// Cancellation token + public Task ExecuteDeleteAsync(RestRequest request, CancellationToken cancellationToken = default) + => client.ExecuteAsync(request, Method.Delete, cancellationToken); + + /// + /// Executes a DELETE-style request asynchronously, authenticating if needed + /// + /// Request resource + /// Cancellation token + public Task ExecuteDeleteAsync(string resource, CancellationToken cancellationToken = default) + => client.ExecuteAsync(new(resource), Method.Delete, cancellationToken); + + /// + /// Executes a DELETE-style synchronously, authenticating if needed + /// + /// Request resource + public RestResponse ExecuteDelete(string resource) + => AsyncHelpers.RunSync(() => client.ExecuteDeleteAsync(resource)); + + /// + /// Executes a DELETE-style synchronously, authenticating if needed + /// + /// Request to be executed + public RestResponse ExecuteDelete(RestRequest request) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Delete)); + + /// + /// Executes a DELETE-style request asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// The cancellation token + /// Deserialized response content + public Task> ExecuteDeleteAsync( + RestRequest request, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(request, Method.Delete, cancellationToken); + + /// + /// Executes a DELETE-style request asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request resource + /// The cancellation token + /// Deserialized response content + public Task> ExecuteDeleteAsync( + string resource, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(new(resource), Method.Delete, cancellationToken); + + /// + /// Executes a DELETE-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// Deserialized response content + public RestResponse ExecuteDelete(RestRequest request) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Delete)); + + /// + /// Executes a DELETE-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request resource + /// Deserialized response content + public RestResponse ExecuteDelete(string resource) + => AsyncHelpers.RunSync(() => client.ExecuteDeleteAsync(resource)); + + /// + /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Cancellation token + /// Expected result type + /// + public async Task DeleteAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Delete, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError().Data; + } + + /// + /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// Request resource + /// Cancellation token + /// Expected result type + /// + public async Task DeleteAsync(string resource, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(new(resource), Method.Delete, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError().Data; + } + + /// + /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Expected result type + /// + public T? Delete(RestRequest request) => AsyncHelpers.RunSync(() => client.DeleteAsync(request)); + + /// + /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// Request resource + /// Expected result type + /// + public T? Delete(string resource) => AsyncHelpers.RunSync(() => client.DeleteAsync(resource)); + + /// + /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. + /// + /// Request resource + /// Cancellation token + /// + public async Task DeleteAsync(string resource, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(new(resource), Method.Delete, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError(); + } + + /// + /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. + /// + /// Request resource + /// + public RestResponse Delete(string resource) => AsyncHelpers.RunSync(() => client.DeleteAsync(resource)); + + /// + /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// Cancellation token + /// + public async Task DeleteAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Delete, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError(); + } + + /// + /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// + public RestResponse Delete(RestRequest request) => AsyncHelpers.RunSync(() => client.DeleteAsync(request)); } - - /// - /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// Request resource - /// Cancellation token - /// Expected result type - /// - public static async Task DeleteAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(new(resource), Method.Delete, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError().Data; - } - - /// - /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Expected result type - /// - public static T? Delete(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.DeleteAsync(request)); - - /// - /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// Request resource - /// Expected result type - /// - public static T? Delete(this IRestClient client, string resource) => AsyncHelpers.RunSync(() => client.DeleteAsync(resource)); - - /// - /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// Request resource - /// Cancellation token - /// - public static async Task DeleteAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(new(resource), Method.Delete, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError(); - } - - /// - /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// Request resource - /// - public static RestResponse Delete(this IRestClient client, string resource) => AsyncHelpers.RunSync(() => client.DeleteAsync(resource)); - - /// - /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// - public static async Task DeleteAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Delete, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError(); - } - - /// - /// Execute the request using DELETE HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// - public static RestResponse Delete(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.DeleteAsync(request)); } \ No newline at end of file diff --git a/src/RestSharp/RestClient.Extensions.Get.cs b/src/RestSharp/RestClient.Extensions.Get.cs index 1a4306844..1dae80183 100644 --- a/src/RestSharp/RestClient.Extensions.Get.cs +++ b/src/RestSharp/RestClient.Extensions.Get.cs @@ -16,212 +16,195 @@ namespace RestSharp; public static partial class RestClientExtensions { - /// - /// Executes a GET-style asynchronously, authenticating if needed. - /// /// - /// Request to be executed - /// Cancellation token - public static Task ExecuteGetAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) - => client.ExecuteAsync(request, Method.Get, cancellationToken); - - /// - /// Executes a GET-style asynchronously, authenticating if needed. - /// - /// - /// Request resource - /// Cancellation token - public static Task ExecuteGetAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default) - => client.ExecuteAsync(new RestRequest(resource), Method.Get, cancellationToken); - - /// - /// Executes a GET-style synchronously, authenticating if needed - /// - /// - /// Request to be executed - public static RestResponse ExecuteGet(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Get)); - - /// - /// Executes a GET-style request asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// Cancellation token - /// Deserialized response content - public static Task> ExecuteGetAsync( - this IRestClient client, - RestRequest request, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(request, Method.Get, cancellationToken); - - /// - /// Executes a GET-style request to the specified resource URL asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request resource - /// Cancellation token - /// Deserialized response content - public static Task> ExecuteGetAsync( - this IRestClient client, - string resource, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(new RestRequest(resource), Method.Get, cancellationToken); - - /// - /// Executes a GET-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// Deserialized response content - public static RestResponse ExecuteGet(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Get)); - - /// - /// Executes a GET-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request resource - /// Deserialized response content - public static RestResponse ExecuteGet(this IRestClient client, string resource) - => AsyncHelpers.RunSync(() => client.ExecuteGetAsync(resource)); - - /// - /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// - public static async Task GetAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteGetAsync(request, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError(); - } + extension(IRestClient client) { + /// + /// Executes a GET-style asynchronously, authenticating if needed. + /// + /// Request to be executed + /// Cancellation token + public Task ExecuteGetAsync(RestRequest request, CancellationToken cancellationToken = default) + => client.ExecuteAsync(request, Method.Get, cancellationToken); + + /// + /// Executes a GET-style asynchronously, authenticating if needed. + /// + /// Request resource + /// Cancellation token + public Task ExecuteGetAsync(string resource, CancellationToken cancellationToken = default) + => client.ExecuteAsync(new(resource), Method.Get, cancellationToken); + + /// + /// Executes a GET-style synchronously, authenticating if needed + /// + /// Request to be executed + public RestResponse ExecuteGet(RestRequest request) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Get)); + + /// + /// Executes a GET-style request asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// Cancellation token + /// Deserialized response content + public Task> ExecuteGetAsync( + RestRequest request, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(request, Method.Get, cancellationToken); + + /// + /// Executes a GET-style request to the specified resource URL asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request resource + /// Cancellation token + /// Deserialized response content + public Task> ExecuteGetAsync( + string resource, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(new(resource), Method.Get, cancellationToken); + + /// + /// Executes a GET-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// Deserialized response content + public RestResponse ExecuteGet(RestRequest request) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Get)); + + /// + /// Executes a GET-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request resource + /// Deserialized response content + public RestResponse ExecuteGet(string resource) + => AsyncHelpers.RunSync(() => client.ExecuteGetAsync(resource)); + + /// + /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// Cancellation token + /// + public async Task GetAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteGetAsync(request, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError(); + } - /// - /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// - public static RestResponse Get(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.GetAsync(request)); - - /// - /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// Expected result type - /// - public static async Task GetAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteGetAsync(request, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError().Data; - } + /// + /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// + public RestResponse Get(RestRequest request) => AsyncHelpers.RunSync(() => client.GetAsync(request)); + + /// + /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Cancellation token + /// Expected result type + /// + public async Task GetAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteGetAsync(request, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError().Data; + } - /// - /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Expected result type - /// - public static T? Get(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.GetAsync(request)); - - /// - /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response. - /// - /// RestClient instance - /// Resource URL - /// Cancellation token - /// Response object type - /// - public static Task GetAsync(this IRestClient client, string resource, CancellationToken cancellationToken = default) - => client.GetAsync(new RestRequest(resource), cancellationToken); - - [Obsolete("Use GetAsync instead")] - public static Task GetJsonAsync( - this IRestClient client, - string resource, - CancellationToken cancellationToken = default - ) - => client.GetAsync(resource, cancellationToken); - - [Obsolete("Use Get instead")] - public static TResponse? GetJson(this IRestClient client, string resource) - => AsyncHelpers.RunSync(() => client.GetAsync(resource)); - - /// - /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response. - /// - /// RestClient instance - /// Resource URL - /// Response object type - /// Deserialized response object - public static TResponse? Get(this IRestClient client, string resource) - => AsyncHelpers.RunSync(() => client.GetAsync(resource)); - - /// - /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response. - /// - /// RestClient instance - /// Resource URL - /// Parameters to pass to the request - /// Cancellation token - /// Response object type - /// Deserialized response object - public static Task GetAsync( - this IRestClient client, - string resource, - object parameters, - CancellationToken cancellationToken = default - ) { - var props = parameters.GetProperties(); - var request = new RestRequest(resource); - - foreach (var prop in props) { - Parameter parameter = resource.Contains($"{prop.Name}") - ? new UrlSegmentParameter(prop.Name, prop.Value!, prop.Encode) - : new QueryParameter(prop.Name, prop.Value, prop.Encode); - request.AddParameter(parameter); + /// + /// Execute the request using GET HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Expected result type + /// + public T? Get(RestRequest request) => AsyncHelpers.RunSync(() => client.GetAsync(request)); + + /// + /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response. + /// + /// Resource URL + /// Cancellation token + /// Response object type + /// + public Task GetAsync(string resource, CancellationToken cancellationToken = default) + => client.GetAsync(new RestRequest(resource), cancellationToken); + + [Obsolete("Use GetAsync instead")] + public Task GetJsonAsync( + string resource, + CancellationToken cancellationToken = default + ) + => client.GetAsync(resource, cancellationToken); + + [Obsolete("Use Get instead")] + public TResponse? GetJson(string resource) + => AsyncHelpers.RunSync(() => client.GetAsync(resource)); + + /// + /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response. + /// + /// Resource URL + /// Response object type + /// Deserialized response object + public TResponse? Get(string resource) + => AsyncHelpers.RunSync(() => client.GetAsync(resource)); + + /// + /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response. + /// + /// Resource URL + /// Parameters to pass to the request + /// Cancellation token + /// Response object type + /// Deserialized response object + public Task GetAsync( + string resource, + object parameters, + CancellationToken cancellationToken = default + ) { + var props = parameters.GetProperties(); + var request = new RestRequest(resource); + + foreach (var prop in props) { + Parameter parameter = resource.Contains($"{prop.Name}") + ? new UrlSegmentParameter(prop.Name, prop.Value!, prop.Encode) + : new QueryParameter(prop.Name, prop.Value, prop.Encode); + request.AddParameter(parameter); + } + + return client.GetAsync(request, cancellationToken); } - return client.GetAsync(request, cancellationToken); + [Obsolete("Use GetAsync instead")] + public Task GetJsonAsync( + string resource, + object parameters, + CancellationToken cancellationToken = default + ) + => client.GetAsync(resource, parameters, cancellationToken); + + /// + /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response. + /// + /// Resource URL + /// Parameters to pass to the request + /// Response object type + /// Deserialized response object + public TResponse? Get(string resource, object parameters) + => AsyncHelpers.RunSync(() => client.GetAsync(resource, parameters)); + + [Obsolete("Use Get instead")] + public TResponse? GetJson(string resource, object parameters) + => client.Get(resource, parameters); } - - [Obsolete("Use GetAsync instead")] - public static Task GetJsonAsync( - this IRestClient client, - string resource, - object parameters, - CancellationToken cancellationToken = default - ) - => client.GetAsync(resource, parameters, cancellationToken); - - /// - /// Calls the URL specified in the resource parameter, expecting a JSON response back. Deserializes and returns the response. - /// - /// RestClient instance - /// Resource URL - /// Parameters to pass to the request - /// Response object type - /// Deserialized response object - public static TResponse? Get(this IRestClient client, string resource, object parameters) - => AsyncHelpers.RunSync(() => client.GetAsync(resource, parameters)); - - [Obsolete("Use Get instead")] - public static TResponse? GetJson(this IRestClient client, string resource, object parameters) - => client.Get(resource, parameters); } \ No newline at end of file diff --git a/src/RestSharp/RestClient.Extensions.Head.cs b/src/RestSharp/RestClient.Extensions.Head.cs index c30402c02..ee4a9421a 100644 --- a/src/RestSharp/RestClient.Extensions.Head.cs +++ b/src/RestSharp/RestClient.Extensions.Head.cs @@ -16,91 +16,85 @@ namespace RestSharp; public static partial class RestClientExtensions { - /// - /// Executes a HEAD-style request asynchronously, authenticating if needed - /// /// - /// Request to be executed - /// Cancellation token - public static Task ExecuteHeadAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) - => client.ExecuteAsync(request, Method.Head, cancellationToken); + extension(IRestClient client) { + /// + /// Executes a HEAD-style request asynchronously, authenticating if needed + /// + /// Request to be executed + /// Cancellation token + public Task ExecuteHeadAsync(RestRequest request, CancellationToken cancellationToken = default) + => client.ExecuteAsync(request, Method.Head, cancellationToken); - /// - /// Executes a HEAD-style synchronously, authenticating if needed - /// - /// - /// Request to be executed - public static RestResponse ExecuteHead(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Head)); + /// + /// Executes a HEAD-style synchronously, authenticating if needed + /// + /// Request to be executed + public RestResponse ExecuteHead(RestRequest request) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Head)); - /// - /// Executes a HEAD-style request asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// The cancellation token - /// Deserialized response content - public static Task> ExecuteHeadAsync( - this IRestClient client, - RestRequest request, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(request, Method.Head, cancellationToken); + /// + /// Executes a HEAD-style request asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// The cancellation token + /// Deserialized response content + public Task> ExecuteHeadAsync( + RestRequest request, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(request, Method.Head, cancellationToken); - /// - /// Executes a HEAD-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// Deserialized response content - public static RestResponse ExecuteHead(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Head)); + /// + /// Executes a HEAD-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// Deserialized response content + public RestResponse ExecuteHead(RestRequest request) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Head)); - /// - /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// Expected result type - /// - public static async Task HeadAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Head, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError().Data; - } + /// + /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Cancellation token + /// Expected result type + /// + public async Task HeadAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Head, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError().Data; + } - /// - /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Expected result type - /// - public static T? Head(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.HeadAsync(request)); + /// + /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Expected result type + /// + public T? Head(RestRequest request) => AsyncHelpers.RunSync(() => client.HeadAsync(request)); - /// - /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// - public static async Task HeadAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Head, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError(); - } + /// + /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// Cancellation token + /// + public async Task HeadAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Head, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError(); + } - /// - /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// - public static RestResponse Head(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.HeadAsync(request)); + /// + /// Execute the request using HEAD HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// + public RestResponse Head(RestRequest request) => AsyncHelpers.RunSync(() => client.HeadAsync(request)); + } } diff --git a/src/RestSharp/RestClient.Extensions.Options.cs b/src/RestSharp/RestClient.Extensions.Options.cs index dccb907d9..82882394a 100644 --- a/src/RestSharp/RestClient.Extensions.Options.cs +++ b/src/RestSharp/RestClient.Extensions.Options.cs @@ -16,91 +16,85 @@ namespace RestSharp; public static partial class RestClientExtensions { - /// - /// Executes an OPTIONS-style request asynchronously, authenticating if needed - /// /// - /// Request to be executed - /// Cancellation token - public static Task ExecuteOptionsAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) - => client.ExecuteAsync(request, Method.Options, cancellationToken); + extension(IRestClient client) { + /// + /// Executes an OPTIONS-style request asynchronously, authenticating if needed + /// + /// Request to be executed + /// Cancellation token + public Task ExecuteOptionsAsync(RestRequest request, CancellationToken cancellationToken = default) + => client.ExecuteAsync(request, Method.Options, cancellationToken); - /// - /// Executes a OPTIONS-style synchronously, authenticating if needed - /// - /// - /// Request to be executed - public static RestResponse ExecuteOptions(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Options)); + /// + /// Executes a OPTIONS-style synchronously, authenticating if needed + /// + /// Request to be executed + public RestResponse ExecuteOptions(RestRequest request) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Options)); - /// - /// Executes a OPTIONS-style request asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// The cancellation token - /// Deserialized response content - public static Task> ExecuteOptionsAsync( - this IRestClient client, - RestRequest request, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(request, Method.Options, cancellationToken); + /// + /// Executes a OPTIONS-style request asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// The cancellation token + /// Deserialized response content + public Task> ExecuteOptionsAsync( + RestRequest request, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(request, Method.Options, cancellationToken); - /// - /// Executes a OPTIONS-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// Deserialized response content - public static RestResponse ExecuteOptions(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Options)); + /// + /// Executes a OPTIONS-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// Deserialized response content + public RestResponse ExecuteOptions(RestRequest request) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Options)); - /// - /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// - public static async Task OptionsAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Options, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError(); - } + /// + /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// Cancellation token + /// + public async Task OptionsAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Options, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError(); + } - /// - /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// - public static RestResponse Options(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.OptionsAsync(request)); + /// + /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// + public RestResponse Options(RestRequest request) => AsyncHelpers.RunSync(() => client.OptionsAsync(request)); - /// - /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// Expected result type - /// - public static async Task OptionsAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Options, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError().Data; - } + /// + /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Cancellation token + /// Expected result type + /// + public async Task OptionsAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Options, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError().Data; + } - /// - /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Expected result type - /// - public static T? Options(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.OptionsAsync(request)); + /// + /// Execute the request using OPTIONS HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Expected result type + /// + public T? Options(RestRequest request) => AsyncHelpers.RunSync(() => client.OptionsAsync(request)); + } } diff --git a/src/RestSharp/RestClient.Extensions.Params.cs b/src/RestSharp/RestClient.Extensions.Params.cs index a919fa8b4..cd3bb635c 100644 --- a/src/RestSharp/RestClient.Extensions.Params.cs +++ b/src/RestSharp/RestClient.Extensions.Params.cs @@ -16,83 +16,79 @@ namespace RestSharp; public static partial class RestClientExtensions { - /// - /// Add a parameter to use on every request made with this client instance - /// /// instance - /// to add - /// - public static IRestClient AddDefaultParameter(this IRestClient client, Parameter parameter) { - client.DefaultParameters.AddParameter(parameter); - return client; - } + extension(IRestClient client) { + /// + /// Add a parameter to use on every request made with this client instance + /// + /// to add + /// + public IRestClient AddDefaultParameter(Parameter parameter) { + client.DefaultParameters.AddParameter(parameter); + return client; + } - /// - /// Adds a default HTTP parameter (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) - /// Used on every request made by this client instance - /// - /// instance - /// Name of the parameter - /// Value of the parameter - /// This request - public static IRestClient AddDefaultParameter(this IRestClient client, string name, string value) - => client.AddDefaultParameter(new GetOrPostParameter(name, value)); + /// + /// Adds a default HTTP parameter (QueryString for GET, DELETE, OPTIONS and HEAD; Encoded form for POST and PUT) + /// Used on every request made by this client instance + /// + /// Name of the parameter + /// Value of the parameter + /// This request + public IRestClient AddDefaultParameter(string name, string value) + => client.AddDefaultParameter(new GetOrPostParameter(name, value)); - /// - /// Adds a default parameter to the client options. There are four types of parameters: - /// - GetOrPost: Either a QueryString value or encoded form value based on method - /// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection - /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} - /// - RequestBody: Used by AddBody() (not recommended to use directly) - /// Used on every request made by this client instance - /// - /// instance - /// Name of the parameter - /// Value of the parameter - /// The type of parameter to add - /// This request - public static IRestClient AddDefaultParameter(this IRestClient client, string name, object value, ParameterType type) - => client.AddDefaultParameter(Parameter.CreateParameter(name, value, type)); + /// + /// Adds a default parameter to the client options. There are four types of parameters: + /// - GetOrPost: Either a QueryString value or encoded form value based on method + /// - HttpHeader: Adds the name/value pair to the HTTP request's Headers collection + /// - UrlSegment: Inserted into URL if there is a matching url token e.g. {AccountId} + /// - RequestBody: Used by AddBody() (not recommended to use directly) + /// Used on every request made by this client instance + /// + /// Name of the parameter + /// Value of the parameter + /// The type of parameter to add + /// This request + public IRestClient AddDefaultParameter(string name, object value, ParameterType type) + => client.AddDefaultParameter(Parameter.CreateParameter(name, value, type)); - /// - /// Adds a default header to the RestClient. Used on every request made by this client instance. - /// - /// instance - /// Name of the header to add - /// Value of the header to add - /// - public static IRestClient AddDefaultHeader(this IRestClient client, string name, string value) - => client.AddDefaultParameter(new HeaderParameter(name, value)); + /// + /// Adds a default header to the RestClient. Used on every request made by this client instance. + /// + /// Name of the header to add + /// Value of the header to add + /// + public IRestClient AddDefaultHeader(string name, string value) + => client.AddDefaultParameter(new HeaderParameter(name, value)); - /// - /// Adds default headers to the RestClient. Used on every request made by this client instance. - /// - /// instance - /// Dictionary containing the Names and Values of the headers to add - /// - public static IRestClient AddDefaultHeaders(this IRestClient client, Dictionary headers) { - foreach (var header in headers) client.AddDefaultParameter(new HeaderParameter(header.Key, header.Value)); + /// + /// Adds default headers to the RestClient. Used on every request made by this client instance. + /// + /// Dictionary containing the Names and Values of the headers to add + /// + public IRestClient AddDefaultHeaders(Dictionary headers) { + foreach (var header in headers) client.AddDefaultParameter(new HeaderParameter(header.Key, header.Value)); - return client; - } + return client; + } - /// - /// Adds a default URL segment parameter to the RestClient. Used on every request made by this client instance. - /// - /// instance - /// Name of the segment to add - /// Value of the segment to add - /// - public static IRestClient AddDefaultUrlSegment(this IRestClient client, string name, string value) - => client.AddDefaultParameter(new UrlSegmentParameter(name, value)); + /// + /// Adds a default URL segment parameter to the RestClient. Used on every request made by this client instance. + /// + /// Name of the segment to add + /// Value of the segment to add + /// + public IRestClient AddDefaultUrlSegment(string name, string value) + => client.AddDefaultParameter(new UrlSegmentParameter(name, value)); - /// - /// Adds a default URL query parameter to the RestClient. Used on every request made by this client instance. - /// - /// instance - /// Name of the query parameter to add - /// Value of the query parameter to add - /// - public static IRestClient AddDefaultQueryParameter(this IRestClient client, string name, string value) - => client.AddDefaultParameter(new QueryParameter(name, value)); + /// + /// Adds a default URL query parameter to the RestClient. Used on every request made by this client instance. + /// + /// Name of the query parameter to add + /// Value of the query parameter to add + /// + public IRestClient AddDefaultQueryParameter(string name, string value) + => client.AddDefaultParameter(new QueryParameter(name, value)); + } } diff --git a/src/RestSharp/RestClient.Extensions.Patch.cs b/src/RestSharp/RestClient.Extensions.Patch.cs index 44547ab7f..129f5fc19 100644 --- a/src/RestSharp/RestClient.Extensions.Patch.cs +++ b/src/RestSharp/RestClient.Extensions.Patch.cs @@ -16,93 +16,85 @@ namespace RestSharp; public static partial class RestClientExtensions { - /// - /// Executes a PUT-style request asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type /// - /// Request to be executed - /// The cancellation token - /// Deserialized response content - public static Task> ExecutePatchAsync( - this IRestClient client, - RestRequest request, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(request, Method.Patch, cancellationToken); + extension(IRestClient client) { + /// + /// Executes a PUT-style request asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// The cancellation token + /// Deserialized response content + public Task> ExecutePatchAsync( + RestRequest request, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(request, Method.Patch, cancellationToken); - /// - /// Executes a PATCH-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// Deserialized response content - public static RestResponse ExecutePatch(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Patch)); + /// + /// Executes a PATCH-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// Deserialized response content + public RestResponse ExecutePatch(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Patch)); - /// - /// Executes a PATCH-style request asynchronously, authenticating if needed - /// - /// - /// Request to be executed - /// Cancellation token - public static Task ExecutePatchAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) - => client.ExecuteAsync(request, Method.Patch, cancellationToken); + /// + /// Executes a PATCH-style request asynchronously, authenticating if needed + /// + /// Request to be executed + /// Cancellation token + public Task ExecutePatchAsync(RestRequest request, CancellationToken cancellationToken = default) + => client.ExecuteAsync(request, Method.Patch, cancellationToken); - /// - /// Executes a PATCH-style synchronously, authenticating if needed - /// - /// - /// Request to be executed - public static RestResponse ExecutePatch(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Patch)); + /// + /// Executes a PATCH-style synchronously, authenticating if needed + /// + /// Request to be executed + public RestResponse ExecutePatch(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Patch)); - /// - /// Execute the request using PATCH HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// Expected result type - /// - public static async Task PatchAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Patch, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError().Data; - } + /// + /// Execute the request using PATCH HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Cancellation token + /// Expected result type + /// + public async Task PatchAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Patch, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError().Data; + } - /// - /// Execute the request using PATCH HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Expected result type - /// - [PublicAPI] - public static T? Patch(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.PatchAsync(request)); + /// + /// Execute the request using PATCH HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Expected result type + /// + [PublicAPI] + public T? Patch(RestRequest request) => AsyncHelpers.RunSync(() => client.PatchAsync(request)); - /// - /// Execute the request using PATCH HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// - public static async Task PatchAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Patch, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError(); - } + /// + /// Execute the request using PATCH HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// Cancellation token + /// + public async Task PatchAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Patch, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError(); + } - /// - /// Execute the request using PATCH HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// - [PublicAPI] - public static RestResponse Patch(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.PatchAsync(request)); -} + /// + /// Execute the request using PATCH HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// + [PublicAPI] + public RestResponse Patch(RestRequest request) => AsyncHelpers.RunSync(() => client.PatchAsync(request)); + } +} \ No newline at end of file diff --git a/src/RestSharp/RestClient.Extensions.Post.cs b/src/RestSharp/RestClient.Extensions.Post.cs index ff1171c6e..b6eb436f0 100644 --- a/src/RestSharp/RestClient.Extensions.Post.cs +++ b/src/RestSharp/RestClient.Extensions.Post.cs @@ -16,158 +16,144 @@ namespace RestSharp; public static partial class RestClientExtensions { - /// - /// Executes a POST-style request asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type /// - /// Request to be executed - /// The cancellation token - /// Deserialized response content - public static Task> ExecutePostAsync( - this IRestClient client, - RestRequest request, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(request, Method.Post, cancellationToken); + extension(IRestClient client) { + /// + /// Executes a POST-style request asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// The cancellation token + /// Deserialized response content + public Task> ExecutePostAsync( + RestRequest request, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(request, Method.Post, cancellationToken); - /// - /// Executes a POST-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// Deserialized response content - public static RestResponse ExecutePost(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Post)); + /// + /// Executes a POST-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// Deserialized response content + public RestResponse ExecutePost(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Post)); - /// - /// Executes a POST-style asynchronously, authenticating if needed - /// - /// - /// Request to be executed - /// Cancellation token - public static Task ExecutePostAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) - => client.ExecuteAsync(request, Method.Post, cancellationToken); + /// + /// Executes a POST-style asynchronously, authenticating if needed + /// + /// Request to be executed + /// Cancellation token + public Task ExecutePostAsync(RestRequest request, CancellationToken cancellationToken = default) + => client.ExecuteAsync(request, Method.Post, cancellationToken); - /// - /// Executes a POST-style synchronously, authenticating if needed - /// - /// - /// Request to be executed - public static RestResponse ExecutePost(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Post)); + /// + /// Executes a POST-style synchronously, authenticating if needed + /// + /// Request to be executed + public RestResponse ExecutePost(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Post)); - /// - /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// Expected result type - /// - public static async Task PostAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecutePostAsync(request, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError().Data; - } + /// + /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Cancellation token + /// Expected result type + /// + public async Task PostAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecutePostAsync(request, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError().Data; + } - /// - /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Expected result type - /// - public static T? Post(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.PostAsync(request)); + /// + /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Expected result type + /// + public T? Post(RestRequest request) => AsyncHelpers.RunSync(() => client.PostAsync(request)); - /// - /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// - public static async Task PostAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecutePostAsync(request, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError(); - } + /// + /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// Cancellation token + /// + public async Task PostAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecutePostAsync(request, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError(); + } - /// - /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// - public static RestResponse Post(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.PostAsync(request)); + /// + /// Execute the request using POST HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// + public RestResponse Post(RestRequest request) => AsyncHelpers.RunSync(() => client.PostAsync(request)); - /// - /// Serializes the request object to JSON and makes a POST call to the resource specified in the resource parameter. - /// Expects a JSON response back, deserializes it to TResponse type and returns it. - /// - /// RestClient instance - /// Resource URL - /// Request object, must be serializable to JSON - /// Cancellation token - /// Request object type - /// Response object type - /// Deserialized response object - public static Task PostJsonAsync( - this IRestClient client, - string resource, - TRequest request, - CancellationToken cancellationToken = default - ) where TRequest : class { - var restRequest = new RestRequest(resource).AddJsonBody(request); - return client.PostAsync(restRequest, cancellationToken); - } + /// + /// Serializes the request object to JSON and makes a POST call to the resource specified in the resource parameter. + /// Expects a JSON response back, deserializes it to TResponse type and returns it. + /// + /// Resource URL + /// Request object, must be serializable to JSON + /// Cancellation token + /// Request object type + /// Response object type + /// Deserialized response object + public Task PostJsonAsync( + string resource, + TRequest request, + CancellationToken cancellationToken = default + ) where TRequest : class { + var restRequest = new RestRequest(resource).AddJsonBody(request); + return client.PostAsync(restRequest, cancellationToken); + } - /// - /// Serializes the request object to JSON and makes a POST call to the resource specified in the resource parameter. - /// Expects a JSON response back, deserializes it to TResponse type and returns it. - /// - /// RestClient instance - /// Resource URL - /// Request object, must be serializable to JSON - /// Request object type - /// Response object type - /// Deserialized response object - public static TResponse? PostJson(this IRestClient client, string resource, TRequest request) where TRequest : class - => AsyncHelpers.RunSync(() => client.PostJsonAsync(resource, request)); + /// + /// Serializes the request object to JSON and makes a POST call to the resource specified in the resource parameter. + /// Expects a JSON response back, deserializes it to TResponse type and returns it. + /// + /// Resource URL + /// Request object, must be serializable to JSON + /// Request object type + /// Response object type + /// Deserialized response object + public TResponse? PostJson(string resource, TRequest request) where TRequest : class + => AsyncHelpers.RunSync(() => client.PostJsonAsync(resource, request)); - /// - /// Serializes the request object to JSON and makes a POST call to the resource specified in the resource parameter. - /// Expects no response back, just the status code. - /// - /// RestClient instance - /// Resource URL - /// Request object, must be serializable to JSON - /// Cancellation token - /// Request object type - /// Response status code - public static async Task PostJsonAsync( - this IRestClient client, - string resource, - TRequest request, - CancellationToken cancellationToken = default - ) where TRequest : class { - var restRequest = new RestRequest(resource).AddJsonBody(request); - var response = await client.PostAsync(restRequest, cancellationToken).ConfigureAwait(false); - return response.StatusCode; - } + /// + /// Serializes the request object to JSON and makes a POST call to the resource specified in the resource parameter. + /// Expects no response back, just the status code. + /// + /// Resource URL + /// Request object, must be serializable to JSON + /// Cancellation token + /// Request object type + /// Response status code + public async Task PostJsonAsync( + string resource, + TRequest request, + CancellationToken cancellationToken = default + ) where TRequest : class { + var restRequest = new RestRequest(resource).AddJsonBody(request); + var response = await client.PostAsync(restRequest, cancellationToken).ConfigureAwait(false); + return response.StatusCode; + } - /// - /// Serializes the request object to JSON and makes a POST call to the resource specified in the resource parameter. - /// Expects no response back, just the status code. - /// - /// RestClient instance - /// Resource URL - /// Request object, must be serializable to JSON - /// Request object type - /// Response status code - public static HttpStatusCode PostJson(this IRestClient client, string resource, TRequest request) where TRequest : class - => AsyncHelpers.RunSync(() => client.PostJsonAsync(resource, request)); -} + /// + /// Serializes the request object to JSON and makes a POST call to the resource specified in the resource parameter. + /// Expects no response back, just the status code. + /// + /// Resource URL + /// Request object, must be serializable to JSON + /// Request object type + /// Response status code + public HttpStatusCode PostJson(string resource, TRequest request) where TRequest : class + => AsyncHelpers.RunSync(() => client.PostJsonAsync(resource, request)); + } +} \ No newline at end of file diff --git a/src/RestSharp/RestClient.Extensions.Put.cs b/src/RestSharp/RestClient.Extensions.Put.cs index e34115c1c..e404e4e34 100644 --- a/src/RestSharp/RestClient.Extensions.Put.cs +++ b/src/RestSharp/RestClient.Extensions.Put.cs @@ -16,158 +16,144 @@ namespace RestSharp; public static partial class RestClientExtensions { - /// - /// Executes a PUT-style request asynchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type /// - /// Request to be executed - /// The cancellation token - /// Deserialized response content - public static Task> ExecutePutAsync( - this IRestClient client, - RestRequest request, - CancellationToken cancellationToken = default - ) - => client.ExecuteAsync(request, Method.Put, cancellationToken); + extension(IRestClient client) { + /// + /// Executes a PUT-style request asynchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// The cancellation token + /// Deserialized response content + public Task> ExecutePutAsync( + RestRequest request, + CancellationToken cancellationToken = default + ) + => client.ExecuteAsync(request, Method.Put, cancellationToken); - /// - /// Executes a PUT-style request synchronously, authenticating if needed. - /// The response content then gets deserialized to T. - /// - /// Target deserialization type - /// - /// Request to be executed - /// Deserialized response content - public static RestResponse ExecutePut(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Put)); + /// + /// Executes a PUT-style request synchronously, authenticating if needed. + /// The response content then gets deserialized to T. + /// + /// Target deserialization type + /// Request to be executed + /// Deserialized response content + public RestResponse ExecutePut(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Put)); - /// - /// Executes a PUP-style request asynchronously, authenticating if needed - /// - /// - /// Request to be executed - /// Cancellation token - public static Task ExecutePutAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) - => client.ExecuteAsync(request, Method.Put, cancellationToken); + /// + /// Executes a PUP-style request asynchronously, authenticating if needed + /// + /// Request to be executed + /// Cancellation token + public Task ExecutePutAsync(RestRequest request, CancellationToken cancellationToken = default) + => client.ExecuteAsync(request, Method.Put, cancellationToken); - /// - /// Executes a PUT-style synchronously, authenticating if needed - /// - /// - /// Request to be executed - public static RestResponse ExecutePut(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Put)); + /// + /// Executes a PUT-style synchronously, authenticating if needed + /// + /// Request to be executed + public RestResponse ExecutePut(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, Method.Put)); - /// - /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// Expected result type - /// Deserialaized response - public static async Task PutAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Put, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError().Data; - } + /// + /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Cancellation token + /// Expected result type + /// Deserialaized response + public async Task PutAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Put, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError().Data; + } - /// - /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. - /// The response data is deserialized to the Data property of the returned response object. - /// - /// RestClient instance - /// The request - /// Expected result type - /// - public static T? Put(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.PutAsync(request)); + /// + /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. + /// The response data is deserialized to the Data property of the returned response object. + /// + /// The request + /// Expected result type + /// + public T? Put(RestRequest request) => AsyncHelpers.RunSync(() => client.PutAsync(request)); - /// - /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// Cancellation token - /// - public static async Task PutAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { - var response = await client.ExecuteAsync(request, Method.Put, cancellationToken).ConfigureAwait(false); - return response.ThrowIfError(); - } + /// + /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// Cancellation token + /// + public async Task PutAsync(RestRequest request, CancellationToken cancellationToken = default) { + var response = await client.ExecuteAsync(request, Method.Put, cancellationToken).ConfigureAwait(false); + return response.ThrowIfError(); + } - /// - /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. - /// - /// RestClient instance - /// The request - /// - public static RestResponse Put(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.PutAsync(request)); + /// + /// Execute the request using PUT HTTP method. Exception will be thrown if the request does not succeed. + /// + /// The request + /// + public RestResponse Put(RestRequest request) => AsyncHelpers.RunSync(() => client.PutAsync(request)); - /// - /// Serializes the request object to JSON and makes a PUT call to the resource specified in the resource parameter. - /// Expects a JSON response back, deserializes it to TResponse type and returns it. - /// - /// RestClient instance - /// Resource URL - /// Request object, must be serializable to JSON - /// Cancellation token - /// Request object type - /// Response object type - /// Deserialized response object - public static Task PutJsonAsync( - this IRestClient client, - string resource, - TRequest request, - CancellationToken cancellationToken = default - ) where TRequest : class { - var restRequest = new RestRequest(resource).AddJsonBody(request); - return client.PutAsync(restRequest, cancellationToken); - } + /// + /// Serializes the request object to JSON and makes a PUT call to the resource specified in the resource parameter. + /// Expects a JSON response back, deserializes it to TResponse type and returns it. + /// + /// Resource URL + /// Request object, must be serializable to JSON + /// Cancellation token + /// Request object type + /// Response object type + /// Deserialized response object + public Task PutJsonAsync( + string resource, + TRequest request, + CancellationToken cancellationToken = default + ) where TRequest : class { + var restRequest = new RestRequest(resource).AddJsonBody(request); + return client.PutAsync(restRequest, cancellationToken); + } - /// - /// Serializes the request object to JSON and makes a PUT call to the resource specified in the resource parameter. - /// Expects a JSON response back, deserializes it to TResponse type and returns it. - /// - /// RestClient instance - /// Resource URL - /// Request object, must be serializable to JSON - /// Request object type - /// Response object type - /// Deserialized response object - public static TResponse? PutJson(this IRestClient client, string resource, TRequest request) where TRequest : class - => AsyncHelpers.RunSync(() => client.PutJsonAsync(resource, request)); + /// + /// Serializes the request object to JSON and makes a PUT call to the resource specified in the resource parameter. + /// Expects a JSON response back, deserializes it to TResponse type and returns it. + /// + /// Resource URL + /// Request object, must be serializable to JSON + /// Request object type + /// Response object type + /// Deserialized response object + public TResponse? PutJson(string resource, TRequest request) where TRequest : class + => AsyncHelpers.RunSync(() => client.PutJsonAsync(resource, request)); - /// - /// Serializes the request object to JSON and makes a PUT call to the resource specified in the resource parameter. - /// Expects no response back, just the status code. - /// - /// RestClient instance - /// Resource URL - /// Request object, must be serializable to JSON - /// Cancellation token - /// Request object type - /// Response status code - public static async Task PutJsonAsync( - this IRestClient client, - string resource, - TRequest request, - CancellationToken cancellationToken = default - ) where TRequest : class { - var restRequest = new RestRequest(resource).AddJsonBody(request); - var response = await client.PutAsync(restRequest, cancellationToken).ConfigureAwait(false); - return response.StatusCode; - } + /// + /// Serializes the request object to JSON and makes a PUT call to the resource specified in the resource parameter. + /// Expects no response back, just the status code. + /// + /// Resource URL + /// Request object, must be serializable to JSON + /// Cancellation token + /// Request object type + /// Response status code + public async Task PutJsonAsync( + string resource, + TRequest request, + CancellationToken cancellationToken = default + ) where TRequest : class { + var restRequest = new RestRequest(resource).AddJsonBody(request); + var response = await client.PutAsync(restRequest, cancellationToken).ConfigureAwait(false); + return response.StatusCode; + } - /// - /// Serializes the request object to JSON and makes a PUT call to the resource specified in the resource parameter. - /// Expects no response back, just the status code. - /// - /// RestClient instance - /// Resource URL - /// Request object, must be serializable to JSON - /// Request object type - /// Response status code - public static HttpStatusCode PutJson(this IRestClient client, string resource, TRequest request) where TRequest : class - => AsyncHelpers.RunSync(() => client.PutJsonAsync(resource, request)); -} + /// + /// Serializes the request object to JSON and makes a PUT call to the resource specified in the resource parameter. + /// Expects no response back, just the status code. + /// + /// Resource URL + /// Request object, must be serializable to JSON + /// Request object type + /// Response status code + public HttpStatusCode PutJson(string resource, TRequest request) where TRequest : class + => AsyncHelpers.RunSync(() => client.PutJsonAsync(resource, request)); + } +} \ No newline at end of file diff --git a/src/RestSharp/RestClient.Extensions.cs b/src/RestSharp/RestClient.Extensions.cs index 27997aa01..4af3fe1c7 100644 --- a/src/RestSharp/RestClient.Extensions.cs +++ b/src/RestSharp/RestClient.Extensions.cs @@ -19,182 +19,169 @@ namespace RestSharp; [PublicAPI] public static partial class RestClientExtensions { - [PublicAPI] - [Obsolete("Please use the async overload with a cancellation token")] - public static RestResponse Deserialize(this IRestClient client, RestResponse response) - => AsyncHelpers.RunSync(() => client.Serializers.Deserialize(response.Request, response, client.Options, CancellationToken.None).AsTask()); - - [PublicAPI] - public static ValueTask> Deserialize(this IRestClient client, RestResponse response, CancellationToken cancellationToken) - => client.Serializers.Deserialize(response.Request, response, client.Options, cancellationToken); - - /// - /// Executes the request asynchronously, authenticating if needed - /// - /// Target deserialization type /// - /// Request to be executed - /// Cancellation token - public static async Task> ExecuteAsync( - this IRestClient client, - RestRequest request, - CancellationToken cancellationToken = default - ) { - Ensure.NotNull(request, nameof(request)); - - var response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); - return await client.Serializers.Deserialize(request, response, client.Options, cancellationToken); - } - - /// - /// Executes the request synchronously, authenticating if needed - /// - /// Target deserialization type - /// - /// Request to be executed - public static RestResponse Execute(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request)); - - /// - /// Executes the request synchronously, authenticating if needed - /// - /// - /// Request to be executed - public static RestResponse Execute(this IRestClient client, RestRequest request) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request)); + extension(IRestClient client) { + [PublicAPI] + [Obsolete("Please use the async overload with a cancellation token")] + public RestResponse Deserialize(RestResponse response) + => AsyncHelpers.RunSync(() + => client.Serializers.Deserialize(response.Request, response, client.Options, CancellationToken.None).AsTask() + ); + + [PublicAPI] + public ValueTask> Deserialize(RestResponse response, CancellationToken cancellationToken) + => client.Serializers.Deserialize(response.Request, response, client.Options, cancellationToken); + + /// + /// Executes the request asynchronously, authenticating if needed + /// + /// Target deserialization type + /// Request to be executed + /// Cancellation token + public async Task> ExecuteAsync( + RestRequest request, + CancellationToken cancellationToken = default + ) { + Ensure.NotNull(request, nameof(request)); + + var response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + return await client.Serializers.Deserialize(request, response, client.Options, cancellationToken); + } - /// - /// Executes the request asynchronously, authenticating if needed - /// - /// - /// Request to be executed - /// Override the request method - /// Cancellation token - public static Task ExecuteAsync( - this IRestClient client, - RestRequest request, - Method httpMethod, - CancellationToken cancellationToken = default - ) { - Ensure.NotNull(request, nameof(request)); - - request.Method = httpMethod; - return client.ExecuteAsync(request, cancellationToken); - } + /// + /// Executes the request synchronously, authenticating if needed + /// + /// Target deserialization type + /// Request to be executed + public RestResponse Execute(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request)); + + /// + /// Executes the request synchronously, authenticating if needed + /// + /// Request to be executed + public RestResponse Execute(RestRequest request) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request)); + + /// + /// Executes the request asynchronously, authenticating if needed + /// + /// Request to be executed + /// Override the request method + /// Cancellation token + public Task ExecuteAsync( + RestRequest request, + Method httpMethod, + CancellationToken cancellationToken = default + ) { + Ensure.NotNull(request, nameof(request)); + + request.Method = httpMethod; + return client.ExecuteAsync(request, cancellationToken); + } - /// - /// Executes the request synchronously, authenticating if needed - /// - /// - /// Request to be executed - /// Override the request method - public static RestResponse Execute(this IRestClient client, RestRequest request, Method httpMethod) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, httpMethod)); - - /// - /// Executes the request asynchronously, authenticating if needed - /// - /// Target deserialization type - /// - /// Request to be executed - /// Override the request method - /// Cancellation token - public static Task> ExecuteAsync( - this IRestClient client, - RestRequest request, - Method httpMethod, - CancellationToken cancellationToken = default - ) { - Ensure.NotNull(request, nameof(request)); - - request.Method = httpMethod; - return client.ExecuteAsync(request, cancellationToken); - } + /// + /// Executes the request synchronously, authenticating if needed + /// + /// Request to be executed + /// Override the request method + public RestResponse Execute(RestRequest request, Method httpMethod) => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, httpMethod)); + + /// + /// Executes the request asynchronously, authenticating if needed + /// + /// Target deserialization type + /// Request to be executed + /// Override the request method + /// Cancellation token + public Task> ExecuteAsync( + RestRequest request, + Method httpMethod, + CancellationToken cancellationToken = default + ) { + Ensure.NotNull(request, nameof(request)); + + request.Method = httpMethod; + return client.ExecuteAsync(request, cancellationToken); + } - /// - /// Executes the request synchronously, authenticating if needed - /// - /// Target deserialization type - /// - /// Request to be executed - /// Override the request method - public static RestResponse Execute(this IRestClient client, RestRequest request, Method httpMethod) - => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, httpMethod)); - - /// - /// A specialized method to download files. - /// - /// RestClient instance - /// Pre-configured request instance. - /// - /// The downloaded file. - [PublicAPI] - public static async Task DownloadDataAsync(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) { + /// + /// Executes the request synchronously, authenticating if needed + /// + /// Target deserialization type + /// Request to be executed + /// Override the request method + public RestResponse Execute(RestRequest request, Method httpMethod) + => AsyncHelpers.RunSync(() => client.ExecuteAsync(request, httpMethod)); + + /// + /// A specialized method to download files. + /// + /// Pre-configured request instance. + /// + /// The downloaded file. + [PublicAPI] + public async Task DownloadDataAsync(RestRequest request, CancellationToken cancellationToken = default) { #if NET - await using var stream = await client.DownloadStreamAsync(request, cancellationToken).ConfigureAwait(false); + await using var stream = await client.DownloadStreamAsync(request, cancellationToken).ConfigureAwait(false); #else - using var stream = await client.DownloadStreamAsync(request, cancellationToken).ConfigureAwait(false); + using var stream = await client.DownloadStreamAsync(request, cancellationToken).ConfigureAwait(false); #endif - return stream == null ? null : await stream.ReadAsBytes(cancellationToken).ConfigureAwait(false); - } + return stream == null ? null : await stream.ReadAsBytes(cancellationToken).ConfigureAwait(false); + } - /// - /// A specialized method to download files as streams. - /// - /// - /// Pre-configured request instance. - /// The cancellation token - /// The downloaded stream. - [PublicAPI] - public static Stream? DownloadStream(this IRestClient client, RestRequest request, CancellationToken cancellationToken = default) - => AsyncHelpers.RunSync(() => client.DownloadStreamAsync(request, cancellationToken)); - - /// - /// A specialized method to download files. - /// - /// RestClient instance - /// Pre-configured request instance. - /// The downloaded file. - public static byte[]? DownloadData(this IRestClient client, RestRequest request) => AsyncHelpers.RunSync(() => client.DownloadDataAsync(request)); - - /// - /// Reads a stream returned by the specified endpoint, deserializes each line to JSON and returns each object asynchronously. - /// It is required for each JSON object to be returned in a single line. - /// - /// - /// - /// - /// - /// - [PublicAPI] - public static async IAsyncEnumerable StreamJsonAsync( - this IRestClient client, - string resource, - [EnumeratorCancellation] CancellationToken cancellationToken - ) { - var request = new RestRequest(resource); + /// + /// A specialized method to download files as streams. + /// + /// Pre-configured request instance. + /// The cancellation token + /// The downloaded stream. + [PublicAPI] + public Stream? DownloadStream(RestRequest request, CancellationToken cancellationToken = default) + => AsyncHelpers.RunSync(() => client.DownloadStreamAsync(request, cancellationToken)); + + /// + /// A specialized method to download files. + /// + /// Pre-configured request instance. + /// The downloaded file. + public byte[]? DownloadData(RestRequest request) => AsyncHelpers.RunSync(() => client.DownloadDataAsync(request)); + + /// + /// Reads a stream returned by the specified endpoint, deserializes each line to JSON and returns each object asynchronously. + /// It is required for each JSON object to be returned in a single line. + /// + /// + /// + /// + /// + [PublicAPI] + public async IAsyncEnumerable StreamJsonAsync( + string resource, + [EnumeratorCancellation] CancellationToken cancellationToken + ) { + var request = new RestRequest(resource); #if NET await using var stream = await client.DownloadStreamAsync(request, cancellationToken).ConfigureAwait(false); #else - using var stream = await client.DownloadStreamAsync(request, cancellationToken).ConfigureAwait(false); + using var stream = await client.DownloadStreamAsync(request, cancellationToken).ConfigureAwait(false); #endif - if (stream == null) yield break; + if (stream == null) yield break; - var serializer = client.Serializers.GetSerializer(DataFormat.Json); + var serializer = client.Serializers.GetSerializer(DataFormat.Json); - using var reader = new StreamReader(stream); + using var reader = new StreamReader(stream); - while (!reader.EndOfStream && !cancellationToken.IsCancellationRequested) { + while (!reader.EndOfStream && !cancellationToken.IsCancellationRequested) { #if NET7_0_OR_GREATER var line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false); #else - var line = await reader.ReadLineAsync().ConfigureAwait(false); + var line = await reader.ReadLineAsync().ConfigureAwait(false); #endif - if (string.IsNullOrWhiteSpace(line)) continue; + if (string.IsNullOrWhiteSpace(line)) continue; - var response = new RestResponse(request) { Content = line }; - yield return serializer.Deserializer.Deserialize(response)!; + var response = new RestResponse(request) { Content = line }; + yield return serializer.Deserializer.Deserialize(response)!; + } } } -} +} \ No newline at end of file diff --git a/src/RestSharp/RestSharp.csproj b/src/RestSharp/RestSharp.csproj index 5643d4c02..3b9db4980 100644 --- a/src/RestSharp/RestSharp.csproj +++ b/src/RestSharp/RestSharp.csproj @@ -58,6 +58,12 @@ RestRequestExtensions.cs + + RestRequestExtensions.cs + + + RestRequestExtensions.cs + diff --git a/src/RestSharp/Serializers/Json/RestClientExtensions.cs b/src/RestSharp/Serializers/Json/RestClientExtensions.cs index ec0fa24b9..121f5b635 100644 --- a/src/RestSharp/Serializers/Json/RestClientExtensions.cs +++ b/src/RestSharp/Serializers/Json/RestClientExtensions.cs @@ -18,20 +18,21 @@ namespace RestSharp.Serializers.Json; [PublicAPI] public static class RestClientExtensions { - /// - /// Use System.Text.Json serializer with default settings - /// /// - /// - public static SerializerConfig UseSystemTextJson(this SerializerConfig serializerConfig) - => serializerConfig.UseSerializer(() => new SystemTextJsonSerializer()); + extension(SerializerConfig serializerConfig) { + /// + /// Use System.Text.Json serializer with default settings + /// + /// + public SerializerConfig UseSystemTextJson() + => serializerConfig.UseSerializer(() => new SystemTextJsonSerializer()); - /// - /// Use System.Text.Json serializer with custom settings - /// - /// - /// System.Text.Json serializer options - /// - public static SerializerConfig UseSystemTextJson(this SerializerConfig serializerConfig, JsonSerializerOptions options) - => serializerConfig.UseSerializer(() => new SystemTextJsonSerializer(options)); + /// + /// Use System.Text.Json serializer with custom settings + /// + /// System.Text.Json serializer options + /// + public SerializerConfig UseSystemTextJson(JsonSerializerOptions options) + => serializerConfig.UseSerializer(() => new SystemTextJsonSerializer(options)); + } } diff --git a/src/RestSharp/Serializers/Json/SystemTextJsonSerializer.cs b/src/RestSharp/Serializers/Json/SystemTextJsonSerializer.cs index 869167163..959ffe9e5 100644 --- a/src/RestSharp/Serializers/Json/SystemTextJsonSerializer.cs +++ b/src/RestSharp/Serializers/Json/SystemTextJsonSerializer.cs @@ -22,7 +22,7 @@ public class SystemTextJsonSerializer : IRestSerializer, ISerializer, IDeseriali /// /// Create the new serializer that uses System.Text.Json.JsonSerializer with default settings /// - public SystemTextJsonSerializer() => _options = new JsonSerializerOptions(JsonSerializerDefaults.Web); + public SystemTextJsonSerializer() => _options = new(JsonSerializerDefaults.Web); /// /// Create the new serializer that uses System.Text.Json.JsonSerializer with custom settings diff --git a/src/RestSharp/Serializers/SerializerConfig.cs b/src/RestSharp/Serializers/SerializerConfig.cs index 78d1f6921..27055cf12 100644 --- a/src/RestSharp/Serializers/SerializerConfig.cs +++ b/src/RestSharp/Serializers/SerializerConfig.cs @@ -28,7 +28,7 @@ public class SerializerConfig { public SerializerConfig UseSerializer(Func serializerFactory) { var instance = serializerFactory(); - Serializers[instance.DataFormat] = new SerializerRecord( + Serializers[instance.DataFormat] = new( instance.DataFormat, instance.AcceptedContentTypes, instance.SupportsContentType, @@ -48,35 +48,35 @@ public SerializerConfig UseSerializer(Func serializerFactory) { } public static class SerializerConfigExtensions { - /// - /// Sets the to only use JSON - /// /// Configuration instance to work with - /// Reference to the client instance - public static SerializerConfig UseJson(this SerializerConfig config) { - config.Serializers.Remove(DataFormat.Xml); - return config; - } + extension(SerializerConfig config) { + /// + /// Sets the to only use JSON + /// + /// Reference to the client instance + public SerializerConfig UseJson() { + config.Serializers.Remove(DataFormat.Xml); + return config; + } - /// - /// Sets the to only use XML - /// - /// Configuration instance to work with - /// Reference to the client instance - public static SerializerConfig UseXml(this SerializerConfig config) { - config.Serializers.Remove(DataFormat.Json); - return config; - } + /// + /// Sets the to only use XML + /// + /// Reference to the client instance + public SerializerConfig UseXml() { + config.Serializers.Remove(DataFormat.Json); + return config; + } - /// - /// Sets the to only use the passed in custom serializer - /// - /// Configuration instance to work with - /// Function that returns the serializer instance - /// Reference to the client instance - public static SerializerConfig UseOnlySerializer(this SerializerConfig config, Func serializerFactory) { - config.Serializers.Clear(); - config.UseSerializer(serializerFactory); - return config; + /// + /// Sets the to only use the passed in custom serializer + /// + /// Function that returns the serializer instance + /// Reference to the client instance + public SerializerConfig UseOnlySerializer(Func serializerFactory) { + config.Serializers.Clear(); + config.UseSerializer(serializerFactory); + return config; + } } } diff --git a/src/RestSharp/Serializers/Xml/DotNetXmlSerializer.cs b/src/RestSharp/Serializers/Xml/DotNetXmlSerializer.cs index 6fb69c3f2..ef7f2f091 100644 --- a/src/RestSharp/Serializers/Xml/DotNetXmlSerializer.cs +++ b/src/RestSharp/Serializers/Xml/DotNetXmlSerializer.cs @@ -105,7 +105,7 @@ static XmlSerializer GetXmlSerializer(Type type, string? rootElement) { // and the last check, some other thread could have added an instance if (!Cache.TryGetValue(key, out var value)) { var root = rootElement == null ? null : new XmlRootAttribute(rootElement); - value = new XmlSerializer(type, root); + value = new(type, root); Cache[key] = value; } @@ -118,10 +118,9 @@ static XmlSerializer GetXmlSerializer(Type type, string? rootElement) { return serializer; } - class EncodingStringWriter : StringWriter { + class EncodingStringWriter(Encoding encoding) : StringWriter { // Need to subclass StringWriter in order to override Encoding - public EncodingStringWriter(Encoding encoding) => Encoding = encoding; - public override Encoding Encoding { get; } + public override Encoding Encoding { get; } = encoding; } -} +} \ No newline at end of file diff --git a/src/RestSharp/Serializers/Xml/XmlRestSerializer.cs b/src/RestSharp/Serializers/Xml/XmlRestSerializer.cs index c3409ca1d..db857095f 100644 --- a/src/RestSharp/Serializers/Xml/XmlRestSerializer.cs +++ b/src/RestSharp/Serializers/Xml/XmlRestSerializer.cs @@ -15,10 +15,13 @@ namespace RestSharp.Serializers.Xml; public class XmlRestSerializer(IXmlSerializer serializer, IXmlDeserializer deserializer) : IRestSerializer { + IXmlDeserializer _deserializer = deserializer; + IXmlSerializer _serializer = serializer; + public XmlRestSerializer() : this(new DotNetXmlSerializer(), new DotNetXmlDeserializer()) { } - public ISerializer Serializer => serializer; - public IDeserializer Deserializer => deserializer; + public ISerializer Serializer => _serializer; + public IDeserializer Deserializer => _deserializer; public string[] AcceptedContentTypes => ContentType.XmlAccept; public SupportsContentType SupportsContentType => contentType => contentType.Value.EndsWith("xml", StringComparison.InvariantCultureIgnoreCase); @@ -31,23 +34,23 @@ public class XmlRestSerializer(IXmlSerializer serializer, IXmlDeserializer deser if (parameter.Value == null) throw new ArgumentNullException(nameof(parameter), "Parameter value is null"); - var savedNamespace = serializer.Namespace; - serializer.Namespace = xmlParameter.XmlNamespace ?? savedNamespace; + var savedNamespace = _serializer.Namespace; + _serializer.Namespace = xmlParameter.XmlNamespace ?? savedNamespace; - var result = serializer.Serialize(parameter.Value); + var result = _serializer.Serialize(parameter.Value); - serializer.Namespace = savedNamespace; + _serializer.Namespace = savedNamespace; return result; } public XmlRestSerializer WithXmlSerializer(IXmlSerializer xmlSerializer) { - serializer = xmlSerializer; + _serializer = xmlSerializer; return this; } public XmlRestSerializer WithXmlDeserializer(IXmlDeserializer xmlDeserializer) { - deserializer = xmlDeserializer; + _deserializer = xmlDeserializer; return this; } } \ No newline at end of file diff --git a/test/RestSharp.InteractiveTests/AuthenticationTests.cs b/test/RestSharp.InteractiveTests/AuthenticationTests.cs index 4930d6ca0..7e5d81173 100644 --- a/test/RestSharp.InteractiveTests/AuthenticationTests.cs +++ b/test/RestSharp.InteractiveTests/AuthenticationTests.cs @@ -37,7 +37,7 @@ public static async Task Can_Authenticate_With_OAuth_Async_With_Callback(Twitter Assert.NotNull(oauthToken); Assert.NotNull(oauthTokenSecret); - request = new RestRequest("oauth/authorize?oauth_token=" + oauthToken); + request = new($"oauth/authorize?oauth_token={oauthToken}"); var url = client.BuildUri(request) .ToString(); @@ -46,7 +46,7 @@ public static async Task Can_Authenticate_With_OAuth_Async_With_Callback(Twitter Console.Write("Enter the verifier: "); var verifier = Console.ReadLine(); - request = new RestRequest("oauth/access_token") { + request = new("oauth/access_token") { Authenticator = OAuth1Authenticator.ForAccessToken( twitterKeys.ConsumerKey!, twitterKeys.ConsumerSecret, @@ -68,7 +68,7 @@ public static async Task Can_Authenticate_With_OAuth_Async_With_Callback(Twitter Assert.NotNull(oauthToken); Assert.NotNull(oauthTokenSecret); - request = new RestRequest("1.1/account/verify_credentials.json") { + request = new("1.1/account/verify_credentials.json") { Authenticator = OAuth1Authenticator.ForProtectedResource( twitterKeys.ConsumerKey!, twitterKeys.ConsumerSecret, diff --git a/test/RestSharp.InteractiveTests/TwitterClient.cs b/test/RestSharp.InteractiveTests/TwitterClient.cs index 72785683a..0df6d0555 100644 --- a/test/RestSharp.InteractiveTests/TwitterClient.cs +++ b/test/RestSharp.InteractiveTests/TwitterClient.cs @@ -31,7 +31,7 @@ public TwitterClient(string apiKey, string apiKeySecret) { var options = new RestClientOptions("https://api.twitter.com/2") { Authenticator = new TwitterAuthenticator("https://api.twitter.com", apiKey, apiKeySecret) }; - _client = new RestClient(options); + _client = new(options); } public async Task GetUser(string user) { @@ -45,7 +45,7 @@ public async Task GetUser(string user) { public async Task AddSearchRules(params AddStreamSearchRule[] rules) { var response = await _client.PostJsonAsync>( "tweets/search/stream/rules", - new AddSearchRulesRequest(rules) + new(rules) ); return response?.Data; } @@ -75,17 +75,7 @@ public void Dispose() { } } -class TwitterAuthenticator : AuthenticatorBase { - readonly string _baseUrl; - readonly string _clientId; - readonly string _clientSecret; - - public TwitterAuthenticator(string baseUrl, string clientId, string clientSecret) : base("") { - _baseUrl = baseUrl; - _clientId = clientId; - _clientSecret = clientSecret; - } - +class TwitterAuthenticator(string baseUrl, string clientId, string clientSecret) : AuthenticatorBase("") { protected override async ValueTask GetAuthenticationParameter(string accessToken) { var token = string.IsNullOrEmpty(Token) ? await GetToken() : Token; Token = token; @@ -93,8 +83,8 @@ protected override async ValueTask GetAuthenticationParameter(string } async Task GetToken() { - var options = new RestClientOptions(_baseUrl) { - Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret) + var options = new RestClientOptions(baseUrl) { + Authenticator = new HttpBasicAuthenticator(clientId, clientSecret) }; using var client = new RestClient(options); diff --git a/test/RestSharp.Tests.Serializers.Csv/CsvHelperTests.cs b/test/RestSharp.Tests.Serializers.Csv/CsvHelperTests.cs index a7659fe75..bb3ac3df7 100644 --- a/test/RestSharp.Tests.Serializers.Csv/CsvHelperTests.cs +++ b/test/RestSharp.Tests.Serializers.Csv/CsvHelperTests.cs @@ -1,4 +1,3 @@ -using CsvHelper.Configuration; using RestSharp.Serializers.CsvHelper; using RestSharp.Serializers.Json; using System.Globalization; @@ -49,7 +48,7 @@ public async Task Invalid_csv_request_body_should_fail() { using var client = new RestClient(_server.Url!, configureSerialization: cfg => cfg.UseCsvHelper()); - var response = await client.ExecuteAsync(new RestRequest()); + var response = await client.ExecuteAsync(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeFalse(); } @@ -61,18 +60,14 @@ public async Task Valid_csv_response_should_succeed() { using var client = new RestClient(_server.Url!, configureSerialization: cfg => cfg.UseSystemTextJson()); - var response = await client.ExecuteAsync(new RestRequest()); + var response = await client.ExecuteAsync(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeTrue(); } [Fact] public void SerializedObject_Should_Be() { - var serializer = new CsvHelperSerializer( - new CsvConfiguration(CultureInfo.InvariantCulture) { - NewLine = ";" - } - ); + var serializer = new CsvHelperSerializer(new(CultureInfo.InvariantCulture) { NewLine = ";" }); var item = Fixture.Create(); var actual = serializer.Serialize(item); @@ -83,11 +78,7 @@ public void SerializedObject_Should_Be() { [Fact] public void SerializedCollection_Should_Be() { - var serializer = new CsvHelperSerializer( - new CsvConfiguration(CultureInfo.InvariantCulture) { - NewLine = ";" - } - ); + var serializer = new CsvHelperSerializer(new(CultureInfo.InvariantCulture) { NewLine = ";" }); var items = new TestObject[] { new() { @@ -95,13 +86,13 @@ public void SerializedCollection_Should_Be() { SingleValue = 16.5f, StringValue = "hello", TimeSpanValue = TimeSpan.FromMinutes(10), - DateTimeValue = new DateTime(2024, 1, 20) + DateTimeValue = new(2024, 1, 20) }, new() { Int32Value = 65, DecimalValue = 89.555m, TimeSpanValue = TimeSpan.FromSeconds(61), - DateTimeValue = new DateTime(2022, 8, 19, 5, 15, 21) + DateTimeValue = new(2022, 8, 19, 5, 15, 21) }, new() { SingleValue = 80000, @@ -122,15 +113,14 @@ public void SerializedCollection_Should_Be() { class TestObjectCustomization : ICustomization { public void Customize(IFixture fixture) - => fixture.Customize( - o => o - .WithAutoProperties() - .With( - p => p.DateTimeValue, - () => { - var dt = fixture.Create(); - return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second); - } - ) + => fixture.Customize(o => o + .WithAutoProperties() + .With( + p => p.DateTimeValue, + () => { + var dt = fixture.Create(); + return new(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second); + } + ) ); } \ No newline at end of file diff --git a/test/RestSharp.Tests.Serializers.Json/NewtonsoftJson/IntegratedSimpleTests.cs b/test/RestSharp.Tests.Serializers.Json/NewtonsoftJson/IntegratedSimpleTests.cs index cf7e54c11..995834822 100644 --- a/test/RestSharp.Tests.Serializers.Json/NewtonsoftJson/IntegratedSimpleTests.cs +++ b/test/RestSharp.Tests.Serializers.Json/NewtonsoftJson/IntegratedSimpleTests.cs @@ -9,7 +9,7 @@ public sealed class IntegratedSimpleTests : IDisposable { readonly WireMockServer _server = WireMockServer.Start(); readonly RestClient _client; - public IntegratedSimpleTests() => _client = new RestClient(_server.Url!, configureSerialization: cfg => cfg.UseNewtonsoftJson()); + public IntegratedSimpleTests() => _client = new(_server.Url!, configureSerialization: cfg => cfg.UseNewtonsoftJson()); [Fact] public async Task Should_serialize_request() { @@ -19,7 +19,7 @@ public async Task Should_serialize_request() { var request = new RestRequest().AddJsonBody(testData); await _client.PostAsync(request); - var actual = serializer.Deserialize(new RestResponse(request) { Content = capturer.Body! }); + var actual = serializer.Deserialize(new(request) { Content = capturer.Body! }); actual.Should().BeEquivalentTo(testData); } @@ -43,7 +43,7 @@ public async Task Invalid_json_body_request_should_fail() { .RespondWith(Response.Create().WithBody("invalid json").WithHeader(KnownHeaders.ContentType, ContentType.Json)); - var response = await _client.ExecuteAsync(new RestRequest()); + var response = await _client.ExecuteAsync(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeFalse(); } @@ -56,7 +56,7 @@ public async Task Valid_json_response_should_succeed() { .Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithBodyAsJson(item)); - var response = await _client.ExecuteAsync(new RestRequest()); + var response = await _client.ExecuteAsync(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeTrue(); } diff --git a/test/RestSharp.Tests.Serializers.Json/SystemTextJson/SystemTextJsonTests.cs b/test/RestSharp.Tests.Serializers.Json/SystemTextJson/SystemTextJsonTests.cs index cc1177171..5e913b2d2 100644 --- a/test/RestSharp.Tests.Serializers.Json/SystemTextJson/SystemTextJsonTests.cs +++ b/test/RestSharp.Tests.Serializers.Json/SystemTextJson/SystemTextJsonTests.cs @@ -9,7 +9,7 @@ public sealed class SystemTextJsonTests : IDisposable { readonly WireMockServer _server = WireMockServer.Start(); readonly RestClient _client; - public SystemTextJsonTests() => _client = new RestClient(_server.Url!); + public SystemTextJsonTests() => _client = new(_server.Url!); [Fact] public async Task Should_serialize_request() { @@ -21,7 +21,7 @@ public async Task Should_serialize_request() { await _client.PostAsync(request); - var actual = serializer.Deserialize(new RestResponse(request) { Content = capturer.Body }); + var actual = serializer.Deserialize(new(request) { Content = capturer.Body }); actual.Should().BeEquivalentTo(testData); } @@ -43,7 +43,7 @@ public async Task Posting_invalid_json_should_fail() { .Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithBody("invalid json").WithHeader(KnownHeaders.ContentType, ContentType.Json)); - var response = await _client.ExecuteAsync(new RestRequest()); + var response = await _client.ExecuteAsync(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeFalse(); } @@ -56,7 +56,7 @@ public async Task Receiving_valid_json_should_succeed() { .Given(Request.Create().WithPath("/").UsingGet()) .RespondWith(Response.Create().WithBodyAsJson(item)); - var response = await _client.ExecuteAsync(new RestRequest()); + var response = await _client.ExecuteAsync(new()); response.IsSuccessStatusCode.Should().BeTrue(); response.IsSuccessful.Should().BeTrue(); } diff --git a/test/RestSharp.Tests.Serializers.Xml/NamespacedXmlTests.cs b/test/RestSharp.Tests.Serializers.Xml/NamespacedXmlTests.cs index 4d3a32b64..a0572b45d 100644 --- a/test/RestSharp.Tests.Serializers.Xml/NamespacedXmlTests.cs +++ b/test/RestSharp.Tests.Serializers.Xml/NamespacedXmlTests.cs @@ -25,22 +25,22 @@ static string CreateUnderscoresXml() { var ns = XNamespace.Get("http://restsharp.org"); var root = new XElement(ns + "Person"); - root.Add(new XElement(ns + "Name", "John Sheehan")); - root.Add(new XElement(ns + "Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); + root.Add(new XElement(ns + "Name", "John Sheehan")); + root.Add(new XElement(ns + "Start_Date", new DateTime(2009, 9, 25, 0, 6, 1))); root.Add(new XAttribute(ns + "Age", 28)); - root.Add(new XElement(ns + "Percent", 99.9999m)); - root.Add(new XElement(ns + "Big_Number", long.MaxValue)); + root.Add(new XElement(ns + "Percent", 99.9999m)); + root.Add(new XElement(ns + "Big_Number", long.MaxValue)); root.Add(new XAttribute(ns + "Is_Cool", false)); - root.Add(new XElement(ns + "Ignore", "dummy")); + root.Add(new XElement(ns + "Ignore", "dummy")); root.Add(new XAttribute(ns + "Read_Only", "dummy")); root.Add(new XAttribute(ns + "Unique_Id", new Guid(GuidString))); - root.Add(new XElement(ns + "Url", "http://example.com")); - root.Add(new XElement(ns + "Url_Path", "/foo/bar")); + root.Add(new XElement(ns + "Url", "http://example.com")); + root.Add(new XElement(ns + "Url_Path", "/foo/bar")); root.Add( new XElement( ns + "Best_Friend", - new XElement(ns + "Name", "The Fonz"), + new XElement(ns + "Name", "The Fonz"), new XAttribute(ns + "Since", 1952) ) ); @@ -51,7 +51,7 @@ static string CreateUnderscoresXml() { friends.Add( new XElement( ns + "Friend", - new XElement(ns + "Name", "Friend" + i), + new XElement(ns + "Name", "Friend" + i), new XAttribute(ns + "Since", DateTime.Now.Year - i) ) ); @@ -102,7 +102,7 @@ static string CreateElementsXml() { friends.Add( new XElement( ns + "Friend", - new XElement(ns + "Name", "Friend" + i), + new XElement(ns + "Name", "Friend" + i), new XElement(ns + "Since", DateTime.Now.Year - i) ) ); @@ -184,14 +184,14 @@ public void Can_Deserialize_Attributes_With_Namespace() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new(GuidString), p.UniqueId); + Assert.Equal(new("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); @@ -205,14 +205,14 @@ public void Can_Deserialize_Elements_With_Namespace() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new(GuidString), p.UniqueId); + Assert.Equal(new("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -228,14 +228,14 @@ public void Can_Deserialize_Elements_With_Namespace_Autodetect_Namespace() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new(GuidString), p.UniqueId); + Assert.Equal(new("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -263,14 +263,14 @@ public void Can_Deserialize_Names_With_Underscores_With_Namespace() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new(GuidString), p.UniqueId); + Assert.Equal(new("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -298,7 +298,7 @@ public void Can_Deserialize_Node_Using_Exact_Name_Defined_In_DeserializeAs_Attri }; var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() }); + var output = xml.Deserialize(new() { Content = doc.ToString() }); Assert.NotNull(output); @@ -324,4 +324,4 @@ public void Ignore_ReadOnly_Property_That_Exists_In_Data() { Assert.Null(p.ReadOnlyProxy); } -} +} \ No newline at end of file diff --git a/test/RestSharp.Tests.Serializers.Xml/XmlAttributeDeserializerTests.cs b/test/RestSharp.Tests.Serializers.Xml/XmlAttributeDeserializerTests.cs index a9294a522..74dcf041a 100644 --- a/test/RestSharp.Tests.Serializers.Xml/XmlAttributeDeserializerTests.cs +++ b/test/RestSharp.Tests.Serializers.Xml/XmlAttributeDeserializerTests.cs @@ -22,13 +22,11 @@ public void Can_Deserialize_Lists_of_Simple_Types() { var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize( - new RestResponse { Content = doc.ToString() } - )!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.NotEmpty(output.Numbers); - Assert.False(output.Names[0].Length == 0); - Assert.False(output.Numbers.Sum() == 0); + Assert.NotEqual(0, output.Names[0].Length); + Assert.NotEqual(0, output.Numbers.Sum()); } [Fact] @@ -36,7 +34,7 @@ public void Can_Deserialize_To_List_Inheritor_From_Custom_Root_With_Attributes() var xmlPath = PathFor("ListWithAttributes.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer { RootElement = "Calls" }; - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(3, output.NumPages); Assert.Equal(2, output.Count); @@ -47,7 +45,7 @@ public void Can_Deserialize_To_Standalone_List_Without_Matching_Class_Case() { var xmlPath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } @@ -57,7 +55,7 @@ public void Can_Deserialize_To_Standalone_List_With_Matching_Class_Case() { var xmlPath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } @@ -67,7 +65,7 @@ public void Can_Deserialize_Directly_To_Lists_Off_Root_Element() { var xmlPath = PathFor("directlists.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize>(new() { Content = doc.ToString() })!; Assert.Equal(2, output.Count); } @@ -77,7 +75,7 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_Without_Matching_Cl var xmlPath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlPath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Images.Count); } @@ -87,7 +85,7 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class var xmlpath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlpath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.images.Count); } @@ -97,7 +95,7 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class var xmlpath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlpath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } @@ -107,7 +105,7 @@ public void Can_Deserialize_Nested_List_Items_Without_Matching_Class_Name() { var xmlpath = PathFor("NestedListSample.xml"); var doc = XDocument.Load(xmlpath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Images.Count); } @@ -117,7 +115,7 @@ public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() { var xmlpath = PathFor("NestedListSample.xml"); var doc = XDocument.Load(xmlpath); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.images.Count); } @@ -126,7 +124,7 @@ public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() { public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() { var doc = CreateXmlWithEmptyNestedList(); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.NotNull(output.Images); Assert.Empty(output.Images); @@ -136,7 +134,7 @@ public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() { public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() { var doc = CreateXmlWithEmptyInlineList(); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.NotNull(output.Images); Assert.Empty(output.Images); @@ -146,7 +144,7 @@ public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() { public void Can_Deserialize_Empty_Elements_to_Nullable_Values() { var doc = CreateXmlWithNullValues(); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -159,7 +157,7 @@ public void Can_Deserialize_Elements_to_Nullable_Values() { var doc = CreateXmlWithoutEmptyValues(culture); var xml = new XmlAttributeDeserializer { Culture = culture }; - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.NotNull(output.Id); Assert.NotNull(output.StartDate); @@ -193,14 +191,14 @@ public void Can_Deserialize_TimeSpan() { var d = new XmlAttributeDeserializer { Culture = culture }; var payload = d.Deserialize(response)!; - Assert.Equal(new TimeSpan(468006), payload.Tick); - Assert.Equal(new TimeSpan(0, 0, 0, 0, 125), payload.Millisecond); - Assert.Equal(new TimeSpan(0, 0, 8), payload.Second); - Assert.Equal(new TimeSpan(0, 55, 2), payload.Minute); - Assert.Equal(new TimeSpan(21, 30, 7), payload.Hour); + Assert.Equal(new(468006), payload.Tick); + Assert.Equal(new(0, 0, 0, 0, 125), payload.Millisecond); + Assert.Equal(new(0, 0, 8), payload.Second); + Assert.Equal(new(0, 55, 2), payload.Minute); + Assert.Equal(new(21, 30, 7), payload.Hour); Assert.Null(payload.NullableWithoutValue); Assert.NotNull(payload.NullableWithValue); - Assert.Equal(new TimeSpan(21, 30, 7), payload.NullableWithValue.Value); + Assert.Equal(new(21, 30, 7), payload.NullableWithValue.Value); } [Fact] @@ -245,15 +243,15 @@ public void Can_Deserialize_Elements_On_Default_Root() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); + Assert.Equal(new(GuidString), p.UniqueId); Assert.Equal(Guid.Empty, p.EmptyGuid); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.Equal(Order.Third, p.Order); Assert.Equal(Disposition.SoSo, p.Disposition); Assert.NotNull(p.Friends); @@ -271,14 +269,14 @@ public void Can_Deserialize_Attributes_On_Default_Root() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new (GuidString), p.UniqueId); + Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.BestFriend); Assert.Equal("The Fonz", p.BestFriend.Name); Assert.Equal(1952, p.BestFriend.Since); @@ -312,14 +310,14 @@ public void Can_Deserialize_Names_With_Underscores_On_Default_Root() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new (GuidString), p.UniqueId); + Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -338,14 +336,14 @@ public void Can_Deserialize_Names_With_Dashes_On_Default_Root() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new (GuidString), p.UniqueId); + Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -364,14 +362,14 @@ public void Can_Deserialize_Names_With_Underscores_Without_Matching_Case_On_Defa var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new (GuidString), p.UniqueId); + Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -390,14 +388,14 @@ public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() { var p = d.Deserialize(response); Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new (2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("http://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new (GuidString), p.UniqueId); + Assert.Equal(new ("http://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new ("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -496,7 +494,7 @@ public void Can_Deserialize_Boolean_From_String() { public void Can_Deserialize_Empty_Elements_With_Attributes_to_Nullable_Values() { var doc = CreateXmlWithAttributesAndNullValues(); var xml = new XmlAttributeDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); diff --git a/test/RestSharp.Tests.Serializers.Xml/XmlDeserializerTests.cs b/test/RestSharp.Tests.Serializers.Xml/XmlDeserializerTests.cs index b8569e82c..5f26af53b 100644 --- a/test/RestSharp.Tests.Serializers.Xml/XmlDeserializerTests.cs +++ b/test/RestSharp.Tests.Serializers.Xml/XmlDeserializerTests.cs @@ -357,7 +357,7 @@ public void Able_to_use_alternative_name_for_arrays() { var xmlFilePath = PathFor("header_and_rows.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize
(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize
(new() { Content = doc.ToString() })!; Assert.NotNull(output); Assert.Equal("text title", output.Title); @@ -368,7 +368,7 @@ public void Able_to_use_alternative_name_for_arrays() { public void Can_deal_with_value_attribute() { const string content = "Green255"; var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = content })!; + var output = xml.Deserialize(new() { Content = content })!; Assert.NotNull(output); Assert.Equal("Green", output.Name); @@ -384,7 +384,7 @@ public void Can_Deserialize_Attribute_Using_Exact_Name_Defined_In_DeserializeAs_ }; var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = content })!; + var output = xml.Deserialize(new() { Content = content })!; Assert.Equal(expected.AttributeValue, output.AttributeValue); } @@ -515,7 +515,7 @@ public void Can_Deserialize_Directly_To_Lists_Off_Root_Element() { var xmlFilePath = PathFor("directlists.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize>(new() { Content = doc.ToString() })!; Assert.Equal(2, output.Count); } @@ -588,7 +588,7 @@ public void Can_Deserialize_Elements_to_Nullable_Values() { var xml = new XmlDeserializer { Culture = culture }; - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.NotNull(output.Id); Assert.NotNull(output.StartDate); @@ -602,7 +602,7 @@ public void Can_Deserialize_Elements_to_Nullable_Values() { public void Can_Deserialize_Empty_Elements_to_Nullable_Values() { var doc = CreateXmlWithNullValues(); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -613,7 +613,7 @@ public void Can_Deserialize_Empty_Elements_to_Nullable_Values() { public void Can_Deserialize_Empty_Elements_With_Attributes_to_Nullable_Values() { var doc = CreateXmlWithAttributesAndNullValues(); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -654,8 +654,7 @@ public void Can_throw_format_exception_xml() { var response = new RestResponse { Content = doc.ToString() }; var d = new XmlDeserializer(); - Assert.Throws( - () => d.Deserialize(response) + Assert.Throws(() => d.Deserialize(response) ); } @@ -675,7 +674,7 @@ public void Can_Deserialize_Google_Weather_Xml() { public void Can_Deserialize_Inline_List_Without_Elements_To_Empty_List() { var doc = CreateXmlWithEmptyInlineList(); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.NotNull(output.Images); Assert.Empty(output.Images); @@ -686,7 +685,7 @@ public void Can_Deserialize_Into_Struct() { const string content = "oneOneOnetwoTwoTwo3"; var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = content }); + var output = xml.Deserialize(new() { Content = content }); Assert.Equal("oneOneOne", output.One); Assert.Equal("twoTwoTwo", output.Two); @@ -714,12 +713,10 @@ public void Can_Deserialize_Lists_of_Simple_Types() { var doc = XDocument.Load(xmlPath); var xml = new XmlDeserializer(); - var output = xml.Deserialize( - new RestResponse { Content = doc.ToString() } - )!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; - Assert.False(output.Names[0].Length == 0); - Assert.False(output.Numbers.Sum() == 0); + Assert.NotEqual(0, output.Names[0].Length); + Assert.NotEqual(0, output.Numbers.Sum()); } [Fact] @@ -730,14 +727,14 @@ public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() { var p = d.Deserialize(response)!; Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("https://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new(GuidString), p.UniqueId); + Assert.Equal(new("https://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -752,7 +749,7 @@ public void Can_Deserialize_Lower_Cased_Root_Elements_With_Dashes() { public void Can_Deserialize_Mixture_Of_Empty_Elements_With_Attributes_And_Populated_Elements() { var doc = CreateXmlWithAttributesAndNullValuesAndPopulatedValues(); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.Null(output.Id); Assert.Null(output.StartDate); @@ -767,14 +764,14 @@ public void Can_Deserialize_Names_With_Dashes_On_Default_Root() { var p = d.Deserialize(response)!; Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("https://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new(GuidString), p.UniqueId); + Assert.Equal(new("https://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -793,14 +790,14 @@ public void Can_Deserialize_Names_With_Underscores_On_Default_Root() { var p = d.Deserialize(response)!; Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("https://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new(GuidString), p.UniqueId); + Assert.Equal(new("https://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -819,14 +816,14 @@ public void Can_Deserialize_Names_With_Underscores_Without_Matching_Case_On_Defa var p = d.Deserialize(response)!; Assert.Equal("John Sheehan", p.Name); - Assert.Equal(new DateTime(2009, 9, 25, 0, 6, 1), p.StartDate); + Assert.Equal(new(2009, 9, 25, 0, 6, 1), p.StartDate); Assert.Equal(28, p.Age); Assert.Equal(long.MaxValue, p.BigNumber); Assert.Equal(99.9999m, p.Percent); Assert.False(p.IsCool); - Assert.Equal(new Guid(GuidString), p.UniqueId); - Assert.Equal(new Uri("https://example.com", UriKind.RelativeOrAbsolute), p.Url); - Assert.Equal(new Uri("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); + Assert.Equal(new(GuidString), p.UniqueId); + Assert.Equal(new("https://example.com", UriKind.RelativeOrAbsolute), p.Url); + Assert.Equal(new("/foo/bar", UriKind.RelativeOrAbsolute), p.UrlPath); Assert.NotNull(p.Friends); Assert.Equal(10, p.Friends.Count); Assert.NotNull(p.BestFriend); @@ -842,7 +839,7 @@ public void Can_Deserialize_Nested_List_Items_With_Matching_Class_Name() { var xmlFilePath = PathFor("NestedListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.images.Count); } @@ -852,7 +849,7 @@ public void Can_Deserialize_Nested_List_Items_Without_Matching_Class_Name() { var xmlFilePath = PathFor("NestedListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Images.Count); } @@ -861,7 +858,7 @@ public void Can_Deserialize_Nested_List_Items_Without_Matching_Class_Name() { public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() { var doc = CreateXmlWithEmptyNestedList(); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc })!; + var output = xml.Deserialize(new() { Content = doc })!; Assert.NotNull(output.Images); Assert.Empty(output.Images); @@ -871,10 +868,8 @@ public void Can_Deserialize_Nested_List_Without_Elements_To_Empty_List() { public void Can_Deserialize_Node_That_Has_Attribute_And_Content() { var doc = CreateNoteXml(); - var response = new RestResponse { - Content = doc - }; - var d = new XmlDeserializer(); + var response = new RestResponse { Content = doc }; + var d = new XmlDeserializer(); var note = d.Deserialize(response)!; @@ -887,12 +882,10 @@ public void Can_Deserialize_Node_That_Has_Attribute_And_Content() { public void Can_Deserialize_Node_Using_Exact_Name_Defined_In_DeserializeAs_Attribute() { const string content = "711"; - var expected = new SingleNode { - Node = "711" - }; + var expected = new SingleNode { Node = "711" }; var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = content })!; + var output = xml.Deserialize(new() { Content = content })!; Assert.NotNull(output); Assert.Equal(expected.Node, output.Node); @@ -903,7 +896,7 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.images.Count); } @@ -913,7 +906,7 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_With_Matching_Class var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } @@ -923,7 +916,7 @@ public void Can_Deserialize_Parentless_aka_Inline_List_Items_Without_Matching_Cl var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Images.Count); } @@ -961,19 +954,17 @@ public void Can_Deserialize_TimeSpan() { Content = doc.ToString() }; - var d = new XmlDeserializer { - Culture = culture - }; + var d = new XmlDeserializer { Culture = culture }; var payload = d.Deserialize(response)!; - Assert.Equal(new TimeSpan(468006), payload.Tick); - Assert.Equal(new TimeSpan(0, 0, 0, 0, 125), payload.Millisecond); - Assert.Equal(new TimeSpan(0, 0, 8), payload.Second); - Assert.Equal(new TimeSpan(0, 55, 2), payload.Minute); - Assert.Equal(new TimeSpan(21, 30, 7), payload.Hour); + Assert.Equal(new(468006), payload.Tick); + Assert.Equal(new(0, 0, 0, 0, 125), payload.Millisecond); + Assert.Equal(new(0, 0, 8), payload.Second); + Assert.Equal(new(0, 55, 2), payload.Minute); + Assert.Equal(new(21, 30, 7), payload.Hour); Assert.Null(payload.NullableWithoutValue); Assert.NotNull(payload.NullableWithValue); - Assert.Equal(new TimeSpan(21, 30, 7), payload.NullableWithValue.Value); + Assert.Equal(new(21, 30, 7), payload.NullableWithValue.Value); } [Fact] @@ -981,7 +972,7 @@ public void Can_Deserialize_To_List_Inheritor_From_Custom_Root_With_Attributes() var xmlFilePath = PathFor("ListWithAttributes.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer { RootElement = "Calls" }; - var output = xml.Deserialize(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize(new() { Content = doc.ToString() })!; Assert.Equal(3, output.NumPages); Assert.Equal(2, output.Count); @@ -992,7 +983,7 @@ public void Can_Deserialize_To_Standalone_List_With_Matching_Class_Case() { var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } @@ -1002,7 +993,7 @@ public void Can_Deserialize_To_Standalone_List_Without_Matching_Class_Case() { var xmlFilePath = PathFor("InlineListSample.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize>(new() { Content = doc.ToString() })!; Assert.Equal(4, output.Count); } @@ -1012,7 +1003,7 @@ public void Can_Deserialize_When_RootElement_Deeper_Then_One() { const string content = "oneOneOnetwoTwoTwo3"; var xml = new XmlDeserializer { RootElement = "subsubroot" }; - var output = xml.Deserialize(new RestResponse { Content = content }); + var output = xml.Deserialize(new() { Content = content }); Assert.Equal("oneOneOne", output.One); Assert.Equal("twoTwoTwo", output.Two); @@ -1024,7 +1015,7 @@ public void Can_Use_DeserializeAs_Attribute() { const string content = "1Jacksonoddball"; var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = content })!; + var output = xml.Deserialize(new() { Content = content })!; Assert.NotNull(output); Assert.Equal("1", output.Sid); @@ -1037,7 +1028,7 @@ public void Can_Use_DeserializeAs_Attribute_for_List() { var xmlFilePath = PathFor("deserialize_as_list.xml"); var doc = XDocument.Load(xmlFilePath); var xml = new XmlDeserializer(); - var output = xml.Deserialize>(new RestResponse { Content = doc.ToString() })!; + var output = xml.Deserialize>(new() { Content = doc.ToString() })!; Assert.NotNull(output); Assert.Equal("1", output[0].Sid); @@ -1049,7 +1040,7 @@ public void Can_Use_DeserializeAs_Attribute_for_List_Property() { "TestValue"; var xml = new XmlDeserializer(); - var output = xml.Deserialize(new RestResponse { Content = content })!; + var output = xml.Deserialize(new() { Content = content })!; Assert.NotNull(output); Assert.NotNull(output.ListWithGoodName); @@ -1060,14 +1051,10 @@ public void Can_Use_DeserializeAs_Attribute_for_List_Property() { public void Cannot_Deserialize_Node_To_An_Object_That_Has_Two_Properties_With_Text_Content_Attributes() { var doc = CreateNoteXml(); - var response = new RestResponse { - Content = doc - }; - var d = new XmlDeserializer(); + var response = new RestResponse { Content = doc }; + var d = new XmlDeserializer(); - Assert.Throws( - () => d.Deserialize(response) - ); + Assert.Throws(() => d.Deserialize(response)); } [Fact] diff --git a/test/RestSharp.Tests.Serializers.Xml/XmlSerializerTests.cs b/test/RestSharp.Tests.Serializers.Xml/XmlSerializerTests.cs index 4762f26d8..ae6d6ea2b 100644 --- a/test/RestSharp.Tests.Serializers.Xml/XmlSerializerTests.cs +++ b/test/RestSharp.Tests.Serializers.Xml/XmlSerializerTests.cs @@ -20,8 +20,8 @@ public void Can_serialize_a_list_of_items_with_interface_type() { Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), - Items = [new Item { Name = "One", Value = 1 }] + StartDate = new(2009, 12, 18, 10, 2, 23), + Items = [new() { Name = "One", Value = 1 }] }, new Item { Name = "Two", Value = 2 }, @@ -40,27 +40,27 @@ public void Can_serialize_a_list_of_items_with_interface_type() { public void Can_serialize_a_list_which_is_the_content_of_root_element() { var contacts = new Contacts { People = [ - new Person { + new() { Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), + StartDate = new(2009, 12, 18, 10, 2, 23), Items = [ - new Item { Name = "One", Value = 1 }, - new Item { Name = "Two", Value = 2 }, - new Item { Name = "Three", Value = 3 } + new() { Name = "One", Value = 1 }, + new() { Name = "Two", Value = 2 }, + new() { Name = "Three", Value = 3 } ] }, - new Person { + new() { Name = "Bar", Age = 23, Price = 23.23m, - StartDate = new DateTime(2009, 12, 23, 10, 23, 23), + StartDate = new(2009, 12, 23, 10, 23, 23), Items = [ - new Item { Name = "One", Value = 1 }, - new Item { Name = "Two", Value = 2 }, - new Item { Name = "Three", Value = 3 } + new() { Name = "One", Value = 1 }, + new() { Name = "Two", Value = 2 }, + new() { Name = "Three", Value = 3 } ] } ] @@ -80,22 +80,22 @@ public void Can_serialize_a_list_which_is_the_root_element() { Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), + StartDate = new(2009, 12, 18, 10, 2, 23), Items = [ - new Item { Name = "One", Value = 1 }, - new Item { Name = "Two", Value = 2 }, - new Item { Name = "Three", Value = 3 } + new() { Name = "One", Value = 1 }, + new() { Name = "Two", Value = 2 }, + new() { Name = "Three", Value = 3 } ] }, new() { Name = "Bar", Age = 23, Price = 23.23m, - StartDate = new DateTime(2009, 12, 23, 10, 23, 23), + StartDate = new(2009, 12, 23, 10, 23, 23), Items = [ - new Item { Name = "One", Value = 1 }, - new Item { Name = "Two", Value = 2 }, - new Item { Name = "Three", Value = 3 } + new() { Name = "One", Value = 1 }, + new() { Name = "Two", Value = 2 }, + new() { Name = "Three", Value = 3 } ] } }; @@ -143,11 +143,11 @@ public void Can_serialize_simple_POCO() { Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), + StartDate = new(2009, 12, 18, 10, 2, 23), Items = [ - new Item { Name = "One", Value = 1 }, - new Item { Name = "Two", Value = 2 }, - new Item { Name = "Three", Value = 3 } + new() { Name = "One", Value = 1 }, + new() { Name = "Two", Value = 2 }, + new() { Name = "Three", Value = 3 } ] }; var xml = new XmlSerializer(); @@ -163,7 +163,7 @@ public void Can_serialize_simple_POCO_With_Attribute_Options_Defined() { Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23) + StartDate = new(2009, 12, 18, 10, 2, 23) }; var xml = new XmlSerializer(); var doc = xml.Serialize(poco); @@ -178,10 +178,10 @@ public void Can_serialize_simple_POCO_With_Attribute_Options_Defined_And_Propert Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), - ContactData = new ContactData { + StartDate = new(2009, 12, 18, 10, 2, 23), + ContactData = new() { EmailAddresses = [ - new EmailAddress { + new() { Address = "test@test.com", Location = "Work" } @@ -201,7 +201,7 @@ public void Can_serialize_simple_POCO_With_DateFormat_Specified() { Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23) + StartDate = new(2009, 12, 18, 10, 2, 23) }; var xml = new XmlSerializer { DateFormat = DateFormat.ISO_8601 }; var doc = xml.Serialize(poco); @@ -216,7 +216,7 @@ public void Can_serialize_simple_POCO_With_Different_Root_Element() { Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23) + StartDate = new(2009, 12, 18, 10, 2, 23) }; var xml = new XmlSerializer { RootElement = "Result" }; var doc = xml.Serialize(poco); @@ -231,7 +231,7 @@ public void Can_serialize_simple_POCO_With_XmlFormat_Specified() { Name = "Foo", Age = 50, Price = 19.95m, - StartDate = new DateTime(2009, 12, 18, 10, 2, 23), + StartDate = new(2009, 12, 18, 10, 2, 23), IsCool = false }; var xml = new XmlSerializer { DateFormat = DateFormat.ISO_8601 }; @@ -258,7 +258,7 @@ public void Serializes_Properties_In_Specified_Order() { var ordered = new OrderedProperties { Name = "Name", Age = 99, - StartDate = new DateTime(2010, 1, 1) + StartDate = new(2010, 1, 1) }; var xml = new XmlSerializer(); var doc = xml.Serialize(ordered); @@ -541,7 +541,7 @@ static XDocument GetPeopleXDoc(IFormatProvider culture) { element.Add(items); root.Add(element); - element = new XElement("Person"); + element = new("Person"); element.Add( new XElement("Name", "Bar"), diff --git a/test/RestSharp.Tests.Shared/Fixtures/Handlers.cs b/test/RestSharp.Tests.Shared/Fixtures/Handlers.cs index a61b05550..8cd404dd4 100644 --- a/test/RestSharp.Tests.Shared/Fixtures/Handlers.cs +++ b/test/RestSharp.Tests.Shared/Fixtures/Handlers.cs @@ -23,7 +23,7 @@ public static class Handlers { ///
public static Action Generic() where T : new() => ctx => { - var methodName = ctx.Request.Url.Segments.Last(); + var methodName = ctx.Request.Url!.Segments.Last(); var method = typeof(T).GetMethod( methodName, diff --git a/test/RestSharp.Tests.Shared/Fixtures/RequestBodyCapturer.cs b/test/RestSharp.Tests.Shared/Fixtures/RequestBodyCapturer.cs index bcb57764a..cc9ead4fb 100644 --- a/test/RestSharp.Tests.Shared/Fixtures/RequestBodyCapturer.cs +++ b/test/RestSharp.Tests.Shared/Fixtures/RequestBodyCapturer.cs @@ -23,7 +23,7 @@ public bool CaptureHeaders(IDictionary headers) { } public bool CaptureUrl(string url) { - Url = new Uri(url); + Url = new(url); return true; } } \ No newline at end of file diff --git a/test/RestSharp.Tests.Shared/Fixtures/SimpleServer.cs b/test/RestSharp.Tests.Shared/Fixtures/SimpleServer.cs index 6ebb81d13..5f6abc2f9 100644 --- a/test/RestSharp.Tests.Shared/Fixtures/SimpleServer.cs +++ b/test/RestSharp.Tests.Shared/Fixtures/SimpleServer.cs @@ -16,7 +16,7 @@ public sealed class SimpleServer : IDisposable { AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous ) { Url = $"http://localhost:{port}/"; - _server = new WebServer(Url, handler, authenticationSchemes); + _server = new(Url, handler, authenticationSchemes); Task.Run(() => _server.Run(_cts.Token)); } @@ -31,7 +31,7 @@ public static SimpleServer Create( AuthenticationSchemes authenticationSchemes = AuthenticationSchemes.Anonymous ) { var port = Random.Next(1000, 9999); - return new SimpleServer(port, handler, authenticationSchemes); + return new(port, handler, authenticationSchemes); } public void SetHandler(Action handler) => _server.ChangeHandler(handler); diff --git a/test/RestSharp.Tests/RestRequestTests.cs b/test/RestSharp.Tests/RestRequestTests.cs index c7e28c702..988f91734 100644 --- a/test/RestSharp.Tests/RestRequestTests.cs +++ b/test/RestSharp.Tests/RestRequestTests.cs @@ -9,17 +9,25 @@ public void RestRequest_Request_Property() { [Fact] public void RestRequest_Test_Already_Encoded() { - var request = new RestRequest("/api/get?query=Id%3d198&another=notencoded"); + const string resource = "/api/get?query=Id%3d198&another=notencoded&novalue="; + const string baseUrl = "https://example.com"; + + var request = new RestRequest(resource); var parameters = request.Parameters.ToArray(); request.Resource.Should().Be("/api/get"); - parameters.Length.Should().Be(2); + parameters.Length.Should().Be(3); var expected = new[] { new { Name = "query", Value = "Id%3d198", Type = ParameterType.QueryString, Encode = false }, - new { Name = "another", Value = "notencoded", Type = ParameterType.QueryString, Encode = false } + new { Name = "another", Value = "notencoded", Type = ParameterType.QueryString, Encode = false }, + new { Name = "novalue", Value = "", Type = ParameterType.QueryString, Encode = false } }; parameters.Should().BeEquivalentTo(expected, options => options.ExcludingMissingMembers()); + + using var client = new RestClient(baseUrl); + var actual = client.BuildUri(request); + actual.AbsoluteUri.Should().Be($"{baseUrl}{resource}"); } [Fact]