From b09c0a02fe0210c5059c19101e661ab98ee06f3e Mon Sep 17 00:00:00 2001 From: helto4real Date: Sun, 6 Dec 2020 17:09:27 +0100 Subject: [PATCH] record and c# 9 refactors --- .devcontainer/Dockerfile | 1 + .../NetDaemon.App/Common/AppRuntimeInfo.cs | 2 +- src/App/NetDaemon.App/Common/DelayResult.cs | 2 +- .../NetDaemon.App/Common/ExtensionMethods.cs | 2 +- .../Common/Fluent/FluentCamera.cs | 6 +- .../Common/Fluent/FluentExpandoObject.cs | 4 +- .../Common/Fluent/FluentInputSelect.cs | 2 +- .../Common/Fluent/IEntityProperties.cs | 14 ++--- src/App/NetDaemon.App/Common/Messages.cs | 58 +++++++++---------- .../NetDaemon.App/Common/NetDaemonAppBase.cs | 18 +++--- .../Common/Reactive/AppDaemonRxApp.cs | 4 +- .../Common/Reactive/ObservableBase.cs | 2 +- .../NetDaemon.App/Common/Reactive/RxEntity.cs | 12 ++-- .../NetDaemon.Daemon/Daemon/HttpHandler.cs | 2 +- .../NetDaemon.Daemon/Daemon/NetDaemonHost.cs | 47 ++++++++------- .../DaemonRunner/Service/API/WsHandler.cs | 10 ++-- .../DaemonRunner/Service/App/CodeGenerator.cs | 4 +- .../Service/App/DaemonCompiler.cs | 6 +- src/Service/Program.cs | 8 +-- .../Daemon/HttpHandlerMock.cs | 2 +- .../NetDaemon.Daemon.Tests/HassClientMock.cs | 4 +- tests/NetDaemon.Daemon.Tests/LoggerMock.cs | 4 +- tests/NetDaemon.Test/HassClientMock.cs | 4 +- tests/NetDaemon.Test/HttpHandlerMock.cs | 2 +- tests/NetDaemon.Test/LoggerMock.cs | 4 +- 25 files changed, 116 insertions(+), 108 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 422ba4caa..191e673f1 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -5,6 +5,7 @@ FROM mcr.microsoft.com/dotnet/sdk:5.0.100 +RUN apt-get update && apt-get install openssh-client # This Dockerfile adds a non-root 'vscode' user with sudo access. However, for Linux, # this user's GID/UID must match your local user UID/GID to avoid permission issues # with bind mounts. Update USER_UID / USER_GID if yours is not 1000. See diff --git a/src/App/NetDaemon.App/Common/AppRuntimeInfo.cs b/src/App/NetDaemon.App/Common/AppRuntimeInfo.cs index f9ecace0a..d6fb11f5d 100644 --- a/src/App/NetDaemon.App/Common/AppRuntimeInfo.cs +++ b/src/App/NetDaemon.App/Common/AppRuntimeInfo.cs @@ -33,7 +33,7 @@ public sealed class AppRuntimeInfo /// in app switch /// [JsonPropertyName("app_attributes")] - public Dictionary AppAttributes { get; set; } = new Dictionary(); + public Dictionary AppAttributes { get; set; } = new(); } diff --git a/src/App/NetDaemon.App/Common/DelayResult.cs b/src/App/NetDaemon.App/Common/DelayResult.cs index dcc824e0f..fa92f28c6 100644 --- a/src/App/NetDaemon.App/Common/DelayResult.cs +++ b/src/App/NetDaemon.App/Common/DelayResult.cs @@ -29,7 +29,7 @@ public DelayResult(TaskCompletionSource delayTaskCompletionSource, INetDae /// public Task Task => _delayTaskCompletionSource.Task; - internal ConcurrentBag StateSubscriptions { get; set; } = new ConcurrentBag(); + internal ConcurrentBag StateSubscriptions { get; set; } = new(); /// public void Cancel() diff --git a/src/App/NetDaemon.App/Common/ExtensionMethods.cs b/src/App/NetDaemon.App/Common/ExtensionMethods.cs index 586d6aad6..626bc432a 100644 --- a/src/App/NetDaemon.App/Common/ExtensionMethods.cs +++ b/src/App/NetDaemon.App/Common/ExtensionMethods.cs @@ -42,7 +42,7 @@ public static dynamic ToDynamic(this (string name, object val)[] attributeNameVa foreach (PropertyDescriptor? property in TypeDescriptor.GetProperties(obj.GetType())) { - if (property is object) + if (property is not null) expando.Add(property.Name, property.GetValue(obj)); } diff --git a/src/App/NetDaemon.App/Common/Fluent/FluentCamera.cs b/src/App/NetDaemon.App/Common/Fluent/FluentCamera.cs index a25e11c97..6fad012d7 100644 --- a/src/App/NetDaemon.App/Common/Fluent/FluentCamera.cs +++ b/src/App/NetDaemon.App/Common/Fluent/FluentCamera.cs @@ -114,7 +114,7 @@ public IExecuteAsync PlayStream(string mediaPlayerId, string? format = null) serviceData.media_player = mediaPlayerId; - if (format is object) + if (format is not null) serviceData.format = format; _serviceCall = ("play_stream", serviceData); @@ -128,9 +128,9 @@ public IExecuteAsync Record(string fileName, int? duration = null, int? lookback serviceData.filename = fileName; - if (duration is object) + if (duration is not null) serviceData.duration = duration; - if (lookback is object) + if (lookback is not null) serviceData.lookback = lookback; _serviceCall = ("record", serviceData); diff --git a/src/App/NetDaemon.App/Common/Fluent/FluentExpandoObject.cs b/src/App/NetDaemon.App/Common/Fluent/FluentExpandoObject.cs index 807a3a3bb..a5a79d148 100644 --- a/src/App/NetDaemon.App/Common/Fluent/FluentExpandoObject.cs +++ b/src/App/NetDaemon.App/Common/Fluent/FluentExpandoObject.cs @@ -17,7 +17,7 @@ namespace NetDaemon.Common.Fluent /// public class FluentExpandoObject : DynamicObject, IDictionary { - private readonly Dictionary _dict = new Dictionary(); + private readonly Dictionary _dict = new(); private readonly NetDaemonAppBase? _daemonApp; private readonly bool _ignoreCase; private readonly bool _returnNullMissingProperties; @@ -194,7 +194,7 @@ public dynamic CopyFrom(IDictionary obj) if (keyValuePair.Value is JsonElement val) { var dynValue = val.ToDynamicValue(); - if (dynValue is object) + if (dynValue is not null) { UpdateDictionary(keyValuePair.Key, dynValue); } diff --git a/src/App/NetDaemon.App/Common/Fluent/FluentInputSelect.cs b/src/App/NetDaemon.App/Common/Fluent/FluentInputSelect.cs index a5e1766bf..a9cb745ce 100644 --- a/src/App/NetDaemon.App/Common/Fluent/FluentInputSelect.cs +++ b/src/App/NetDaemon.App/Common/Fluent/FluentInputSelect.cs @@ -61,7 +61,7 @@ public InputSelectManager(IEnumerable entityIds, INetDaemon daemon, INet /// public Task ExecuteAsync() { - List tasks = new List(); + List tasks = new(); foreach (var entityId in _entityIds) { dynamic data = new FluentExpandoObject(); diff --git a/src/App/NetDaemon.App/Common/Fluent/IEntityProperties.cs b/src/App/NetDaemon.App/Common/Fluent/IEntityProperties.cs index b3d647590..23a87568a 100644 --- a/src/App/NetDaemon.App/Common/Fluent/IEntityProperties.cs +++ b/src/App/NetDaemon.App/Common/Fluent/IEntityProperties.cs @@ -10,36 +10,36 @@ public interface IEntityProperties /// /// Filter on area where the entity device are at /// - string? Area { get; set; } + string? Area { get; } /// /// Filter on attribute /// - dynamic? Attribute { get; set; } + dynamic? Attribute { get; } /// /// Filter on unique id of the entity /// - string EntityId { get; set; } + string EntityId { get; } /// /// Filter on last changed time /// - DateTime LastChanged { get; set; } + DateTime LastChanged { get; } /// /// Filter on last updated time /// - DateTime LastUpdated { get; set; } + DateTime LastUpdated { get; } /// /// Filter on state /// - dynamic? State { get; set; } + dynamic? State { get; } /// /// Context /// - public Context? Context { get; set; } + public Context? Context { get; } } } \ No newline at end of file diff --git a/src/App/NetDaemon.App/Common/Messages.cs b/src/App/NetDaemon.App/Common/Messages.cs index 310f0d35f..c9c9ad0e1 100644 --- a/src/App/NetDaemon.App/Common/Messages.cs +++ b/src/App/NetDaemon.App/Common/Messages.cs @@ -9,98 +9,98 @@ namespace NetDaemon.Common /// /// Home assistant config parameters /// - public class Config + public record Config { /// /// Components being installed and used /// - public List? Components { get; set; } = null; + public List? Components { get; init; } = null; /// /// Local config directory /// - public string? ConfigDir { get; set; } = null; + public string? ConfigDir { get; init; } = null; /// /// Elevation of Home Assistant instance /// - public int? Elevation { get; set; } = null; + public int? Elevation { get; init; } = null; /// /// Latitude of Home Assistant instance /// - public float? Latitude { get; set; } = null; + public float? Latitude { get; init; } = null; /// /// The name of the location /// - public string? LocationName { get; set; } = null; + public string? LocationName { get; init; } = null; /// /// Longitude of Home Assistant instance /// - public float? Longitude { get; set; } = null; + public float? Longitude { get; init; } = null; /// /// The timezone /// - public string? TimeZone { get; set; } = null; + public string? TimeZone { get; init; } = null; /// /// Unity system being configured /// - public HassUnitSystem? UnitSystem { get; set; } = null; + public HassUnitSystem? UnitSystem { get; init; } = null; /// /// Current Home Assistant version /// - public string? Version { get; set; } = null; + public string? Version { get; init; } = null; /// /// Whitelisted external directories /// - public List? WhitelistExternalDirs { get; set; } = null; + public List? WhitelistExternalDirs { get; init; } = null; } /// /// Detailed state information /// - public class EntityState : IEntityProperties + public record EntityState : IEntityProperties { /// /// The name of the Area in home assistant /// - public string? Area { get; set; } + public string? Area { get; init; } /// /// Attributes of the entity /// - public dynamic? Attribute { get; set; } = new FluentExpandoObject(true, true); + public dynamic? Attribute { get; init; } = new FluentExpandoObject(true, true); /// /// Unique id of the entity /// - public string EntityId { get; set; } = ""; + public string EntityId { get; init; } = ""; /// /// Last changed, when state changed from and to different values /// - public DateTime LastChanged { get; set; } = DateTime.MinValue; + public DateTime LastChanged { get; init; } = DateTime.MinValue; /// /// Last updated, when entity state or attributes changed /// - public DateTime LastUpdated { get; set; } = DateTime.MinValue; + public DateTime LastUpdated { get; init; } = DateTime.MinValue; /// /// The state /// - public dynamic? State { get; set; } = ""; + public dynamic? State { get; init; } = ""; /// /// Context /// - public Context? Context { get; set; } + public Context? Context { get; init; } /// /// returns a pretty print of EntityState @@ -113,7 +113,7 @@ public override string ToString() { foreach (var key in attr.Keys) { - if (key is object) + if (key is not null) { attributes = attributes + string.Format(" {0}:{1}", key, attr[key]); } @@ -135,48 +135,48 @@ public override string ToString() /// /// Unit system parameters for Home Assistant /// - public class HassUnitSystem + public record HassUnitSystem { /// /// Lenght unit /// - public string? Length { get; set; } = null; + public string? Length { get; init; } = null; /// /// Mass unit /// - public string? Mass { get; set; } = null; + public string? Mass { get; init; } = null; /// /// Temperature unit /// - public string? Temperature { get; set; } = null; + public string? Temperature { get; init; } = null; /// /// Volume unit /// - public string? Volume { get; set; } = null; + public string? Volume { get; init; } = null; } /// /// Event from CallService /// - public class ServiceEvent + public record ServiceEvent { /// /// Home Assistant domain /// - public string Domain { get; set; } = ""; + public string Domain { get; init; } = ""; /// /// Service being called /// - public string Service { get; set; } = ""; + public string Service { get; init; } = ""; /// /// Data being sent by the service /// /// - public JsonElement? ServiceData { get; set; } = null; + public JsonElement? ServiceData { get; init; } = null; } } \ No newline at end of file diff --git a/src/App/NetDaemon.App/Common/NetDaemonAppBase.cs b/src/App/NetDaemon.App/Common/NetDaemonAppBase.cs index 79af87b6d..929f200e5 100644 --- a/src/App/NetDaemon.App/Common/NetDaemonAppBase.cs +++ b/src/App/NetDaemon.App/Common/NetDaemonAppBase.cs @@ -19,7 +19,7 @@ public abstract class NetDaemonAppBase : INetDaemonAppBase /// /// A set of properties found in static analysis of code for each app /// - public static Dictionary> CompileTimeProperties { get; set; } = new Dictionary>(); + public static Dictionary> CompileTimeProperties { get; set; } = new(); /// /// The NetDaemonHost instance @@ -40,9 +40,9 @@ public abstract class NetDaemonAppBase : INetDaemonAppBase // This is declared as static since it will contain state shared globally - private static ConcurrentDictionary _global = new ConcurrentDictionary(); + private static ConcurrentDictionary _global = new(); - private readonly ConcurrentDictionary _attributes = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _attributes = new(); // To handle state saves max once at a time, internal due to tests private readonly Channel _lazyStoreStateQueue = @@ -120,7 +120,7 @@ public string Description /// The instance to compare public bool Equals([AllowNull] INetDaemonAppBase other) { - if (other is object && other.Id is object && this.Id is object && this.Id == other.Id) + if (other is not null && other.Id is not null && this.Id is not null && this.Id == other.Id) return true; return false; @@ -251,7 +251,7 @@ private async Task HandleLazyStorage() public async virtual ValueTask DisposeAsync() { _cancelSource.Cancel(); - if (_manageRuntimeInformationUpdatesTask is object) + if (_manageRuntimeInformationUpdatesTask is not null) await _manageRuntimeInformationUpdatesTask.ConfigureAwait(false); _daemonCallBacksForServiceCalls.Clear(); @@ -283,7 +283,7 @@ public void ListenServiceCall(string domain, string service, Func public void Log(LogLevel level, string message, params object[] param) { - if (param is object && param.Length > 0) + if (param is not null && param.Length > 0) { var result = param.Prepend(Id).ToArray(); Logger.Log(level, $" {{Id}}: {message}", result); @@ -300,7 +300,7 @@ public void Log(LogLevel level, string message, params object[] param) /// public void Log(LogLevel level, Exception exception, string message, params object[] param) { - if (param is object && param.Length > 0) + if (param is not null && param.Length > 0) { var result = param.Prepend(Id).ToArray(); Logger.Log(level, exception, $" {{Id}}: {message}", result); @@ -399,7 +399,7 @@ public void LogError(Exception exception, string message, params object[] param) /// public void SetAttribute(string attribute, object? value) { - if (value is object) + if (value is not null) { RuntimeInfo.AppAttributes[attribute] = value; } @@ -452,7 +452,7 @@ private async Task HandleUpdateRuntimeInformation() { _ = _daemon ?? throw new NullReferenceException($"{nameof(_daemon)} cant be null!"); - if (RuntimeInfo.LastErrorMessage is object) + if (RuntimeInfo.LastErrorMessage is not null) { RuntimeInfo.HasError = true; } diff --git a/src/App/NetDaemon.App/Common/Reactive/AppDaemonRxApp.cs b/src/App/NetDaemon.App/Common/Reactive/AppDaemonRxApp.cs index a321711f1..4a783b56b 100644 --- a/src/App/NetDaemon.App/Common/Reactive/AppDaemonRxApp.cs +++ b/src/App/NetDaemon.App/Common/Reactive/AppDaemonRxApp.cs @@ -67,10 +67,10 @@ public async override ValueTask DisposeAsync() // To end timers _cancelTimers.Cancel(); - if (_eventObservables is object) + if (_eventObservables is not null) _eventObservables!.Clear(); - if (_stateObservables is object) + if (_stateObservables is not null) _stateObservables!.Clear(); // Make sure we release all references so the apps can be diff --git a/src/App/NetDaemon.App/Common/Reactive/ObservableBase.cs b/src/App/NetDaemon.App/Common/Reactive/ObservableBase.cs index 9717c3026..214423161 100644 --- a/src/App/NetDaemon.App/Common/Reactive/ObservableBase.cs +++ b/src/App/NetDaemon.App/Common/Reactive/ObservableBase.cs @@ -81,7 +81,7 @@ private class UnsubscriberObservable : IDisposable public void Dispose() { - if (_observer is object) + if (_observer is not null) { _observers.TryRemove(_observer, out _); } diff --git a/src/App/NetDaemon.App/Common/Reactive/RxEntity.cs b/src/App/NetDaemon.App/Common/Reactive/RxEntity.cs index de18df928..10118100b 100644 --- a/src/App/NetDaemon.App/Common/Reactive/RxEntity.cs +++ b/src/App/NetDaemon.App/Common/Reactive/RxEntity.cs @@ -138,7 +138,7 @@ internal static string GetDomainFromEntity(string entity) /// Data to provide public void CallService(string service, dynamic? data = null) { - if (EntityIds is null || EntityIds is object && EntityIds.Count() == 0) + if (EntityIds is null || EntityIds is not null && EntityIds.Count() == 0) return; foreach (var entityId in EntityIds!) @@ -150,11 +150,11 @@ public void CallService(string service, dynamic? data = null) // Maske sure we make a copy since we reuse all info but entity id serviceData.CopyFrom(data); } - else if (data is object) + else if (data is not null) { // It is initialized with anonmous type new {transition=10} for example var expObject = ((object)data).ToExpandoObject(); - if (expObject is object) + if (expObject is not null) { serviceData.CopyFrom(expObject); } @@ -170,12 +170,12 @@ public void CallService(string service, dynamic? data = null) private void CallServiceOnEntity(string service, dynamic? attributes = null) { - if (EntityIds is null || EntityIds is object && EntityIds.Count() == 0) + if (EntityIds is null || EntityIds is not null && EntityIds.Count() == 0) return; dynamic? data = null; - if (attributes is object) + if (attributes is not null) { if (attributes is IDictionary == false) data = ((object)attributes).ToExpandoObject(); @@ -187,7 +187,7 @@ private void CallServiceOnEntity(string service, dynamic? attributes = null) { var serviceData = new FluentExpandoObject(); - if (data is object) + if (data is not null) { // Maske sure we make a copy since we reuse all info but entity id serviceData.CopyFrom(data); diff --git a/src/Daemon/NetDaemon.Daemon/Daemon/HttpHandler.cs b/src/Daemon/NetDaemon.Daemon/Daemon/HttpHandler.cs index 629f6118e..98a6a8a7c 100644 --- a/src/Daemon/NetDaemon.Daemon/Daemon/HttpHandler.cs +++ b/src/Daemon/NetDaemon.Daemon/Daemon/HttpHandler.cs @@ -71,7 +71,7 @@ public async Task PostJson(string url, object request, JsonSerializerOptions? op private void AddHeaders(HttpClient httpClient, (string, object)[] headers) { - if (headers is object && headers.Length > 0) + if (headers is not null && headers.Length > 0) { httpClient.DefaultRequestHeaders.Clear(); foreach (var (name, header) in headers) diff --git a/src/Daemon/NetDaemon.Daemon/Daemon/NetDaemonHost.cs b/src/Daemon/NetDaemon.Daemon/Daemon/NetDaemonHost.cs index 3424ecd58..6ba7d3023 100644 --- a/src/Daemon/NetDaemon.Daemon/Daemon/NetDaemonHost.cs +++ b/src/Daemon/NetDaemon.Daemon/Daemon/NetDaemonHost.cs @@ -49,7 +49,7 @@ public class NetDaemonHost : INetDaemonHost, IAsyncDisposable internal int InternalDelayTimeForTts = 2500; // internal so we can use for unittest - internal ConcurrentDictionary InternalState = new ConcurrentDictionary(); + internal ConcurrentDictionary InternalState = new(); private IInstanceDaemonApp? _appInstanceManager; @@ -62,7 +62,7 @@ public class NetDaemonHost : INetDaemonHost, IAsyncDisposable /// /// Currently running tasks for handling new events from HomeAssistant /// - private readonly List _eventHandlerTasks = new List(); + private readonly List _eventHandlerTasks = new(); private readonly IHassClient _hassClient; @@ -82,7 +82,7 @@ public class NetDaemonHost : INetDaemonHost, IAsyncDisposable private readonly Scheduler _scheduler; - private readonly List _supportedDomainsForTurnOnOff = new List + private readonly List _supportedDomainsForTurnOnOff = new() { "light", "switch", @@ -555,8 +555,11 @@ public void SetState(string entityId, dynamic state, dynamic? attributes = null) if (result != null) { EntityState entityState = result.Map(); - entityState.State = state; - entityState.Area = GetAreaForEntityId(entityState.EntityId); + entityState = entityState with + { + State = state, + Area = GetAreaForEntityId(entityState.EntityId) + }; InternalState[entityState.EntityId] = entityState; return entityState; } @@ -645,7 +648,7 @@ internal static bool FixStateTypes(HassStateChangedEventData stateData) if (stateData.NewState.State is null && stateData.OldState.State is null) return false; - if (stateData.NewState.State is object && stateData.OldState.State is object) + if (stateData.NewState.State is not null && stateData.OldState.State is not null) { Type? newStateType = stateData.NewState?.State?.GetType(); Type? oldStateType = stateData.OldState?.State?.GetType(); @@ -694,19 +697,19 @@ internal static bool FixStateTypes(HassStateChangedEventData stateData) internal string? GetAreaForEntityId(string entityId) { HassEntity? entity; - if (_hassEntities.TryGetValue(entityId, out entity) && entity is object) + if (_hassEntities.TryGetValue(entityId, out entity) && entity is not null) { - if (entity.DeviceId is object) + if (entity.DeviceId is not null) { // The entity is on a device HassDevice? device; - if (_hassDevices.TryGetValue(entity.DeviceId, out device) && device is object) + if (_hassDevices.TryGetValue(entity.DeviceId, out device) && device is not null) { - if (device.AreaId is object) + if (device.AreaId is not null) { // This device is in an area HassArea? area; - if (_hassAreas.TryGetValue(device.AreaId, out area) && area is object) + if (_hassAreas.TryGetValue(device.AreaId, out area) && area is not null) { return area.Name; } @@ -723,17 +726,17 @@ internal async Task RefreshInternalStatesAndSetArea() foreach (var device in await _hassClient.GetDevices().ConfigureAwait(false)) { - if (device is object && device.Id is object) + if (device is not null && device.Id is not null) _hassDevices[device.Id] = device; } foreach (var area in await _hassClient.GetAreas().ConfigureAwait(false)) { - if (area is object && area.Id is object) + if (area is not null && area.Id is not null) _hassAreas[area.Id] = area; } foreach (var entity in await _hassClient.GetEntities().ConfigureAwait(false)) { - if (entity is object && entity.EntityId is object) + if (entity is not null && entity.EntityId is not null) _hassEntities[entity.EntityId] = entity; } var hassStates = await _hassClient.GetAllStates(_cancelToken).ConfigureAwait(false); @@ -744,7 +747,10 @@ internal async Task RefreshInternalStatesAndSetArea() foreach (var key in initialStates.Keys) { var state = initialStates[key]; - state.Area = GetAreaForEntityId(state.EntityId); + state = state with + { + Area = GetAreaForEntityId(state.EntityId) + }; InternalState[key] = state; } } @@ -816,7 +822,8 @@ protected virtual async Task HandleNewEvent(HassEvent hassEvent, CancellationTok // Make sure we get the area name with the new state var newState = stateData!.NewState!.Map(); var oldState = stateData!.OldState!.Map(); - newState.Area = GetAreaForEntityId(newState.EntityId); + // TODO: refactor map to take area as input to avoid the copy + newState = newState with { Area = GetAreaForEntityId(newState.EntityId) }; InternalState[stateData.EntityId] = newState; var tasks = new List(); @@ -1304,7 +1311,7 @@ private async Task SetDependentState(string entityId, string state) { var app = _allAppInstances.Values.Where(n => n.EntityId == entityId).FirstOrDefault(); - if (app is object) + if (app is not null) { if (state == "off") { @@ -1325,7 +1332,7 @@ private async Task SetDependentState(string entityId, string state) foreach (var depOnId in app.Dependencies) { var depOnApp = _allAppInstances.Values.Where(n => n.Id == depOnId).FirstOrDefault(); - if (depOnApp is object) + if (depOnApp is not null) { await SetDependentState(depOnApp.EntityId, state).ConfigureAwait(false); @@ -1339,10 +1346,10 @@ private async Task SetDependentState(string entityId, string state) var entityAttributes = GetState(entityId)?.Attribute as IDictionary; - if (entityAttributes is object && entityAttributes.Count > 0) + if (entityAttributes is not null && entityAttributes.Count > 0) attributes = entityAttributes.Keys.Select(n => (n, entityAttributes[n])).ToList(); - if (attributes is object && attributes.Count > 0) + if (attributes is not null && attributes.Count > 0) await SetStateAsync(entityId, state, attributes.ToArray()).ConfigureAwait(false); else await SetStateAsync(entityId, state).ConfigureAwait(false); diff --git a/src/DaemonRunner/DaemonRunner/Service/API/WsHandler.cs b/src/DaemonRunner/DaemonRunner/Service/API/WsHandler.cs index e6f9cf027..9fba5afd3 100644 --- a/src/DaemonRunner/DaemonRunner/Service/API/WsHandler.cs +++ b/src/DaemonRunner/DaemonRunner/Service/API/WsHandler.cs @@ -20,7 +20,7 @@ namespace NetDaemon.Service.Api public class ApiWebsocketMiddleware { - private static ConcurrentDictionary _sockets = new ConcurrentDictionary(); + private static ConcurrentDictionary _sockets = new(); private readonly RequestDelegate _next; @@ -101,7 +101,7 @@ public async Task Invoke(HttpContext context) break; } - if (msg is object) + if (msg is not null) { switch (msg.Type) { @@ -132,7 +132,7 @@ public async Task Invoke(HttpContext context) }; // For first release we do not expose the token - if (tempResult.HomeAssistantSettings is object) + if (tempResult.HomeAssistantSettings is not null) { tempResult.HomeAssistantSettings.Token = ""; } @@ -152,7 +152,7 @@ public async Task Invoke(HttpContext context) _logger.LogDebug("App should not bee null."); continue; } - if (msg.ServiceData is object) + if (msg.ServiceData is not null) { var command = JsonSerializer.Deserialize(msg.ServiceData.Value.GetRawText(), _jsonOptions); if (command is null) @@ -160,7 +160,7 @@ public async Task Invoke(HttpContext context) _logger.LogDebug("Failed to read command."); continue; } - if (command.IsEnabled is object) + if (command.IsEnabled is not null) { if (command.IsEnabled ?? false) { diff --git a/src/DaemonRunner/DaemonRunner/Service/App/CodeGenerator.cs b/src/DaemonRunner/DaemonRunner/Service/App/CodeGenerator.cs index 1e011f1bc..00617de3c 100644 --- a/src/DaemonRunner/DaemonRunner/Service/App/CodeGenerator.cs +++ b/src/DaemonRunner/DaemonRunner/Service/App/CodeGenerator.cs @@ -197,7 +197,7 @@ public class CodeGenerator { name = "s_" + name; } - var hasEntityId = (s.Fields is object && s.Fields.Count(c => c.Field == "entity_id") > 0) ? true : false; + var hasEntityId = (s.Fields is not null && s.Fields.Count(c => c.Field == "entity_id") > 0) ? true : false; var entityAssignmentStatement = hasEntityId ? @"serviceData[""entity_id""] = EntityId;" : ""; var methodCode = $@"public void {name.ToCamelCase()}(dynamic? data=null) @@ -208,7 +208,7 @@ public class CodeGenerator {{ serviceData.CopyFrom(data); }} - else if (data is object) + else if (data is not null) {{ var expObject = ((object)data).ToExpandoObject(); serviceData.CopyFrom(expObject); diff --git a/src/DaemonRunner/DaemonRunner/Service/App/DaemonCompiler.cs b/src/DaemonRunner/DaemonRunner/Service/App/DaemonCompiler.cs index 0eb37a2e6..3c56b413e 100644 --- a/src/DaemonRunner/DaemonRunner/Service/App/DaemonCompiler.cs +++ b/src/DaemonRunner/DaemonRunner/Service/App/DaemonCompiler.cs @@ -43,7 +43,7 @@ public static (IEnumerable, CollectibleAssemblyLoadContext?) GetDaemonApps // Load the compiled apps var (compiledApps, compileErrorText) = GetCompiledApps(out alc, codeFolder, logger); - if (compiledApps is object) + if (compiledApps is not null) loadedApps.AddRange(compiledApps); else if (string.IsNullOrEmpty(compileErrorText) == false) logger.LogError(compileErrorText); @@ -290,7 +290,7 @@ private static void WarnIfExecuteIsMissing(SyntaxTree syntaxTree, CSharpCompilat // Now find top invocation to match whole expression InvocationExpressionSyntax topInvocationExpression = invocationExpression; - if (symbol is object && symbol.ContainingType.Name == "NetDaemonApp") + if (symbol is not null && symbol.ContainingType.Name == "NetDaemonApp") { var disableLogging = false; @@ -298,7 +298,7 @@ private static void WarnIfExecuteIsMissing(SyntaxTree syntaxTree, CSharpCompilat SyntaxNode? parentInvocationExpression = invocationExpression.Parent; - while (parentInvocationExpression is object) + while (parentInvocationExpression is not null) { if (parentInvocationExpression is MethodDeclarationSyntax) { diff --git a/src/Service/Program.cs b/src/Service/Program.cs index bc9cbebd5..31d239c33 100644 --- a/src/Service/Program.cs +++ b/src/Service/Program.cs @@ -43,16 +43,16 @@ private static async Task ReadHassioConfig() { var hassAddOnSettings = await JsonSerializer.DeserializeAsync(File.OpenRead(HassioConfigPath)).ConfigureAwait(false); - if (hassAddOnSettings?.LogLevel is object) + if (hassAddOnSettings?.LogLevel is not null) SerilogConfigurator.SetMinimumLogLevel(hassAddOnSettings.LogLevel); - if (hassAddOnSettings?.GenerateEntitiesOnStart is object) + if (hassAddOnSettings?.GenerateEntitiesOnStart is not null) Environment.SetEnvironmentVariable("NETDAEMON__GENERATEENTITIES", hassAddOnSettings.GenerateEntitiesOnStart.ToString()); - if (hassAddOnSettings?.LogMessages is object && hassAddOnSettings.LogMessages == true) + if (hassAddOnSettings?.LogMessages is not null && hassAddOnSettings.LogMessages == true) Environment.SetEnvironmentVariable("HASSCLIENT_MSGLOGLEVEL", "Default"); - if (hassAddOnSettings?.ProjectFolder is object && string.IsNullOrEmpty(hassAddOnSettings.ProjectFolder) == false) + if (hassAddOnSettings?.ProjectFolder is not null && string.IsNullOrEmpty(hassAddOnSettings.ProjectFolder) == false) Environment.SetEnvironmentVariable("NETDAEMON__PROJECTFOLDER", hassAddOnSettings.ProjectFolder); // We are in Hassio so hard code the path diff --git a/tests/NetDaemon.Daemon.Tests/Daemon/HttpHandlerMock.cs b/tests/NetDaemon.Daemon.Tests/Daemon/HttpHandlerMock.cs index bb6fc8204..8f9225ecd 100644 --- a/tests/NetDaemon.Daemon.Tests/Daemon/HttpHandlerMock.cs +++ b/tests/NetDaemon.Daemon.Tests/Daemon/HttpHandlerMock.cs @@ -64,7 +64,7 @@ protected override async Task SendAsync(HttpRequestMessage { var responseMessage = new HttpResponseMessage(_StatusCode); - if (request is object && request.Content is object) + if (request is not null && request.Content is not null) _requestContent = await request.Content.ReadAsStringAsync().ConfigureAwait(false); responseMessage.Content = new ByteArrayContent(Encoding.ASCII.GetBytes(_response)); diff --git a/tests/NetDaemon.Daemon.Tests/HassClientMock.cs b/tests/NetDaemon.Daemon.Tests/HassClientMock.cs index ede3c99e3..94106c69e 100644 --- a/tests/NetDaemon.Daemon.Tests/HassClientMock.cs +++ b/tests/NetDaemon.Daemon.Tests/HassClientMock.cs @@ -17,8 +17,8 @@ public class HassClientMock : Mock internal HassAreas Areas = new HassAreas(); internal HassDevices Devices = new HassDevices(); internal HassEntities Entities = new HassEntities(); - internal ConcurrentQueue FakeEvents = new ConcurrentQueue(); - internal ConcurrentDictionary FakeStates = new ConcurrentDictionary(); + internal ConcurrentQueue FakeEvents = new(); + internal ConcurrentDictionary FakeStates = new(); public HassClientMock() { #pragma warning disable 8619, 8620 diff --git a/tests/NetDaemon.Daemon.Tests/LoggerMock.cs b/tests/NetDaemon.Daemon.Tests/LoggerMock.cs index 4c8429f21..879f3ead2 100644 --- a/tests/NetDaemon.Daemon.Tests/LoggerMock.cs +++ b/tests/NetDaemon.Daemon.Tests/LoggerMock.cs @@ -13,10 +13,10 @@ public LoggerMock() } public ILoggerFactory LoggerFactory => MockLoggerFactory.Object; - public Mock MockLoggerFactory { get; } = new Mock(); + public Mock MockLoggerFactory { get; } = new(); public ILogger Logger => MockLogger.Object; - public Mock MockLogger { get; } = new Mock(); + public Mock MockLogger { get; } = new(); /// /// Assert if the log has been used at times diff --git a/tests/NetDaemon.Test/HassClientMock.cs b/tests/NetDaemon.Test/HassClientMock.cs index 7cc10ffa2..c0a258f33 100644 --- a/tests/NetDaemon.Test/HassClientMock.cs +++ b/tests/NetDaemon.Test/HassClientMock.cs @@ -17,8 +17,8 @@ public class HassClientMock : Mock internal HassAreas Areas = new HassAreas(); internal HassDevices Devices = new HassDevices(); internal HassEntities Entities = new HassEntities(); - internal ConcurrentQueue FakeEvents = new ConcurrentQueue(); - internal ConcurrentDictionary FakeStates = new ConcurrentDictionary(); + internal ConcurrentQueue FakeEvents = new(); + internal ConcurrentDictionary FakeStates = new(); /// /// Default constructor diff --git a/tests/NetDaemon.Test/HttpHandlerMock.cs b/tests/NetDaemon.Test/HttpHandlerMock.cs index 3cca9fb3f..969bcff33 100644 --- a/tests/NetDaemon.Test/HttpHandlerMock.cs +++ b/tests/NetDaemon.Test/HttpHandlerMock.cs @@ -64,7 +64,7 @@ protected override async Task SendAsync(HttpRequestMessage { var responseMessage = new HttpResponseMessage(_StatusCode); - if (request is object && request.Content is object) + if (request is not null && request.Content is not null) _requestContent = await request.Content.ReadAsStringAsync().ConfigureAwait(false); responseMessage.Content = new ByteArrayContent(Encoding.ASCII.GetBytes(_response)); diff --git a/tests/NetDaemon.Test/LoggerMock.cs b/tests/NetDaemon.Test/LoggerMock.cs index f9aea58d5..ee4c19fb3 100644 --- a/tests/NetDaemon.Test/LoggerMock.cs +++ b/tests/NetDaemon.Test/LoggerMock.cs @@ -13,10 +13,10 @@ public LoggerMock() } public ILoggerFactory LoggerFactory => MockLoggerFactory.Object; - public Mock MockLoggerFactory { get; } = new Mock(); + public Mock MockLoggerFactory { get; } = new(); public ILogger Logger => MockLogger.Object; - public Mock MockLogger { get; } = new Mock(); + public Mock MockLogger { get; } = new(); /// /// Assert if the log has been used at times