Skip to content

Commit

Permalink
Fix string usage problems reported by analyzers (#5050)
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma authored Nov 23, 2024
1 parent 5a0073a commit 5ef193c
Show file tree
Hide file tree
Showing 34 changed files with 112 additions and 85 deletions.
13 changes: 1 addition & 12 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -72,32 +72,21 @@
[IDE0290] Use primary constructor
[IDE0330] Use 'System.Threading.Lock'
[CA1200] Avoid using cref tags with a prefix
[CA1304] The behavior of 'string.ToUpper()' could vary based on the current user's locale settings
[CA1305] The behavior of 'int.ToString()' could vary based on the current user's locale settings
[CA1310] The behavior of 'string.StartsWith(string)' could vary based on the current user's locale settings
[CA1311] The behavior of 'string.StartsWith(string)' could vary based on the current user's locale settings
[CA1507] Use nameof in place of string literal
[CA1510] Use 'ArgumentNullException.ThrowIfNull' instead of explicitly throwing a new exception instance
[CA1514] 'System.ReadOnlySpan<char>.Slice(int, int)' uses a redundant length calculation that can be removed
[CA1710] Rename to end in either 'Dictionary' or 'Collection'
[CA1716] rename parameter property so that it no longer conflicts with the reserved language keyword
[CA1720] Identifier 'xxx' contains type name
[CA1725] Overriden parameter name mismatch
[CA1834] Use 'StringBuilder.Append(char)' instead of 'StringBuilder.Append(string)' when the input is a constant unit string
[CA1845] Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
[CA1847] Use 'string.Contains(char)' instead of 'string.Contains(string)' - needs polyfill
[CA1861] Prefer 'static readonly' fields over constant array arguments
[CA1862] Prefer using 'string.Equals(string, StringComparison)' to perform a case-insensitive comparison
[CA1865] Use 'string.StartsWith(char)' instead of 'string.StartsWith(string)' - needs polyfill
[CA1866] Use 'string.StartsWith(char)' instead of 'string.StartsWith(string)' - needs polyfill
[CA1870] Use a cached 'SearchValues' instance for improved searching performance
[CA2249] Use 'string.Contains' instead of 'string.IndexOf' to improve readability - needs polyfill
[CA2263] Prefer the generic overload 'System.Enum.GetValues<TEnum>()'
[SYSLIB0012] 'Assembly.CodeBase' is obsolete
-->
<NoWarn>$(NoWarn);IDE0005;IDE0008;IDE0017;IDE0021;IDE0022;IDE0025;IDE0027;IDE0029;IDE0032;IDE0039;IDE0045;IDE0046;IDE0055;IDE0056;IDE0057;IDE0060;IDE0061;IDE0090;IDE0130;IDE0160;IDE0200;IDE0270;IDE0290;IDE0330</NoWarn>
<NoWarn>$(NoWarn);CA1200;CA1304;CA1305;CA1310;CA1311;CA1507;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1834;CA1845;CA1847;CA1861;CA1862;CA1865;CA1866;CA1870;CA2249;CA2263;SYSLIB0012</NoWarn>
<NoWarn>$(NoWarn);CA1200;CA1510;CA1514;CA1710;CA1716;CA1720;CA1725;CA1845;CA1861;CA1870;CA2263;SYSLIB0012</NoWarn>
</PropertyGroup>

</Project>
5 changes: 3 additions & 2 deletions src/NSwag.Annotations/ResponseTypeAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

using System.Globalization;
using System.Net;

namespace NSwag.Annotations
Expand Down Expand Up @@ -37,7 +38,7 @@ public ResponseTypeAttribute(string httpStatusCode, Type responseType)
/// <param name="responseType">The JSON result type of the MVC or Web API action method.</param>
public ResponseTypeAttribute(int httpStatusCode, Type responseType)
{
HttpStatusCode = httpStatusCode.ToString();
HttpStatusCode = httpStatusCode.ToString(CultureInfo.InvariantCulture);
ResponseType = responseType;
}

Expand All @@ -46,7 +47,7 @@ public ResponseTypeAttribute(int httpStatusCode, Type responseType)
/// <param name="responseType">The JSON result type of the MVC or Web API action method.</param>
public ResponseTypeAttribute(HttpStatusCode httpStatusCode, Type responseType)
{
HttpStatusCode = ((int)httpStatusCode).ToString();
HttpStatusCode = ((int)httpStatusCode).ToString(CultureInfo.InvariantCulture);
ResponseType = responseType;
}

Expand Down
5 changes: 3 additions & 2 deletions src/NSwag.Annotations/SwaggerResponseAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

using System.Globalization;
using System.Net;

namespace NSwag.Annotations
Expand Down Expand Up @@ -37,7 +38,7 @@ public SwaggerResponseAttribute(string httpStatusCode, Type responseType)
/// <param name="responseType">The JSON result type of the MVC or Web API action method.</param>
public SwaggerResponseAttribute(int httpStatusCode, Type responseType)
{
StatusCode = httpStatusCode.ToString();
StatusCode = httpStatusCode.ToString(CultureInfo.InvariantCulture);
Type = responseType;
}

Expand All @@ -46,7 +47,7 @@ public SwaggerResponseAttribute(int httpStatusCode, Type responseType)
/// <param name="responseType">The JSON result type of the MVC or Web API action method.</param>
public SwaggerResponseAttribute(HttpStatusCode httpStatusCode, Type responseType)
{
StatusCode = ((int)httpStatusCode).ToString();
StatusCode = ((int)httpStatusCode).ToString(CultureInfo.InvariantCulture);
Type = responseType;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class OpenApiDocumentMiddleware : OwinMiddleware
public OpenApiDocumentMiddleware(OwinMiddleware next, string path, IEnumerable<Type> controllerTypes, SwaggerSettings<WebApiOpenApiDocumentGeneratorSettings> settings)
: base(next)
{
_path = path.StartsWith("/") ? path : '/' + path;
_path = path.StartsWith('/') ? path : '/' + path;
_controllerTypes = controllerTypes;
_settings = settings;
}
Expand Down
1 change: 1 addition & 0 deletions src/NSwag.AspNet.Owin/NSwag.AspNet.Owin.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<Compile Include="..\NSwag.AspNetCore\SwaggerSettings.cs" Link="SwaggerSettings.cs" />
<Compile Include="..\NSwag.AspNetCore\SwaggerUiSettings.cs" Link="SwaggerUiSettings.cs" />
<Compile Include="..\NSwag.AspNetCore\SwaggerUiSettingsBase.cs" Link="SwaggerUiSettingsBase.cs" />
<Compile Include="..\NSwag.Core\Polyfills.cs" Link="Polyfills.cs" />
</ItemGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.AspNetCore/Middlewares/OpenApiDocumentMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public OpenApiDocumentMiddleware(RequestDelegate nextDelegate, IServiceProvider
_nextDelegate = nextDelegate;

_documentName = documentName;
_path = path.StartsWith("/") ? path : '/' + path;
_path = path.StartsWith('/') ? path : '/' + path;

_apiDescriptionGroupCollectionProvider = serviceProvider.GetService<IApiDescriptionGroupCollectionProvider>() ??
throw new InvalidOperationException("API Explorer not registered in DI.");
Expand All @@ -58,7 +58,7 @@ public async Task Invoke(HttpContext context)
{
var schemaJson = await GetDocumentAsync(context);
context.Response.StatusCode = 200;
context.Response.Headers["Content-Type"] = _path.IndexOf(".yaml", StringComparison.OrdinalIgnoreCase) >= 0 ?
context.Response.Headers["Content-Type"] = _path.Contains(".yaml", StringComparison.OrdinalIgnoreCase) ?
"application/yaml; charset=utf-8" :
"application/json; charset=utf-8";

Expand Down Expand Up @@ -99,7 +99,7 @@ protected virtual async Task<string> GetDocumentAsync(HttpContext context)
try
{
var openApiDocument = await GenerateDocumentAsync(context);
var data = _path.IndexOf(".yaml", StringComparison.OrdinalIgnoreCase) >= 0 ?
var data = _path.Contains(".yaml", StringComparison.OrdinalIgnoreCase) ?
OpenApiYamlDocument.ToYaml(openApiDocument) :
openApiDocument.ToJson();

Expand Down
4 changes: 4 additions & 0 deletions src/NSwag.AspNetCore/NSwag.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@
<ProjectReference Include="..\NSwag.Generation.AspNetCore\NSwag.Generation.AspNetCore.csproj" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\NSwag.Core\Polyfills.cs" Link="Polyfills.cs" />
</ItemGroup>

<Target Name="PopulateNuspec">
<PropertyGroup>
<NuspecProperties>
Expand Down
1 change: 1 addition & 0 deletions src/NSwag.AspNetCore/SwaggerUiSettingsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//-----------------------------------------------------------------------

#pragma warning disable IDE0005
#pragma warning disable CA1305

using NSwag.Generation;
using Newtonsoft.Json;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ public CSharpParameterModel(
}

/// <summary>Gets a value indicating whether the type is a Nullable&lt;&gt;.</summary>
public bool IsSystemNullable => Type.EndsWith("?");
public bool IsSystemNullable => Type.EndsWith('?');

/// <summary>Gets the type of the parameter when used in a controller interface where we can set default values before calling.</summary>
public string TypeInControllerInterface => HasDefault ? Type.EndsWith("?") ? Type.Substring(0, Type.Length - 1) : Type : Type;
public string TypeInControllerInterface => HasDefault ? Type.EndsWith('?') ? Type.Substring(0, Type.Length - 1) : Type : Type;

/// <summary>Gets a value indicating whether the parameter name is a valid CSharp identifier.</summary>
public bool IsValidIdentifier => Name.Equals(VariableName, StringComparison.OrdinalIgnoreCase);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

<ItemGroup>
<EmbeddedResource Include="Templates\*.liquid" />
<Compile Include="..\NSwag.Core\Polyfills.cs" Link="Polyfills.cs" />
</ItemGroup>

<ItemGroup>
Expand All @@ -15,4 +16,5 @@
<ItemGroup>
<PackageReference Include="NJsonSchema.CodeGeneration.CSharp" Version="11.1.0" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion src/NSwag.CodeGeneration/ClientGeneratorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ private List<TOperationModel> GetOperations(OpenApiDocument document)
operationName = operationName.Replace(".", "_");
}

if (operationName.EndsWith("Async"))
if (operationName.EndsWith("Async", StringComparison.Ordinal))
{
operationName = operationName.Substring(0, operationName.Length - "Async".Length);
}
Expand Down
2 changes: 1 addition & 1 deletion src/NSwag.CodeGeneration/Models/OperationModelBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ public TParameterModel ContentParameter
public IEnumerable<TParameterModel> HeaderParameters => Parameters.Where(p => p.Kind == OpenApiParameterKind.Header);

/// <summary>Gets or sets a value indicating whether the accept header is defined in a parameter.</summary>
public bool HasAcceptHeaderParameterParameter => HeaderParameters.Any(p => p.Name.ToLowerInvariant() == "accept");
public bool HasAcceptHeaderParameterParameter => HeaderParameters.Any(p => p.Name.Equals("accept", StringComparison.OrdinalIgnoreCase));

/// <summary>Gets a value indicating whether the operation has form parameters.</summary>
public bool HasFormParameters => Parameters.Any(p => p.Kind == OpenApiParameterKind.FormData);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class ExecuteDocumentCommand : IConsoleCommand
public async Task<object> RunAsync(CommandLineProcessor processor, IConsoleHost host)
{
// input can be nix-like file path starting with /
if (!string.IsNullOrEmpty(Input) && (!Input.StartsWith("/") || File.Exists(Input) || Input.EndsWith("nswag.json")) && !Input.StartsWith("-"))
if (!string.IsNullOrEmpty(Input) && (!Input.StartsWith('/') || File.Exists(Input) || Input.EndsWith("nswag.json", StringComparison.OrdinalIgnoreCase)) && !Input.StartsWith('-'))
{
await ExecuteDocumentAsync(host, Input);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ public override async Task<object> RunAsync(CommandLineProcessor processor, ICon
}

if (projectMetadata.TargetFrameworkIdentifier == ".NETCoreApp" ||
projectMetadata.TargetFrameworkIdentifier.StartsWith("net"))
projectMetadata.TargetFrameworkIdentifier.StartsWith("net", StringComparison.Ordinal))
{
executable = "dotnet";
args.Add("exec");
Expand Down
10 changes: 5 additions & 5 deletions src/NSwag.Commands/Commands/Generation/AspNetCore/Exe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,17 @@ private static string ToArguments(IReadOnlyList<string> args)
var argument = args[i];
if (i != 0)
{
builder.Append(" ");
builder.Append(' ');
}

if (argument.IndexOf(' ') == -1)
if (!argument.Contains(' '))
{
builder.Append(args[i]);

continue;
}

builder.Append("\"");
builder.Append('"');

var pendingBackslashs = 0;
for (var j = 0; j < argument.Length; j++)
Expand All @@ -113,7 +113,7 @@ private static string ToArguments(IReadOnlyList<string> args)
{
if (pendingBackslashs == 1)
{
builder.Append("\\");
builder.Append('\\');
}
else
{
Expand All @@ -133,7 +133,7 @@ private static string ToArguments(IReadOnlyList<string> args)
builder.Append('\\', pendingBackslashs * 2);
}

builder.Append("\"");
builder.Append('"');
}

return builder.ToString();
Expand Down
6 changes: 3 additions & 3 deletions src/NSwag.Commands/Commands/OutputCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ protected static Task<OpenApiDocument> ReadSwaggerDocumentAsync(string input)
{
if (!IsJson(input) && !IsYaml(input))
{
if (input.StartsWith("http://") || input.StartsWith("https://"))
if (input.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || input.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
if (input.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase) ||
input.EndsWith(".yml", StringComparison.OrdinalIgnoreCase))
Expand Down Expand Up @@ -67,12 +67,12 @@ protected static Task<OpenApiDocument> ReadSwaggerDocumentAsync(string input)

protected static bool IsJson(string data)
{
return data.StartsWith("{");
return data.StartsWith('{');
}

protected static bool IsYaml(string data)
{
return !IsJson(data) && data.Contains("\n");
return !IsJson(data) && data.Contains('\n');
}

protected Task<bool> TryWriteFileOutputAsync(IConsoleHost host, Func<string> generator)
Expand Down
4 changes: 4 additions & 0 deletions src/NSwag.Commands/NSwag.Commands.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,8 @@
<ProjectReference Include="..\NSwag.Generation.AspNetCore\NSwag.Generation.AspNetCore.csproj" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\NSwag.Core\Polyfills.cs" Link="Polyfills.cs" />
</ItemGroup>

</Project>
10 changes: 5 additions & 5 deletions src/NSwag.Commands/NSwagDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public async Task<OpenApiDocumentExecutionResult> ExecuteCommandLineAsync(bool r
/// <returns>The absolute path.</returns>
protected override string ConvertToAbsolutePath(string pathToConvert)
{
if (!string.IsNullOrEmpty(pathToConvert) && !System.IO.Path.IsPathRooted(pathToConvert) && !pathToConvert.Contains("%"))
if (!string.IsNullOrEmpty(pathToConvert) && !System.IO.Path.IsPathRooted(pathToConvert) && !pathToConvert.Contains('%'))
{
return PathUtilities.MakeAbsolutePath(pathToConvert, GetDocumentDirectory());
}
Expand All @@ -151,7 +151,7 @@ protected override string ConvertToAbsolutePath(string pathToConvert)
/// <returns>The relative path.</returns>
protected override string ConvertToRelativePath(string pathToConvert)
{
if (!string.IsNullOrEmpty(pathToConvert) && !pathToConvert.Contains("C:\\Program Files\\") && !pathToConvert.Contains("%"))
if (!string.IsNullOrEmpty(pathToConvert) && !pathToConvert.Contains("C:\\Program Files\\") && !pathToConvert.Contains('%'))
{
return PathUtilities.MakeRelativePath(pathToConvert, GetDocumentDirectory())?.Replace("\\", "/");
}
Expand Down Expand Up @@ -192,17 +192,17 @@ private async Task<string> StartCommandLineProcessAsync(string command)

if (process.ExitCode != 0)
{
var errorStart = output.IndexOf("...");
var errorStart = output.IndexOf("...", StringComparison.Ordinal);
if (errorStart < 0)
{
errorStart = Regex.Match(output, "\n[^\n\r]*?Exception: .*", RegexOptions.Singleline)?.Index ?? -1;
}

var error = errorStart > 0 ? output.Substring(errorStart + 4) : output;
var stackTraceStart = error.IndexOf("Server stack trace: ");
var stackTraceStart = error.IndexOf("Server stack trace: ", StringComparison.Ordinal);
if (stackTraceStart < 0)
{
stackTraceStart = error.IndexOf(" at ");
stackTraceStart = error.IndexOf(" at ", StringComparison.Ordinal);
}

var message = stackTraceStart > 0 ? error.Substring(0, stackTraceStart) : error;
Expand Down
12 changes: 8 additions & 4 deletions src/NSwag.Commands/NSwagDocumentBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------

#pragma warning disable CA1507

using System.ComponentModel;
using System.Reflection;
using System.Runtime.CompilerServices;
Expand Down Expand Up @@ -308,7 +310,8 @@ private void ConvertToAbsolutePaths()
{
if (SwaggerGenerators.FromDocumentCommand != null)
{
if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://") && !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://"))
if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
&& !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
SwaggerGenerators.FromDocumentCommand.Url = ConvertToAbsolutePath(SwaggerGenerators.FromDocumentCommand.Url);
}
Expand Down Expand Up @@ -372,7 +375,8 @@ private void ConvertToRelativePaths()
{
if (SwaggerGenerators.FromDocumentCommand != null)
{
if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://") && !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://"))
if (!SwaggerGenerators.FromDocumentCommand.Url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
&& !SwaggerGenerators.FromDocumentCommand.Url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
SwaggerGenerators.FromDocumentCommand.Url = ConvertToRelativePath(SwaggerGenerators.FromDocumentCommand.Url);
}
Expand Down Expand Up @@ -436,7 +440,7 @@ private static string TransformLegacyDocument(string data, out bool saveFile)
saveFile = false;

// Swagger to OpenApi rename
if (data.Contains("\"typeScriptVersion\":") && !data.ToLowerInvariant().Contains("ExceptionClass".ToLowerInvariant()))
if (data.Contains("\"typeScriptVersion\":") && !data.Contains("ExceptionClass", StringComparison.OrdinalIgnoreCase))
{
data = data.Replace("\"typeScriptVersion\":", "\"exceptionClass\": \"SwaggerException\", \"typeScriptVersion\":");
saveFile = true;
Expand Down Expand Up @@ -509,7 +513,7 @@ private static string TransformLegacyDocument(string data, out bool saveFile)
saveFile = true;
}

if (data.Contains("\"noBuild\":") && !data.ToLowerInvariant().Contains("RequireParametersWithoutDefault".ToLowerInvariant()))
if (data.Contains("\"noBuild\":") && !data.Contains("RequireParametersWithoutDefault", StringComparison.OrdinalIgnoreCase))
{
data = data.Replace("\"noBuild\":", "\"requireParametersWithoutDefault\": true, \"noBuild\":");
saveFile = true;
Expand Down
Loading

0 comments on commit 5ef193c

Please sign in to comment.