Fixing some analyzer warnings (#5617)

* Fixing some analyzer warnings

* review feedback

---------

Co-authored-by: Sipke Schoorstra <sipkeschoorstra@outlook.com>
This commit is contained in:
Marko Lahma 2024-07-05 16:14:28 +03:00 committed by GitHub
parent daac6b1542
commit 492d6fcd35
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
37 changed files with 73 additions and 73 deletions

View file

@ -137,7 +137,7 @@ public static class ObjectConverter
return Enum.ToObject(underlyingTargetType, value);
if (underlyingSourceType == typeof(double))
return Enum.ToObject(underlyingTargetType, Convert.ChangeType(value, typeof(int)));
return Enum.ToObject(underlyingTargetType, Convert.ChangeType(value, typeof(int), CultureInfo.InvariantCulture));
}
if (value is string s)
@ -178,7 +178,7 @@ public static class ObjectConverter
try
{
return Convert.ChangeType(value, underlyingTargetType);
return Convert.ChangeType(value, underlyingTargetType, CultureInfo.InvariantCulture);
}
catch (InvalidCastException)
{

View file

@ -4,4 +4,4 @@ using System.ComponentModel;
namespace System.Runtime.CompilerServices;
[EditorBrowsable(EditorBrowsableState.Never)]
internal class IsExternalInit{}
internal sealed class IsExternalInit;

View file

@ -8,5 +8,5 @@ public class GetActivityDescriptorOptionsRequest
/// <summary>
/// Object context use to pass custom information
/// </summary>
public object? Context { get; set; } = default;
public object? Context { get; set; }
}

View file

@ -81,5 +81,5 @@ public class WorkflowDefinition : LinkedEntity
/// <summary>
/// An option to use the workflow as a readonly workflow.
/// </summary>
public bool IsReadonly { get; set; } = false;
public bool IsReadonly { get; set; }
}

View file

@ -12,8 +12,9 @@ namespace Elsa.Api.Client.Resources.WorkflowInstances.Models;
/// <param name="Payload">The data associated with the bookmark.</param>
/// <param name="ActivityNodeId">The ID of the activity node associated with the bookmark.</param>
/// <param name="ActivityInstanceId">The ID of the activity instance associated with the bookmark.</param>
/// <param name="AutoBurn">Whether or not the bookmark should be automatically burned.</param>
/// <param name="AutoBurn">Whether the bookmark should be automatically burned.</param>
/// <param name="CallbackMethodName">The name of the method on the activity class to invoke when the bookmark is resumed.</param>
/// <param name="Metadata">The metadata associated with this bookmark.</param>
[PublicAPI]
public record Bookmark(
string Id,

View file

@ -2,7 +2,7 @@ using System.Text.Json.Serialization;
namespace Elsa.Api.Client.Resources.WorkflowInstances.Responses;
internal class BulkDeleteWorkflowInstancesResponse
internal sealed class BulkDeleteWorkflowInstancesResponse
{
[JsonPropertyName("deleted")] public int DeletedCount { get; }
}

View file

@ -37,7 +37,7 @@ public class ActivityNode
get
{
var ancestorIds = Ancestors().Reverse().Select(x => x.Activity.GetId()).ToList();
return ancestorIds.Any() ? $"{string.Join(":", ancestorIds)}:{Activity.GetId()}" : Activity.GetId();
return ancestorIds.Count > 0 ? $"{string.Join(":", ancestorIds)}:{Activity.GetId()}" : Activity.GetId();
}
}

View file

@ -8,5 +8,5 @@ public class LinkedEntity : VersionedEntity
/// <summary>
/// A list of links that with the possible actions used in the context of HATEOAS.
/// </summary>
public Link[]? Links { get; set; } = default;
public Link[]? Links { get; set; }
}

View file

