Skip to content

Commit 8dd3142

Browse files
committed
Updated to .NET analyzers and fixed warnings
1 parent 7659f83 commit 8dd3142

19 files changed

+80
-101
lines changed

.editorconfig

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ dotnet_diagnostic.CA1034.severity = none
1414
dotnet_diagnostic.CA1054.severity = none
1515
dotnet_diagnostic.CA2227.severity = none
1616
dotnet_diagnostic.CA1308.severity = none
17+
dotnet_diagnostic.CA1002.severity = none
18+
# TODO: Enable for next major version, EventArgs breaking change:
19+
dotnet_diagnostic.CA1003.severity = none
20+
#
1721
# Sort using and Import directives with System.* appearing first
1822
dotnet_sort_system_directives_first = true
1923
dotnet_style_require_accessibility_modifiers = always:warning

SpotifyAPI.Web.Auth/AssemblyInfo.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
using System;
2+
using System.Runtime.CompilerServices;
3+
4+
[assembly: InternalsVisibleTo("SpotifyAPI.Web.Tests")]
5+
[assembly: CLSCompliant(true)]

SpotifyAPI.Web.Tests/Http/NetHTTPClientTest.cs

Lines changed: 0 additions & 20 deletions
This file was deleted.

SpotifyAPI.Web.Tests/UtilTests/URIExtensionTest.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public class URIExtensionTest
1111
public void ApplyParameters_WithoutExistingParameters()
1212
{
1313
var expected = "http://google.com/?hello=world&nice=day";
14-
Uri uri = new Uri("http://google.com/");
14+
var uri = new Uri("http://google.com/");
1515

1616
var parameters = new Dictionary<string, string>
1717
{
@@ -25,7 +25,7 @@ public void ApplyParameters_WithoutExistingParameters()
2525
public void ApplyParameters_WithExistingParameters()
2626
{
2727
var expected = "http://google.com/?existing=paramter&hello=world&nice=day";
28-
Uri uri = new Uri("http://google.com/?existing=paramter");
28+
var uri = new Uri("http://google.com/?existing=paramter");
2929

3030
var parameters = new Dictionary<string, string>
3131
{
@@ -39,7 +39,7 @@ public void ApplyParameters_WithExistingParameters()
3939
public void ApplyParameters_HandlesEscape()
4040
{
4141
var expected = "http://google.com/?existing=paramter&hello=%26world++";
42-
Uri uri = new Uri("http://google.com/?existing=paramter");
42+
var uri = new Uri("http://google.com/?existing=paramter");
4343

4444
var parameters = new Dictionary<string, string>
4545
{

SpotifyAPI.Web/Assembly.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System;
12
using System.Runtime.CompilerServices;
23

34
[assembly: InternalsVisibleTo("SpotifyAPI.Web.Tests")]
5+
[assembly: CLSCompliant(true)]

SpotifyAPI.Web/Clients/APIClient.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ namespace SpotifyAPI.Web
44
{
55
public abstract class APIClient
66
{
7-
public APIClient(IAPIConnector apiConnector)
7+
protected APIClient(IAPIConnector apiConnector)
88
{
99
Ensure.ArgumentNotNull(apiConnector, nameof(apiConnector));
1010

SpotifyAPI.Web/Clients/PlaylistsClient.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,12 +49,12 @@ public Task<FullPlaylist> Create(string userId, PlaylistCreateRequest request)
4949
return API.Post<FullPlaylist>(URLs.UserPlaylists(userId), null, request.BuildBodyParams());
5050
}
5151

52-
public async Task<bool> UploadCover(string playlistId, string base64Jpg)
52+
public async Task<bool> UploadCover(string playlistId, string base64JpgData)
5353
{
5454
Ensure.ArgumentNotNullOrEmptyString(playlistId, nameof(playlistId));
55-
Ensure.ArgumentNotNullOrEmptyString(base64Jpg, nameof(base64Jpg));
55+
Ensure.ArgumentNotNullOrEmptyString(base64JpgData, nameof(base64JpgData));
5656

57-
var statusCode = await API.PutRaw(URLs.PlaylistImages(playlistId), null, base64Jpg).ConfigureAwait(false);
57+
var statusCode = await API.PutRaw(URLs.PlaylistImages(playlistId), null, base64JpgData).ConfigureAwait(false);
5858
return statusCode == HttpStatusCode.Accepted;
5959
}
6060

SpotifyAPI.Web/Clients/SpotifyClient.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@ public SpotifyClient(SpotifyClientConfig config)
2424
Ensure.ArgumentNotNull(config, nameof(config));
2525
if (config.Authenticator == null)
2626
{
27-
throw new NullReferenceException("Authenticator in config is null. Please supply it via `WithAuthenticator` or `WithToken`");
27+
#pragma warning disable CA2208
28+
throw new ArgumentNullException("Authenticator in config is null. Please supply it via `WithAuthenticator` or `WithToken`");
29+
#pragma warning restore CA2208
2830
}
2931

3032
_apiConnector = new APIConnector(

SpotifyAPI.Web/Http/APIConnector.cs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -279,15 +279,13 @@ private static void ProcessErrors(IResponse response)
279279
return;
280280
}
281281

282-
switch (response.StatusCode)
282+
throw response.StatusCode switch
283283
{
284-
case HttpStatusCode.Unauthorized:
285-
throw new APIUnauthorizedException(response);
286-
case (HttpStatusCode)429: // TODO: Remove hack once .netstandard 2.0 is not supported
287-
throw new APITooManyRequestsException(response);
288-
default:
289-
throw new APIException(response);
290-
}
284+
HttpStatusCode.Unauthorized => new APIUnauthorizedException(response),
285+
// TODO: Remove hack once .netstandard 2.0 is not supported
286+
(HttpStatusCode)429 => new APITooManyRequestsException(response),
287+
_ => new APIException(response),
288+
};
291289
}
292290
}
293291
}

SpotifyAPI.Web/Http/NetHttpClient.cs

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -35,34 +35,30 @@ public async Task<IResponse> DoRequest(IRequest request)
3535
{
3636
Ensure.ArgumentNotNull(request, nameof(request));
3737

38-
using (HttpRequestMessage requestMsg = BuildRequestMessage(request))
39-
{
40-
var responseMsg = await _httpClient
41-
.SendAsync(requestMsg, HttpCompletionOption.ResponseContentRead)
42-
.ConfigureAwait(false);
38+
using HttpRequestMessage requestMsg = BuildRequestMessage(request);
39+
var responseMsg = await _httpClient
40+
.SendAsync(requestMsg, HttpCompletionOption.ResponseContentRead)
41+
.ConfigureAwait(false);
4342

44-
return await BuildResponse(responseMsg).ConfigureAwait(false);
45-
}
43+
return await BuildResponse(responseMsg).ConfigureAwait(false);
4644
}
4745

4846
private static async Task<IResponse> BuildResponse(HttpResponseMessage responseMsg)
4947
{
5048
Ensure.ArgumentNotNull(responseMsg, nameof(responseMsg));
5149

5250
// We only support text stuff for now
53-
using (var content = responseMsg.Content)
51+
using var content = responseMsg.Content;
52+
var headers = responseMsg.Headers.ToDictionary(header => header.Key, header => header.Value.First());
53+
var body = await responseMsg.Content.ReadAsStringAsync().ConfigureAwait(false);
54+
var contentType = content.Headers?.ContentType?.MediaType;
55+
56+
return new Response(headers)
5457
{
55-
var headers = responseMsg.Headers.ToDictionary(header => header.Key, header => header.Value.First());
56-
var body = await responseMsg.Content.ReadAsStringAsync().ConfigureAwait(false);
57-
var contentType = content.Headers?.ContentType?.MediaType;
58-
59-
return new Response(headers)
60-
{
61-
ContentType = contentType,
62-
StatusCode = responseMsg.StatusCode,
63-
Body = body
64-
};
65-
}
58+
ContentType = contentType,
59+
StatusCode = responseMsg.StatusCode,
60+
Body = body
61+
};
6662
}
6763

6864
private static HttpRequestMessage BuildRequestMessage(IRequest request)

SpotifyAPI.Web/Http/SimpleConsoleHTTPLogger.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public void OnRequest(IRequest request)
1616
if (request.Parameters != null)
1717
{
1818
parameters = string.Join(",",
19-
request.Parameters?.Select(kv => kv.Key + "=" + kv.Value)?.ToArray() ?? Array.Empty<string>()
19+
request.Parameters.Select(kv => kv.Key + "=" + kv.Value)?.ToArray() ?? Array.Empty<string>()
2020
);
2121
}
2222

@@ -33,7 +33,7 @@ public void OnResponse(IResponse response)
3333
string? body = response.Body?.ToString()?.Replace("\n", "", StringComparison.InvariantCulture);
3434
#endif
3535

36-
body = body?.Substring(0, Math.Min(50, body?.Length ?? 0));
36+
body = body?.Substring(0, Math.Min(50, body.Length));
3737
Console.WriteLine("--> {0} {1} {2}\n", response.StatusCode, response.ContentType, body);
3838
}
3939
}

SpotifyAPI.Web/Models/Converters/PlayableItemConverter.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public class PlayableItemConverter : JsonConverter
3636
}
3737
else
3838
{
39-
throw new Exception($@"Received unkown playlist element type: {type}.
39+
throw new APIException($@"Received unkown playlist element type: {type}.
4040
If you're requesting a subset of available fields via the fields query paramter,
4141
make sure to include at least the type field. Often it's `items(track(type))` or `item(type)`");
4242
}

SpotifyAPI.Web/Models/Request/LoginRequest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public LoginRequest(Uri redirectUri, string clientId, ResponseType responseType)
2929

3030
public Uri ToUri()
3131
{
32-
StringBuilder builder = new StringBuilder(SpotifyUrls.Authorize.ToString());
32+
var builder = new StringBuilder(SpotifyUrls.Authorize.ToString());
3333
builder.Append($"?client_id={ClientId}");
3434
builder.Append($"&response_type={ResponseTypeParam.ToString().ToLower(CultureInfo.InvariantCulture)}");
3535
builder.Append($"&redirect_uri={HttpUtility.UrlEncode(RedirectUri.ToString())}");

SpotifyAPI.Web/Models/Request/RequestParams.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ namespace SpotifyAPI.Web
1111
public abstract class RequestParams
1212
{
1313
private static readonly ConcurrentDictionary<Type, List<(PropertyInfo, BodyParamAttribute)>> _bodyParamsCache =
14-
new ConcurrentDictionary<Type, List<(PropertyInfo, BodyParamAttribute)>>();
14+
new();
1515

1616
public JObject BuildBodyParams()
1717
{
@@ -59,7 +59,7 @@ private void AddBodyParam(JObject body, PropertyInfo prop, BodyParamAttribute at
5959
}
6060

6161
private static readonly ConcurrentDictionary<Type, List<(PropertyInfo, QueryParamAttribute)>> _queryParamsCache =
62-
new ConcurrentDictionary<Type, List<(PropertyInfo, QueryParamAttribute)>>();
62+
new();
6363

6464
public Dictionary<string, string> BuildQueryParams()
6565
{
@@ -146,7 +146,7 @@ private void AddQueryParam(Dictionary<string, string> queryParams, PropertyInfo
146146
}
147147
else
148148
{
149-
queryParams.Add(attribute.Key ?? prop.Name, value.ToString() ?? throw new Exception("ToString was null on a value"));
149+
queryParams.Add(attribute.Key ?? prop.Name, value.ToString() ?? throw new APIException("ToString returned null for query parameter"));
150150
}
151151
}
152152
}
@@ -156,7 +156,7 @@ protected virtual void AddCustomQueryParams(Dictionary<string, string> queryPara
156156
}
157157

158158
[AttributeUsage(AttributeTargets.Property)]
159-
public class QueryParamAttribute : Attribute
159+
public sealed class QueryParamAttribute : Attribute
160160
{
161161
public string Key { get; }
162162

@@ -167,7 +167,7 @@ public QueryParamAttribute(string key)
167167
}
168168

169169
[AttributeUsage(AttributeTargets.Property)]
170-
public class BodyParamAttribute : Attribute
170+
public sealed class BodyParamAttribute : Attribute
171171
{
172172
public string Key { get; }
173173

SpotifyAPI.Web/SpotifyAPI.Web.csproj

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@
3535
<PackageReference Include="Newtonsoft.Json" Version="12.0.3">
3636
<PrivateAssets>None</PrivateAssets>
3737
</PackageReference>
38-
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="3.3.2">
39-
<PrivateAssets>all</PrivateAssets>
40-
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
41-
</PackageReference>
4238
</ItemGroup>
39+
40+
<PropertyGroup>
41+
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
42+
</PropertyGroup>
4343
</Project>

SpotifyAPI.Web/SpotifyUrls.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ namespace SpotifyAPI.Web
33
{
44
public static class SpotifyUrls
55
{
6-
static private readonly URIParameterFormatProvider _provider = new URIParameterFormatProvider();
6+
static private readonly URIParameterFormatProvider _provider = new();
77

8-
public static readonly Uri APIV1 = new Uri("https://api.spotify.com/v1/");
8+
public static readonly Uri APIV1 = new("https://api.spotify.com/v1/");
99

10-
public static readonly Uri Authorize = new Uri("https://accounts.spotify.com/authorize");
10+
public static readonly Uri Authorize = new("https://accounts.spotify.com/authorize");
1111

12-
public static readonly Uri OAuthToken = new Uri("https://accounts.spotify.com/api/token");
12+
public static readonly Uri OAuthToken = new("https://accounts.spotify.com/api/token");
1313

1414
public static Uri Me() => EUri($"me");
1515

@@ -125,6 +125,6 @@ public static class SpotifyUrls
125125

126126
public static Uri LibraryShows() => EUri($"me/shows");
127127

128-
private static Uri EUri(FormattableString path) => new Uri(path.ToString(_provider), UriKind.Relative);
128+
private static Uri EUri(FormattableString path) => new(path.ToString(_provider), UriKind.Relative);
129129
}
130130
}

SpotifyAPI.Web/Util/Base64Util.cs

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -114,21 +114,17 @@ private static int GetArraySizeRequiredToDecode(int count)
114114

115115
private static int GetNumBase64PaddingCharsToAddForDecode(int inputLength)
116116
{
117-
switch (inputLength % 4)
117+
return (inputLength % 4) switch
118118
{
119-
case 0:
120-
return 0;
121-
case 2:
122-
return 2;
123-
case 3:
124-
return 1;
125-
default:
126-
throw new FormatException(
127-
string.Format(
128-
CultureInfo.CurrentCulture,
129-
WebEncoders_MalformedInput,
130-
inputLength));
131-
}
119+
0 => 0,
120+
2 => 2,
121+
3 => 1,
122+
_ => throw new FormatException(
123+
string.Format(
124+
CultureInfo.CurrentCulture,
125+
WebEncoders_MalformedInput,
126+
inputLength)),
127+
};
132128
}
133129
}
134130

SpotifyAPI.Web/Util/PKCEUtil.cs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -52,22 +52,18 @@ public static (string verifier, string challenge) GenerateCodes(string verifier)
5252

5353
private static string GenerateRandomURLSafeString(int length)
5454
{
55-
using (var rng = new RNGCryptoServiceProvider())
56-
{
57-
var bit_count = length * 6;
58-
var byte_count = (bit_count + 7) / 8; // rounded up
59-
var bytes = new byte[byte_count];
60-
rng.GetBytes(bytes);
61-
return Base64Util.UrlEncode(bytes);
62-
}
55+
using var rng = new RNGCryptoServiceProvider();
56+
var bit_count = length * 6;
57+
var byte_count = (bit_count + 7) / 8; // rounded up
58+
var bytes = new byte[byte_count];
59+
rng.GetBytes(bytes);
60+
return Base64Util.UrlEncode(bytes);
6361
}
6462

6563
private static byte[] ComputeSHA256(string value)
6664
{
67-
using (var hash = SHA256.Create())
68-
{
69-
return hash.ComputeHash(Encoding.UTF8.GetBytes(value));
70-
}
65+
using var hash = SHA256.Create();
66+
return hash.ComputeHash(Encoding.UTF8.GetBytes(value));
7167
}
7268
}
7369
}

SpotifyAPI.Web/Util/StringAttribute.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66
namespace SpotifyAPI.Web
77
{
88
[AttributeUsage(AttributeTargets.Field)]
9-
public class StringAttribute : Attribute
9+
public sealed class StringAttribute : Attribute
1010
{
1111
public StringAttribute(string value)
1212
{
1313
Value = value;
1414
}
1515

16-
public string Value { get; set; }
16+
public string Value { get; }
1717

1818
#if NETSTANDARD2_0
1919
public static bool GetValue(Type enumType, Enum enumValue, out string? result)

0 commit comments

Comments
 (0)