Skip to content

Commit ee97e33

Browse files
committed
Fixing the exception for #867
1 parent 370659d commit ee97e33

File tree

9 files changed

+119
-92
lines changed

9 files changed

+119
-92
lines changed

src/RestSharp/Authenticators/OAuth/Extensions/StringExtensions.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,8 @@
1818

1919
namespace RestSharp.Authenticators.OAuth.Extensions
2020
{
21-
internal static class StringExtensions
21+
static class StringExtensions
2222
{
23-
public static bool IsNullOrBlank(this string value) => string.IsNullOrWhiteSpace(value);
24-
2523
public static bool EqualsIgnoreCase(this string left, string right) => string.Equals(left, right, StringComparison.InvariantCultureIgnoreCase);
2624

2725
public static string Then(this string input, string value) => string.Concat(input, value);

src/RestSharp/Authenticators/OAuth/OAuth1Authenticator.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
using System.Web;
2020
using RestSharp.Authenticators.OAuth;
2121
using RestSharp.Authenticators.OAuth.Extensions;
22+
using RestSharp.Extensions;
2223

2324
// ReSharper disable CheckNamespace
2425

@@ -314,7 +315,7 @@ IEnumerable<Parameter> CreateHeaderParameters()
314315
=> new[] {new Parameter("Authorization", GetAuthorizationHeader(), ParameterType.HttpHeader)};
315316

316317
IEnumerable<Parameter> CreateUrlParameters()
317-
=> parameters.Where(p => !p.Name.IsNullOrBlank() && (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_")))
318+
=> parameters.Where(p => !p.Name.IsEmpty() && (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_")))
318319
.Select(p => new Parameter(p.Name, HttpUtility.UrlDecode(p.Value), ParameterType.GetOrPost));
319320

320321
string GetAuthorizationHeader()
@@ -324,13 +325,13 @@ string GetAuthorizationHeader()
324325
.OrderBy(x => x, WebPair.Comparer)
325326
.Where(
326327
p =>
327-
!p.Name.IsNullOrBlank() && !p.Value.IsNullOrBlank() &&
328+
!p.Name.IsEmpty() && !p.Value.IsEmpty() &&
328329
(p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_"))
329330
)
330331
.Select(x => $"{x.Name}=\"{x.Value}\"")
331332
.ToList();
332333

333-
if (!Realm.IsNullOrBlank())
334+
if (!Realm.IsEmpty())
334335
oathParameters.Insert(0, $"realm=\"{OAuthTools.UrlEncodeRelaxed(Realm)}\"");
335336

336337
return "OAuth " + string.Join(",", oathParameters);

src/RestSharp/Authenticators/OAuth/OAuthTools.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ public static string GetSignature(
249249
string tokenSecret
250250
)
251251
{
252-
if (tokenSecret.IsNullOrBlank())
252+
if (tokenSecret.IsEmpty())
253253
tokenSecret = string.Empty;
254254

255255
var unencodedConsumerSecret = consumerSecret;

src/RestSharp/Authenticators/OAuth/OAuthWorkflow.cs

Lines changed: 23 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@
1616
using System.Collections.Generic;
1717
using System.Web;
1818
using RestSharp.Authenticators.OAuth.Extensions;
19+
using RestSharp.Extensions;
20+
using RestSharp.Validation;
1921

2022
namespace RestSharp.Authenticators.OAuth
2123
{
2224
/// <summary>
2325
/// A class to encapsulate OAuth authentication flow.
2426
/// </summary>
25-
internal sealed class OAuthWorkflow
27+
sealed class OAuthWorkflow
2628
{
2729
public string Version { get; set; }
2830

@@ -66,8 +68,7 @@ public string BuildRequestTokenInfo(string method, WebPairCollection parameters)
6668
{
6769
ValidateTokenRequestState();
6870

69-
if (parameters == null)
70-
parameters = new WebPairCollection();
71+
parameters ??= new WebPairCollection();
7172

7273
var timestamp = OAuthTools.GetTimestamp();
7374
var nonce = OAuthTools.GetNonce();
@@ -89,8 +90,7 @@ public string BuildAccessTokenSignature(string method, WebPairCollection paramet
8990
{
9091
ValidateAccessRequestState();
9192

92-
if (parameters == null)
93-
parameters = new WebPairCollection();
93+
parameters ??= new WebPairCollection();
9494

9595
var uri = new Uri(AccessTokenUrl);
9696
var timestamp = OAuthTools.GetTimestamp();
@@ -138,8 +138,7 @@ public string BuildProtectedResourceSignature(string method, WebPairCollection p
138138
{
139139
ValidateProtectedResourceState();
140140

141-
if (parameters == null)
142-
parameters = new WebPairCollection();
141+
parameters ??= new WebPairCollection();
143142

144143
// Include url parameters in query pool
145144
var uri = new Uri(url);
@@ -163,53 +162,31 @@ public string BuildProtectedResourceSignature(string method, WebPairCollection p
163162

164163
void ValidateTokenRequestState()
165164
{
166-
if (RequestTokenUrl.IsNullOrBlank())
167-
throw new ArgumentException("You must specify a request token URL");
168-
169-
if (ConsumerKey.IsNullOrBlank())
170-
throw new ArgumentException("You must specify a consumer key");
171-
172-
if (ConsumerSecret.IsNullOrBlank())
173-
throw new ArgumentException("You must specify a consumer secret");
165+
Ensure.NotEmpty(RequestTokenUrl, nameof(RequestTokenUrl));
166+
Ensure.NotEmpty(ConsumerKey, nameof(ConsumerKey));
167+
Ensure.NotEmpty(ConsumerSecret, nameof(ConsumerSecret));
174168
}
175169

176170
void ValidateAccessRequestState()
177171
{
178-
if (AccessTokenUrl.IsNullOrBlank())
179-
throw new ArgumentException("You must specify an access token URL");
180-
181-
if (ConsumerKey.IsNullOrBlank())
182-
throw new ArgumentException("You must specify a consumer key");
183-
184-
if (ConsumerSecret.IsNullOrBlank())
185-
throw new ArgumentException("You must specify a consumer secret");
186-
187-
if (Token.IsNullOrBlank())
188-
throw new ArgumentException("You must specify a token");
172+
Ensure.NotEmpty(AccessTokenUrl, nameof(AccessTokenUrl));
173+
Ensure.NotEmpty(ConsumerKey, nameof(ConsumerKey));
174+
Ensure.NotEmpty(ConsumerSecret, nameof(ConsumerSecret));
175+
Ensure.NotEmpty(Token, nameof(Token));
189176
}
190177

191178
void ValidateClientAuthAccessRequestState()
192179
{
193-
if (AccessTokenUrl.IsNullOrBlank())
194-
throw new ArgumentException("You must specify an access token URL");
195-
196-
if (ConsumerKey.IsNullOrBlank())
197-
throw new ArgumentException("You must specify a consumer key");
198-
199-
if (ConsumerSecret.IsNullOrBlank())
200-
throw new ArgumentException("You must specify a consumer secret");
201-
202-
if (ClientUsername.IsNullOrBlank() || ClientPassword.IsNullOrBlank())
203-
throw new ArgumentException("You must specify user credentials");
180+
Ensure.NotEmpty(AccessTokenUrl, nameof(AccessTokenUrl));
181+
Ensure.NotEmpty(ConsumerKey, nameof(ConsumerKey));
182+
Ensure.NotEmpty(ConsumerSecret, nameof(ConsumerSecret));
183+
Ensure.NotEmpty(ClientUsername, nameof(ClientUsername));
204184
}
205185

206186
void ValidateProtectedResourceState()
207187
{
208-
if (ConsumerKey.IsNullOrBlank())
209-
throw new ArgumentException("You must specify a consumer key");
210-
211-
if (ConsumerSecret.IsNullOrBlank())
212-
throw new ArgumentException("You must specify a consumer secret");
188+
Ensure.NotEmpty(ConsumerKey, nameof(ConsumerKey));
189+
Ensure.NotEmpty(ConsumerSecret, nameof(ConsumerSecret));
213190
}
214191

215192
void AddAuthParameters(ICollection<WebPair> parameters, string timestamp, string nonce)
@@ -223,16 +200,16 @@ void AddAuthParameters(ICollection<WebPair> parameters, string timestamp, string
223200
new WebPair("oauth_version", Version ?? "1.0")
224201
};
225202

226-
if (!Token.IsNullOrBlank())
203+
if (!Token.IsEmpty())
227204
authParameters.Add(new WebPair("oauth_token", Token));
228205

229-
if (!CallbackUrl.IsNullOrBlank())
206+
if (!CallbackUrl.IsEmpty())
230207
authParameters.Add(new WebPair("oauth_callback", CallbackUrl));
231208

232-
if (!Verifier.IsNullOrBlank())
209+
if (!Verifier.IsEmpty())
233210
authParameters.Add(new WebPair("oauth_verifier", Verifier));
234211

235-
if (!SessionHandle.IsNullOrBlank())
212+
if (!SessionHandle.IsEmpty())
236213
authParameters.Add(new WebPair("oauth_session_handle", SessionHandle));
237214

238215
foreach (var authParameter in authParameters)

src/RestSharp/Extensions/MiscExtensions.cs

Lines changed: 2 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414

1515
using System;
1616
using System.IO;
17+
using System.Linq;
1718
using System.Text;
19+
using RestSharp.Authenticators.OAuth.Extensions;
1820

1921
namespace RestSharp.Extensions
2022
{
@@ -72,40 +74,5 @@ public static void CopyTo(this Stream input, Stream output)
7274
}
7375
}
7476

75-
/// <summary>
76-
/// Converts a byte array to a string, using its byte order mark to convert it to the right encoding.
77-
/// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx
78-
/// </summary>
79-
/// <param name="buffer">An array of bytes to convert</param>
80-
/// <param name="encoding">Content encoding. Will fallback to UTF8 if not a valid encoding.</param>
81-
/// <returns>The byte as a string.</returns>
82-
[Obsolete("This method will be removed soon. If you use it, please copy the code to your project.")]
83-
public static string AsString(this byte[] buffer, string encoding)
84-
{
85-
var enc = Encoding.UTF8;
86-
87-
try
88-
{
89-
if (!string.IsNullOrEmpty(encoding))
90-
enc = Encoding.GetEncoding(encoding);
91-
}
92-
catch (Exception)
93-
{
94-
// Use UTF8 as the default
95-
}
96-
97-
return AsString(buffer, enc);
98-
}
99-
100-
/// <summary>
101-
/// Converts a byte array to a string, using its byte order mark to convert it to the right encoding.
102-
/// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx
103-
/// </summary>
104-
/// <param name="buffer">An array of bytes to convert</param>
105-
/// <returns>The byte as a string using UTF8.</returns>
106-
[Obsolete("This method will be removed soon. If you use it, please copy the code to your project.")]
107-
public static string AsString(this byte[] buffer) => AsString(buffer, Encoding.UTF8);
108-
109-
static string AsString(byte[] buffer, Encoding encoding) => buffer == null ? "" : encoding.GetString(buffer, 0, buffer.Length);
11077
}
11178
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Copyright © 2009-2020 John Sheehan, Andrew Young, Alexey Zimarev and RestSharp community
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
//
15+
16+
using System;
17+
using System.Collections.Generic;
18+
using System.Text;
19+
20+
namespace RestSharp.Extensions
21+
{
22+
public static class StringEncodingExtensions
23+
{
24+
static readonly Dictionary<string, Encoding> Encodings = new Dictionary<string, Encoding>();
25+
26+
static StringEncodingExtensions()
27+
{
28+
var encodings = Encoding.GetEncodings();
29+
30+
foreach (var encoding in encodings)
31+
{
32+
Encodings[encoding.Name] = encoding.GetEncoding();
33+
}
34+
}
35+
36+
/// <summary>
37+
/// Converts a byte array to a string, using its byte order mark to convert it to the right encoding.
38+
/// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx
39+
/// </summary>
40+
/// <param name="buffer">An array of bytes to convert</param>
41+
/// <param name="encoding">Content encoding. Will fallback to UTF8 if not a valid encoding.</param>
42+
/// <returns>The byte as a string.</returns>
43+
[Obsolete("This method will be removed soon. If you use it, please copy the code to your project.")]
44+
public static string AsString(this byte[] buffer, string? encoding)
45+
{
46+
var enc = encoding.IsEmpty() ? Encoding.UTF8 : Encodings.TryGetValue(encoding!, out var e) ? e : Encoding.UTF8;
47+
48+
return AsString(buffer, enc);
49+
}
50+
51+
/// <summary>
52+
/// Converts a byte array to a string, using its byte order mark to convert it to the right encoding.
53+
/// http://www.shrinkrays.net/code-snippets/csharp/an-extension-method-for-converting-a-byte-array-to-a-string.aspx
54+
/// </summary>
55+
/// <param name="buffer">An array of bytes to convert</param>
56+
/// <returns>The byte as a string using UTF8.</returns>
57+
[Obsolete("This method will be removed soon. If you use it, please copy the code to your project.")]
58+
public static string AsString(this byte[] buffer) => AsString(buffer, Encoding.UTF8);
59+
60+
static string AsString(byte[] buffer, Encoding encoding) => buffer == null ? "" : encoding.GetString(buffer, 0, buffer.Length);
61+
}
62+
}

src/RestSharp/Extensions/StringExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ public static string AddSpaces(this string pascalCasedWord)
294294
" "
295295
);
296296

297-
internal static bool IsEmpty(this string value) => string.IsNullOrWhiteSpace(value);
297+
internal static bool IsEmpty(this string? value) => string.IsNullOrWhiteSpace(value);
298298

299299
internal static bool IsNotEmpty(this string value) => !string.IsNullOrWhiteSpace(value);
300300

src/RestSharp/RestSharp.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
<ItemGroup>
1111
<Reference Include="System.Web" Condition="'$(TargetFramework)' == 'net452'" />
1212
</ItemGroup>
13+
<ItemGroup>
14+
<None Remove="RestSharp.csproj.DotSettings" />
15+
</ItemGroup>
1316

1417
<Target DependsOnTargets="ResolveReferences" Name="CopyProjectReferencesToPackage">
1518
<ItemGroup>

test/RestSharp.Tests/StringExtensionsTests.cs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Globalization;
33
using System.Text;
4+
using FluentAssertions;
45
using NUnit.Framework;
56
using RestSharp.Extensions;
67

@@ -13,9 +14,7 @@ public void UrlEncode_Throws_ArgumentNullException_For_Null_Input()
1314
{
1415
const string nullString = null;
1516

16-
Assert.Throws<ArgumentNullException>(
17-
delegate { nullString.UrlEncode(); }
18-
);
17+
Assert.Throws<ArgumentNullException>(() => nullString.UrlEncode());
1918
}
2019

2120
[Test]
@@ -66,5 +65,25 @@ public void ToPascalCase(string start, bool removeUnderscores, string finish)
6665

6766
Assert.AreEqual(finish, result);
6867
}
68+
69+
[Test]
70+
public void Does_not_throw_on_invalid_encoding()
71+
{
72+
const string value = "SomeValue";
73+
var bytes = Encoding.UTF8.GetBytes(value);
74+
75+
var decoded = bytes.AsString("blah");
76+
decoded.Should().Be(value);
77+
}
78+
79+
[Test]
80+
public void Does_not_throw_on_missing_encoding()
81+
{
82+
const string value = "SomeValue";
83+
var bytes = Encoding.UTF8.GetBytes(value);
84+
85+
var decoded = bytes.AsString(null);
86+
decoded.Should().Be(value);
87+
}
6988
}
7089
}

0 commit comments

Comments
 (0)