@ -3,11 +3,9 @@ namespace Elsa.Api.Client.Shared.Models;
/// <summary>
/// Represents a generic paged list response that offers a unified format for returning paged list of things from API endpoints.
/// </summary>
/// <param name="Items">A page of items.</param>
/// <param name="TotalCount">The total number of items.</param>
/// <typeparam name="T">The type of the items.</typeparam>
public class PagedListResponse<T> : LinkedEntity
{
public ICollection<T> Items { get; set; }
public ICollection<T> Items { get; set; } = default!;
public long TotalCount { get; set; }
}

View file

@ -1,4 +1,5 @@
using System.ComponentModel;
using System.Globalization;
using System.Text.Json.Serialization;
using Elsa.Api.Client.Converters;
using JetBrains.Annotations;
@ -60,7 +61,7 @@ public struct VersionOptions
"Published" => Published,
"LatestOrPublished" => LatestOrPublished,
"LatestAndPublished" => LatestAndPublished,
_ => SpecificVersion(int.Parse(value))
_ => SpecificVersion(int.Parse(value, CultureInfo.InvariantCulture))
};
/// <summary>
@ -113,5 +114,5 @@ public struct VersionOptions
/// <summary>
/// Returns a simple string representation of this <see cref="VersionOptions"/>.
/// </summary>
public override string ToString() => AllVersions ? "AllVersions" : IsDraft ? "Draft" : IsLatest ? "Latest" : IsPublished ? "Published" : IsLatestOrPublished ? "LatestOrPublished" : IsLatestAndPublished ? "LatestAndPublished" : Version.ToString();
public override string ToString() => AllVersions ? "AllVersions" : IsDraft ? "Draft" : IsLatest ? "Latest" : IsPublished ? "Published" : IsLatestOrPublished ? "LatestOrPublished" : IsLatestAndPublished ? "LatestAndPublished" : Version.ToString(CultureInfo.InvariantCulture);
}

View file

@ -2,7 +2,9 @@ namespace Elsa.Api.Client.Shared.UIHints.CheckList;
public class CheckListItem
{
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public string Text { get; set; }
public string Value { get; set; }
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public bool IsChecked { get; set; }
}

View file

@ -50,12 +50,12 @@ public class DirectoryDropInCatalog : IDropInCatalog
}
}
private IEnumerable<string> ListPackages()
private string[] ListPackages()
{
return Directory.GetFiles(_directoryPath, "*.nupkg", SearchOption.AllDirectories);
}
private Assembly? LoadDropInAssembly(string path)
private static Assembly? LoadDropInAssembly(string path)
{
return !File.Exists(path) ? null : AssemblyLoader.LoadPath(path);
}

View file

