Skip to content

Commit

Permalink
minor warning fixes by SonarLint
Browse files Browse the repository at this point in the history
  • Loading branch information
luca-domenichini committed Dec 14, 2023
1 parent e6f2b2e commit f5127e4
Show file tree
Hide file tree
Showing 31 changed files with 207 additions and 189 deletions.
3 changes: 1 addition & 2 deletions Apps/SmartIOT.Connector.App/AspNetExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using SmartIOT.Connector.Core;
using SmartIOT.Connector.Core.Factory;
using SmartIOT.Connector.Core.Factory;

namespace SmartIOT.Connector.App;

Expand Down
32 changes: 16 additions & 16 deletions Apps/SmartIOT.Connector.App/Runner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,28 +36,28 @@ public Runner(AppConfiguration configuration, ILogger<Runner> logger)
if (configuration.PrometheusConfiguration != null)
SmartIotConnector.AddPrometheus(configuration.PrometheusConfiguration);

SmartIotConnector.SchedulerStarting += (s, e) => _logger.LogInformation($"{e.Scheduler.DeviceDriver.Name}: Scheduler starting");
SmartIotConnector.SchedulerStopping += (s, e) => _logger.LogInformation($"{e.Scheduler.DeviceDriver.Name}: Scheduler stopping");
SmartIotConnector.SchedulerRestarting += (s, e) => _logger.LogInformation($"{e.DeviceDriver.Name}: Scheduler restarting");
SmartIotConnector.SchedulerStarting += (s, e) => _logger.LogInformation("{driver}: Scheduler starting", e.Scheduler.DeviceDriver.Name);
SmartIotConnector.SchedulerStopping += (s, e) => _logger.LogInformation("{driver}: Scheduler stopping", e.Scheduler.DeviceDriver.Name);
SmartIotConnector.SchedulerRestarting += (s, e) => _logger.LogInformation("{driver}: Scheduler restarting", e.DeviceDriver.Name);
SmartIotConnector.SchedulerRestarted += (s, e) =>
{
if (e.IsSuccess)
_logger.LogInformation($"{e.DeviceDriver.Name}: Scheduler restarted successfully");
_logger.LogInformation("{driver}: Scheduler restarted successfully", e.DeviceDriver.Name);
else
_logger.LogError($"{e.DeviceDriver.Name}: Error during scheduler restart: {e.ErrorDescription}");
_logger.LogError("{driver}: Error during scheduler restart: {message}", e.DeviceDriver.Name, e.ErrorDescription);
};
SmartIotConnector.TagReadEvent += (s, e) =>
{
if (e.TagScheduleEvent.Data != null)
{
// data event
if (e.TagScheduleEvent.Data.Length > 0)
_logger.LogInformation($"{e.DeviceDriver.Name}: {e.TagScheduleEvent.Device.Name}, {e.TagScheduleEvent.Tag.TagId}: received data[{e.TagScheduleEvent.StartOffset}..{e.TagScheduleEvent.StartOffset + e.TagScheduleEvent.Data.Length - 1}], size {e.TagScheduleEvent.Data.Length}");
_logger.LogInformation("{driver}: {device}, {tag}: received data[{offset}..{endOffset}], size {size}", e.DeviceDriver.Name, e.TagScheduleEvent.Device.Name, e.TagScheduleEvent.Tag.TagId, e.TagScheduleEvent.StartOffset, e.TagScheduleEvent.StartOffset + e.TagScheduleEvent.Data.Length - 1, e.TagScheduleEvent.Data.Length);
}
else if (e.TagScheduleEvent.IsErrorNumberChanged)
{
// status changed
_logger.LogInformation($"{e.DeviceDriver.Name}: {e.TagScheduleEvent.Device.Name}, {e.TagScheduleEvent.Tag.TagId}: status changed {e.TagScheduleEvent.ErrorNumber} {e.TagScheduleEvent.Description}");
_logger.LogInformation("{driver}: {device}, {tag}: status changed {err} {message}", e.DeviceDriver.Name, e.TagScheduleEvent.Device.Name, e.TagScheduleEvent.Tag.TagId, e.TagScheduleEvent.ErrorNumber, e.TagScheduleEvent.Description);
}
};
SmartIotConnector.TagWriteEvent += (s, e) =>
Expand All @@ -70,33 +70,33 @@ public Runner(AppConfiguration configuration, ILogger<Runner> logger)
SmartIotConnector.Stopped += (s, e) => _logger.LogInformation("SmartIOT.Connector stopped");
SmartIotConnector.ConnectorStarted += (s, e) =>
{
_logger.LogInformation($"{e.Connector.GetType().Name}: {e.Info}");
_logger.LogInformation("{connector}: {message}", e.Connector.GetType().Name, e.Info);
};
SmartIotConnector.ConnectorStopped += (s, e) =>
{
_logger.LogInformation($"{e.Connector.GetType().Name}: {e.Info}");
_logger.LogInformation("{connector}: {message}", e.Connector.GetType().Name, e.Info);
};
SmartIotConnector.ConnectorConnected += (s, e) =>
{
_logger.LogInformation($"{e.Connector.GetType().Name}: {e.Info}");
_logger.LogInformation("{connector}: {message}", e.Connector.GetType().Name, e.Info);
};
SmartIotConnector.ConnectorConnectionFailed += (s, e) =>
{
_logger.LogError(e.Exception, $"{e.Connector.GetType().Name}: {e.Info}");
_logger.LogError(e.Exception, "{connector}: {message}", e.Connector.GetType().Name, e.Info);
};
SmartIotConnector.ConnectorDisconnected += (s, e) =>
{
_logger.LogInformation($"{e.Connector.GetType().Name}: {e.Info}");
_logger.LogInformation("{connector}: {message}", e.Connector.GetType().Name, e.Info);
};
SmartIotConnector.ConnectorException += (s, e) =>
{
_logger.LogError(e.Exception, $"{e.Connector.GetType().Name}: Unexpected exception: {e.Exception.Message}");
_logger.LogError(e.Exception, "{connector}: Unexpected exception: {message}", e.Connector.GetType().Name, e.Exception.Message);
};