@ -3,7 +3,7 @@ using System.Runtime.Loader;
namespace Elsa.DropIns.Contexts;
internal class DirectoryAssemblyLoadContext : AssemblyLoadContext
internal sealed class DirectoryAssemblyLoadContext : AssemblyLoadContext
{
private readonly AssemblyDependencyResolver _resolver;

View file

@ -4,7 +4,7 @@ using NuGet.Packaging;
namespace Elsa.DropIns.Contexts;
internal class NuGetPackageAssemblyLoadContext : AssemblyLoadContext
internal sealed class NuGetPackageAssemblyLoadContext : AssemblyLoadContext
{
private readonly Dictionary<string, Assembly> _loadedAssemblies = new Dictionary<string, Assembly>();
@ -12,7 +12,7 @@ internal class NuGetPackageAssemblyLoadContext : AssemblyLoadContext
{
var packageReader = new PackageArchiveReader(nugetPackagePath);
foreach (var dllFile in packageReader.GetFiles().Where(fileName => fileName.EndsWith(".dll")))
foreach (var dllFile in packageReader.GetFiles().Where(fileName => fileName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)))
{
using var dllStream = packageReader.GetStream(dllFile);
using var memoryStream = new MemoryStream();
@ -26,6 +26,6 @@ internal class NuGetPackageAssemblyLoadContext : AssemblyLoadContext
protected override Assembly? Load(AssemblyName assemblyName)
{
return _loadedAssemblies.TryGetValue(assemblyName.FullName, out var assembly) ? assembly : null;
return _loadedAssemblies.GetValueOrDefault(assemblyName.FullName);
}
}

View file

@ -4,13 +4,13 @@ namespace Elsa.Features.Attributes;
/// Specifies that the feature depends on another feature.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class DependsOn : Attribute
public class DependsOnAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="DependsOn"/> class.
/// Initializes a new instance of the <see cref="DependsOnAttribute"/> class.
/// </summary>
/// <param name="type">The type of the feature this feature depends on.</param>
public DependsOn(Type type)
public DependsOnAttribute(Type type)
{
Type = type;
}

View file

@ -23,10 +23,8 @@ public static class EnumerableTopologicalSortExtensions
private static void Visit<T>(T item, ISet<T> visited, ICollection<T> sorted, Func<T, IEnumerable<T>> dependencies, bool throwOnCycle)
{
if (!visited.Contains(item))
if (visited.Add(item))
{
visited.Add(item);
foreach (var dep in dependencies(item))
Visit(dep, visited, sorted, dependencies, throwOnCycle);

View file

@ -14,11 +14,11 @@ namespace Elsa.Features.Implementations;
/// <inheritdoc />
public class Module : IModule
{
private record HostedServiceDescriptor(int Order, Type Type);
private sealed record HostedServiceDescriptor(int Order, Type Type);
private IDictionary<Type, IFeature> _features = new Dictionary<Type, IFeature>();
private readonly ISet<IFeature> _configuredFeatures = new HashSet<IFeature>();
private readonly ICollection<HostedServiceDescriptor> _hostedServiceDescriptors = new List<HostedServiceDescriptor>();
private Dictionary<Type, IFeature> _features = new();
private readonly HashSet<IFeature> _configuredFeatures = new();
private readonly List<HostedServiceDescriptor> _hostedServiceDescriptors = new();
/// <summary>
/// Constructor.
@ -134,7 +134,7 @@ public class Module : IModule
let featureType = feature.GetType()
let dependencyOfAttributes = featureType.GetCustomAttributes<DependencyOfAttribute>().ToList()
let missingDependencies = dependencyOfAttributes.Where(x => !_features.ContainsKey(x.Type)).ToList()
where !missingDependencies.Any()
where missingDependencies.Count == 0
select feature;
}
@ -154,17 +154,17 @@ public class Module : IModule
return _features.TryGetValue(featureType, out var existingFeature) ? existingFeature : (IFeature)Activator.CreateInstance(featureType, this)!;
}
private ISet<Type> GetFeatureTypes()
private HashSet<Type> GetFeatureTypes()
{
var featureTypes = _features.Keys.ToHashSet();
var featureTypesWithDependencies = featureTypes.Concat(featureTypes.SelectMany(GetDependencyTypes)).ToHashSet();
return featureTypesWithDependencies.TSort(x => x.GetCustomAttributes<DependsOn>().Select(dependsOn => dependsOn.Type)).ToHashSet();
return featureTypesWithDependencies.TSort(x => x.GetCustomAttributes<DependsOnAttribute>().Select(dependsOn => dependsOn.Type)).ToHashSet();
}
// Recursively get dependency types.
private IEnumerable<Type> GetDependencyTypes(Type type)
{
var dependencies = type.GetCustomAttributes<DependsOn>().Select(dependsOn => dependsOn.Type).ToList();
var dependencies = type.GetCustomAttributes<DependsOnAttribute>().Select(dependsOn => dependsOn.Type).ToList();
return dependencies.Concat(dependencies.SelectMany(GetDependencyTypes));
}
}

View file

@ -6,7 +6,7 @@ namespace Elsa.Features.Services;
/// <inheritdoc />
public class InstalledFeatureRegistry : IInstalledFeatureRegistry
{
private readonly IDictionary<string, FeatureDescriptor> _descriptors = new Dictionary<string, FeatureDescriptor>();
private readonly Dictionary<string, FeatureDescriptor> _descriptors = new();
/// <inheritdoc />
public void Add(FeatureDescriptor descriptor) => _descriptors[descriptor.FullName] = descriptor;
@ -15,5 +15,5 @@ public class InstalledFeatureRegistry : IInstalledFeatureRegistry
public IEnumerable<FeatureDescriptor> List() => _descriptors.Values;
/// <inheritdoc />
public FeatureDescriptor? Find(string fullName) => _descriptors.TryGetValue(fullName, out var descriptor) ? descriptor : null;
public FeatureDescriptor? Find(string fullName) => _descriptors.GetValueOrDefault(fullName);
}

View file

@ -37,5 +37,5 @@ public interface ICommandSender
/// <param name="command">The command to send.</param>
/// <param name="strategy">The command strategy to use.</param>
/// <param name="cancellationToken">The cancellation token.</param>
Task SendAsync(ICommand command, ICommandStrategy strategy, CancellationToken cancellationToken = default);
Task SendAsync(ICommand command, ICommandStrategy? strategy, CancellationToken cancellationToken = default);
}

View file

@ -18,7 +18,7 @@ public interface INotificationSender
/// Publishes the given notification.
/// </summary>
/// <param name="notification">The notification to publish.</param>
/// <param name="strategy"><see cref="FireAndForgetStrategy"/><see cref="SequentialProcessingStrategy"/><see cref="ParallelProcessingStrategy"/></param>
/// <param name="strategy"><see cref="SequentialProcessingStrategy"/><see cref="ParallelProcessingStrategy"/></param>
/// <param name="cancellationToken">The cancellation token.</param>
Task SendAsync(INotification notification, IEventPublishingStrategy strategy, CancellationToken cancellationToken = default);
Task SendAsync(INotification notification, IEventPublishingStrategy? strategy, CancellationToken cancellationToken = default);
}

View file

@ -14,7 +14,7 @@ public class BackgroundCommandSenderHostedService : BackgroundService
private readonly int _workerCount;
private readonly ICommandsChannel _commandsChannel;
private readonly IServiceScopeFactory _scopeFactory;
private readonly IList<Channel<ICommand>> _outputs;
private readonly List<Channel<ICommand>> _outputs;
private readonly ILogger _logger;
/// <inheritdoc />

View file

@ -14,7 +14,7 @@ public class BackgroundEventPublisherHostedService : BackgroundService
private readonly int _workerCount;
private readonly INotificationsChannel _notificationsChannel;
private readonly IServiceScopeFactory _scopeFactory;
private readonly IList<Channel<INotification>> _outputs;
private readonly List<Channel<INotification>> _outputs;
private readonly ILogger _logger;
/// <inheritdoc />

View file

@ -14,7 +14,7 @@ public class MessageProcessorHostedService<T> : BackgroundService where T : notn
private readonly Channel<T> _channel;
private readonly IEnumerable<IConsumer<T>> _consumers;
private readonly ILogger _logger;
private readonly IList<MessageWorker<T>> _workers;
private readonly List<MessageWorker<T>> _workers;
/// <inheritdoc />
// ReSharper disable once ContextualLoggerProblem

View file