if (builder.AutoDiscoveryExceptions.Any())
if (builder.AutoDiscoveryExceptions.Any() && _logger.IsEnabled(LogLevel.Debug))
{
if (_logger.IsEnabled(LogLevel.Debug))
_logger.LogDebug($"Error autodiscoverying dll: [{Environment.NewLine}{string.Join($"{Environment.NewLine}\t", builder.AutoDiscoveryExceptions.Select(x => x.Message))}{Environment.NewLine}]");
string details = string.Join($"{Environment.NewLine}\t", builder.AutoDiscoveryExceptions.Select(x => x.Message));
_logger.LogDebug("Error autodiscoverying dll: [{nl}{details}{nl}]", Environment.NewLine, details, Environment.NewLine);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,12 @@ public class AggregatingConnectorEventQueue : AggregatingQueue<CompositeConnecto
return null;
}

#pragma warning disable S1172 // Unused method parameters should be removed

private CompositeConnectorEvent? AggregateExceptionEvents(object? sender, ExceptionEventArgs item1, ExceptionEventArgs item2)
{
return null;
}

#pragma warning restore S1172 // Unused method parameters should be removed
}
2 changes: 1 addition & 1 deletion Core/SmartIOT.Connector.Core/Connector/AggregatingQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public T PopWait(CancellationToken cancellationToken)
{
T? item = default;

while (_queue.Any())
while (_queue.Count > 0)
{
if (item == default)
{
Expand Down
2 changes: 1 addition & 1 deletion Core/SmartIOT.Connector.Core/Factory/ConnectorFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public void AddRange(IList<IConnectorFactory> connectorFactories)

public bool Any(Func<IConnectorFactory, bool> predicate)
{
return _factories.Any(x => predicate(x));
return _factories.Exists(x => predicate(x));
}

public IConnector? CreateConnector(string connectionString)
Expand Down
4 changes: 2 additions & 2 deletions Core/SmartIOT.Connector.Core/Factory/DeviceDriverFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ public void AddRange(IList<IDeviceDriverFactory> deviceDriverFactories)
_factories.AddRange(deviceDriverFactories);
}

public bool Any() => _factories.Any();
public bool Any() => _factories.Count > 0;

public bool Any(Func<object, bool> predicate) => _factories.Any(predicate);
public bool Any(Func<object, bool> predicate) => _factories.Exists(x => predicate.Invoke(x));

public IDeviceDriver? CreateDriver(DeviceConfiguration deviceConfiguration)
{
Expand Down
51 changes: 22 additions & 29 deletions Core/SmartIOT.Connector.Core/Model/Device.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,13 +190,7 @@ internal void SetTagSynchronized(Tag tag, DateTime instant)
maxPunti = GetMaxPoints(type);
List<Tag> list = GetTagsInRange(type, maxPunti - GetWeightMCM(type), maxPunti);

int min = int.MaxValue;
foreach (Tag t in list)
{
if (t.Points < min)
min = t.Points;
}

int min = list.Count > 0 ? list.Min(x => x.Points) : int.MaxValue;
if (min - GetWeightMCM(type) < 0)
{
riscalaturaPossibile = false;
Expand Down Expand Up @@ -273,34 +267,33 @@ private int GetWeightMCM(TagType type)

private int CalculateMCM(TagType type)
{
int max = int.MinValue;
return FindLCM(_tags.Where(x => x.TagType == type).Select(x => x.Weight));
}

foreach (Tag t in _tags)
{
if (t.TagType == type && t.Weight > max)
max = t.Weight;
}
private static int FindLCM(IEnumerable<int> numbers)
{
int lcm = int.MinValue;

bool mcmTrovato = false;
while (!mcmTrovato)
foreach (var n in numbers)
{
mcmTrovato = true;

foreach (Tag t in _tags)
{
if (t.TagType == type && max % t.Weight != 0)
{
mcmTrovato = false;
break;
}
}
if (lcm == int.MinValue)
lcm = n;
else
lcm = Math.Abs(lcm * n) / FindGCD(lcm, n);
}

if (mcmTrovato)
break;
return lcm;
}

max++;
private static int FindGCD(int a, int b)
{
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}

return max;
return a;
}
}
2 changes: 2 additions & 0 deletions Core/SmartIOT.Connector.Core/Model/Tag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,13 @@ public Tag(TagConfiguration tagConfiguration)
/// </summary>
public void RequestTagWrite(byte[] data, int startOffset)
{
#pragma warning disable S2551 // Shared resources should not be used for locking: we purposefully lock on "this" to avoid races between tag-scheduler and services that request tag write.
lock (this)
{
Array.Copy(data, 0, Data, startOffset - ByteOffset, data.Length);
IsWriteSynchronizationRequested = true;
}
#pragma warning restore S2551 // Shared resources should not be used for locking
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ private TagScheduleEvent WriteTag(TagSchedule schedule)
// del valore 0 sempre in DB22.DBX0.0, annullando in pratica la richiesta precedente. Il flag "needsWrite" rimane a true
// tuttavia non c'è alcun cambiamento sul datablock che deve effettivamente essere scritto.
List<TagChangeBounds> listBounds = ParseWriteBounds(device, tag);
if (!listBounds.Any())
if (listBounds.Count == 0)
{
// se la lista dei bounds è vuota, interpreto la schedule come una scrittura completa
// questo è usato anche per gestire il parametro rewritePeriod dei tag in scrittura: ogni tot millisecondi, vengono comunque scritti tutti
Expand Down
27 changes: 13 additions & 14 deletions Core/SmartIOT.Connector.Core/SmartIotConnectorBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using SmartIOT.Connector.Core.Conf;
#pragma warning disable S3885 // "Assembly.Load" should be used

using SmartIOT.Connector.Core.Conf;
using SmartIOT.Connector.Core.Factory;
using SmartIOT.Connector.Core.Scheduler;
using System.Reflection;
Expand Down Expand Up @@ -86,28 +88,25 @@ public SmartIotConnector Build()
if (_autoDiscoverDeviceDriverFactory)
DeviceDriverFactory.AddRange(AutoDiscoverDeviceDriverFactories());

if (!DeviceDriverFactory.Any() && !_deviceDrivers.Any())
if (!DeviceDriverFactory.Any() && _deviceDrivers.Count == 0)
throw new ArgumentException($"Nessuna {nameof(IDeviceDriverFactory)} o {nameof(IDeviceDriver)} presente in configurazione");

if (_autoDiscoverConnectorFactory)
ConnectorFactory.AddRange(AutoDiscoverConnectorFactories());

IList<ITagScheduler> schedulers = BuildSchedulers();
IList<IConnector> connectors = BuildConnectors();
var schedulers = BuildSchedulers();
var connectors = BuildConnectors();

return new SmartIotConnector(schedulers, connectors, Configuration.SchedulerConfiguration);
}

private IList<IConnector> BuildConnectors()
private List<IConnector> BuildConnectors()
{
var list = new List<IConnector>();

foreach (var connectionString in Configuration!.ConnectorConnectionStrings)
{
IConnector? connector = ConnectorFactory.CreateConnector(connectionString);
if (connector == null)
throw new ArgumentException($"Impossibile creare il connector: ConnectionString {connectionString} non riconosciuta.");

IConnector? connector = ConnectorFactory.CreateConnector(connectionString) ?? throw new ArgumentException($"Error creating connector: ConnectionString {connectionString} not recognized.");
list.Add(connector);
}

Expand All @@ -116,12 +115,12 @@ private IList<IConnector> BuildConnectors()
return list;
}

private IList<ITagScheduler> BuildSchedulers()
private List<ITagScheduler> BuildSchedulers()
{
// creating schedulers from configuration
var drivers = new Dictionary<DeviceConfiguration, IDeviceDriver>();
var devices = new List<DeviceConfiguration>(Configuration!.DeviceConfigurations);
if (devices.Any())
if (devices.Count > 0)
{
foreach (var device in devices)
{
Expand All @@ -135,7 +134,7 @@ private IList<ITagScheduler> BuildSchedulers()
devices.RemoveAll(x => drivers.ContainsKey(x)); // rimuovo dalla lista temporanea le configurazioni che hanno ritornato un driver
}

if (devices.Any())
if (devices.Count > 0)
throw new ArgumentException($"Error configuring SmartIotConnector: no scheduler factory found for these devices:\r\n{string.Join("\r\n", devices.Select(x => x.Name + ": " + x.ConnectionString))}");

var schedulers = drivers.Values.Select(x => SchedulerFactory.CreateScheduler(x.Name, x, TimeService, Configuration.SchedulerConfiguration)).ToList();
Expand All @@ -146,7 +145,7 @@ private IList<ITagScheduler> BuildSchedulers()
return schedulers;
}

private IList<IDeviceDriverFactory> AutoDiscoverDeviceDriverFactories()
private List<IDeviceDriverFactory> AutoDiscoverDeviceDriverFactories()
{
var list = new List<IDeviceDriverFactory>();

Expand Down Expand Up @@ -188,7 +187,7 @@ ex is BadImageFormatException
return list;
}

private IList<IConnectorFactory> AutoDiscoverConnectorFactories()
private List<IConnectorFactory> AutoDiscoverConnectorFactories()
{
var list = new List<IConnectorFactory>();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace SmartIOT.Connector.Core.Util;

public class ConnectionStringParser
public static class ConnectionStringParser
{
public static IDictionary<string, string> ParseTokens(string connectionString)
{
Expand Down
6 changes: 2 additions & 4 deletions Core/SmartIOT.Connector.Core/Util/CopyOnWriteArrayList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,7 @@ public bool Contains(object? value)

public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
ArgumentNullException.ThrowIfNull(array);

var data = _data;

Expand All @@ -111,8 +110,7 @@ public void CopyTo(T[] array, int arrayIndex)

public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
ArgumentNullException.ThrowIfNull(array);

var data = _data;
Array.Copy(data, array, data.Length);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@ public class JsonSingleMessageSerializer : ISingleMessageSerializer
{
private readonly JsonSerializerOptions _options;

public JsonSingleMessageSerializer()
: this(CreateDefaultSerializerOptions())
{
}

private static JsonSerializerOptions CreateDefaultSerializerOptions()
{
var options = new JsonSerializerOptions()
Expand All @@ -20,6 +15,11 @@ private static JsonSerializerOptions CreateDefaultSerializerOptions()
return options;
}

public JsonSingleMessageSerializer()
: this(CreateDefaultSerializerOptions())
{
}

public JsonSingleMessageSerializer(JsonSerializerOptions options)
{
_options = options;
Expand All @@ -30,8 +30,8 @@ public byte[] SerializeMessage(object message)
return JsonSerializer.SerializeToUtf8Bytes(message, _options);
}

public T? DeserializeMessage<T>(byte[] message)
public T? DeserializeMessage<T>(byte[] bytes)
{
return JsonSerializer.Deserialize<T>(message, _options);
return JsonSerializer.Deserialize<T>(bytes, _options);
}
}
Loading

0 comments on commit f5127e4

Please sign in to comment.