@ -6,7 +6,7 @@ namespace Elsa.Mediator.Middleware.Command;
public class CommandPipelineBuilder : ICommandPipelineBuilder
{
private const string ServicesKey = "mediator.Services";
private readonly IList<Func<CommandMiddlewareDelegate, CommandMiddlewareDelegate>> _components = new List<Func<CommandMiddlewareDelegate, CommandMiddlewareDelegate>>();
private readonly List<Func<CommandMiddlewareDelegate, CommandMiddlewareDelegate>> _components = new();
/// <summary>
/// Initializes a new instance of the <see cref="CommandPipelineBuilder"/> class.
@ -38,8 +38,10 @@ public class CommandPipelineBuilder : ICommandPipelineBuilder
{
CommandMiddlewareDelegate pipeline = _ => new ValueTask();
foreach (var component in _components.Reverse())
pipeline = component(pipeline);
for (int i = _components.Count - 1; i >= 0; i--)
{
pipeline = _components[i](pipeline);
}
return pipeline;
}

View file

@ -33,7 +33,7 @@ public class CommandHandlerInvokerMiddleware : ICommandMiddleware
var handlerType = typeof(ICommandHandler<,>).MakeGenericType(commandType, resultType);
var handlers = _commandHandlers.Where(x => handlerType.IsInstanceOfType(x)).ToArray();
if (!handlers.Any())
if (handlers.Length == 0)
throw new InvalidOperationException($"There is no handler to handle the {commandType.FullName} command");
if (handlers.Length > 1)

View file

@ -6,7 +6,7 @@ namespace Elsa.Mediator.Middleware.Notification;
public class NotificationPipelineBuilder : INotificationPipelineBuilder
{
private const string ServicesKey = "mediator.Services";
private readonly IList<Func<NotificationMiddlewareDelegate, NotificationMiddlewareDelegate>> _components = new List<Func<NotificationMiddlewareDelegate, NotificationMiddlewareDelegate>>();
private readonly List<Func<NotificationMiddlewareDelegate, NotificationMiddlewareDelegate>> _components = new();
/// <summary>
/// Initializes a new instance of the <see cref="NotificationPipelineBuilder"/> class.
@ -38,8 +38,10 @@ public class NotificationPipelineBuilder : INotificationPipelineBuilder
{
NotificationMiddlewareDelegate pipeline = _ => new ValueTask();
foreach (var component in _components.Reverse())
pipeline = component(pipeline);
for (int i = _components.Count - 1; i >= 0; i--)
{
pipeline = _components[i](pipeline);
}
return pipeline;
}

View file

@ -6,7 +6,7 @@ namespace Elsa.Mediator.Middleware.Request;
public class RequestPipelineBuilder : IRequestPipelineBuilder
{
private const string ServicesKey = "mediator.Services";
private readonly IList<Func<RequestMiddlewareDelegate, RequestMiddlewareDelegate>> _components = new List<Func<RequestMiddlewareDelegate, RequestMiddlewareDelegate>>();
private readonly List<Func<RequestMiddlewareDelegate, RequestMiddlewareDelegate>> _components = new();
/// <summary>
/// Initializes a new instance of the <see cref="RequestPipelineBuilder"/> class.
@ -38,8 +38,10 @@ public class RequestPipelineBuilder : IRequestPipelineBuilder
{
RequestMiddlewareDelegate pipeline = _ => new ValueTask();
foreach (var component in _components.Reverse())
pipeline = component(pipeline);
for (int i = _components.Count - 1; i >= 0; i--)
{
pipeline = _components[i](pipeline);
}
return pipeline;
}

View file

@ -25,7 +25,7 @@ public class TenantResolutionContext
/// <summary>
/// Gets the cancellation token.
/// </summary>
public CancellationToken CancellationToken { get; } = default;
public CancellationToken CancellationToken { get; }
/// <summary>
/// Finds a tenant based on the provided tenant ID.

View file

@ -1,3 +1,4 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
@ -17,7 +18,7 @@ public class DecimalJsonConverter : JsonConverter<decimal>
if (reader.TokenType == JsonTokenType.String)
{
var value = reader.GetString()!;
return decimal.Parse(value);
return decimal.Parse(value, CultureInfo.InvariantCulture);
}
throw new JsonException("Expected number or string.");

View file

@ -1,3 +1,4 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
@ -17,7 +18,7 @@ public class IntegerJsonConverter : JsonConverter<int>
if (reader.TokenType == JsonTokenType.String)
{
var value = reader.GetString()!;
return int.Parse(value);
return int.Parse(value, CultureInfo.InvariantCulture);
}
throw new JsonException("Expected number or string.");

View file

@ -1,4 +1,5 @@
using System.ComponentModel;
using System.Globalization;
using System.Text.Json.Serialization;
using Elsa.Common.Converters;
using JetBrains.Annotations;
@ -60,7 +61,7 @@ public struct VersionOptions
"Published" => Published,
"LatestOrPublished" => LatestOrPublished,
"LatestAndPublished" => LatestAndPublished,
_ => SpecificVersion(int.Parse(value))
_ => SpecificVersion(int.Parse(value, CultureInfo.InvariantCulture))
};
/// <summary>
@ -113,5 +114,5 @@ public struct VersionOptions
/// <summary>
/// Returns a simple string representation of this <see cref="VersionOptions"/>.
/// </summary>
public override string ToString() => AllVersions ? "AllVersions" : IsDraft ? "Draft" : IsLatest ? "Latest" : IsPublished ? "Published" : IsLatestOrPublished ? "LatestOrPublished" : IsLatestAndPublished ? "LatestAndPublished" : Version.ToString();
public override string ToString() => AllVersions ? "AllVersions" : IsDraft ? "Draft" : IsLatest ? "Latest" : IsPublished ? "Published" : IsLatestOrPublished ? "LatestOrPublished" : IsLatestAndPublished ? "LatestAndPublished" : Version.ToString(CultureInfo.InvariantCulture);
}

View file

@ -67,7 +67,7 @@ public abstract class ConfigurableSerializer
/// <summary>
/// Creates a new instance of <see cref="JsonSerializerOptions"/>.
/// </summary>
private JsonSerializerOptions CreateOptionsInternal()
private static JsonSerializerOptions CreateOptionsInternal()
{
var options = new JsonSerializerOptions
{

View file

@ -119,7 +119,7 @@ public class MemoryStore<TEntity>
foreach (var entry in entries)
Entities.Remove(entry);
return entries.LongCount();
return entries.Count;
}
/// <summary>

View file

@ -181,10 +181,10 @@ public static class ObjectConverter
return Enum.ToObject(underlyingTargetType, value);
if (underlyingSourceType == typeof(double))
return Enum.ToObject(underlyingTargetType, Convert.ChangeType(value, typeof(int)));
return Enum.ToObject(underlyingTargetType, Convert.ChangeType(value, typeof(int), CultureInfo.InvariantCulture));
if (underlyingSourceType == typeof(long))
return Enum.ToObject(underlyingTargetType, Convert.ChangeType(value, typeof(int)));
return Enum.ToObject(underlyingTargetType, Convert.ChangeType(value, typeof(int), CultureInfo.InvariantCulture));
}
if (value is string s)
@ -225,7 +225,7 @@ public static class ObjectConverter
try
{
return Convert.ChangeType(value, underlyingTargetType);
return Convert.ChangeType(value, underlyingTargetType, CultureInfo.InvariantCulture);
}
catch (InvalidCastException e)
{

View file

@ -7,8 +7,8 @@ namespace Elsa.Expressions.Services;
/// <inheritdoc />
public class WellKnownTypeRegistry : IWellKnownTypeRegistry
{
private readonly IDictionary<string, Type> _aliasTypeDictionary = new Dictionary<string, Type>();
private readonly IDictionary<Type, string> _typeAliasDictionary = new Dictionary<Type, string>();
private readonly Dictionary<string, Type> _aliasTypeDictionary = new();
private readonly Dictionary<Type, string> _typeAliasDictionary = new();
/// <summary>
/// Creates a new instance of the <see cref="WellKnownTypeRegistry"/> class.

View file

@ -4,11 +4,6 @@
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NSubstitute"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\modules\Elsa.MongoDb\Elsa.MongoDb.csproj" />
</ItemGroup>

View file

@ -8,8 +8,4 @@
<ProjectReference Include="..\..\..\src\modules\Elsa.Workflows.Runtime\Elsa.Workflows.Runtime.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NSubstitute" />
</ItemGroup>
</Project>