Skip to content

Commit

Permalink
More refactorings .net 5 analyzers
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real committed Dec 26, 2020
1 parent 3402d6d commit d9e8c40
Show file tree
Hide file tree
Showing 15 changed files with 225 additions and 105 deletions.
7 changes: 7 additions & 0 deletions .linting/roslynator.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,14 @@ Just add ruleset file to a solution and open it.

<!-- Specify default action that should be applied to a specified analyzer. -->
<Rule Id="RCS0044" Action="None" />
<Rule Id="RCS1308" Action="None" />
<Rule Id="CA1014" Action="None" />
<Rule Id="CA1308" Action="None" />
<Rule Id="CA1054" Action="None" />
<Rule Id="CA1716" Action="None" />
<!-- Lots of catching rare null pointer exceptions in properties. Might refactor those in the future -->
<Rule Id="CA1065" Action="None" />


</Rules>

Expand Down
8 changes: 8 additions & 0 deletions .vscode/daemon.code-snippets
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@
// "description": "Log output to console"
// }
{
"nullcheck": {
"scope": "csharp",
"prefix": "nullcheck",
"body": [
"_ = $1 ??",
" throw new NetDaemonArgumentNullException(nameof($1));"
]
},
"fact": {
"scope": "csharp",
"prefix": "fact",
Expand Down
5 changes: 4 additions & 1 deletion src/Daemon/NetDaemon.Daemon/Daemon/CodeManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
Expand Down Expand Up @@ -31,6 +32,7 @@ public CodeManager(IEnumerable<Type> daemonAppTypes, ILogger logger, IYamlConfig
_yamlConfig = yamlConfig;
}

[SuppressMessage("", "CA1065")]
public int Count => _loadedDaemonApps?.Count() ?? throw new NetDaemonNullReferenceException("_loadedDaemonApps cannot be null");

// Internal for testing
Expand All @@ -57,7 +59,8 @@ public IEnumerable<INetDaemonAppBase> InstanceDaemonApps()
{
try
{
var yamlAppConfig = new YamlAppConfig(_loadedDaemonApps, File.OpenText(file), _yamlConfig, file);
using var fileReader = File.OpenText(file);
var yamlAppConfig = new YamlAppConfig(_loadedDaemonApps, fileReader, _yamlConfig, file);

foreach (var appInstance in yamlAppConfig.Instances)
{
Expand Down
17 changes: 14 additions & 3 deletions src/Daemon/NetDaemon.Daemon/Daemon/Config/ConfigExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System.Reflection;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using NetDaemon.Common.Exceptions;

[assembly: InternalsVisibleTo("NetDaemon.Daemon.Tests")]

Expand All @@ -15,6 +17,9 @@ public static class TaskExtensions
{
public static async Task InvokeAsync(this MethodInfo mi, object? obj, params object?[]? parameters)
{
_ = mi ??
throw new NetDaemonArgumentNullException(nameof(mi));

dynamic? awaitable = mi.Invoke(obj, parameters);
if (awaitable != null)
await awaitable.ConfigureAwait(false);
Expand All @@ -25,6 +30,9 @@ public static class ConfigStringExtensions
{
public static string ToPythonStyle(this string str)
{
_ = str ??
throw new NetDaemonArgumentNullException(nameof(str));

var build = new StringBuilder(str.Length);
bool isStart = true;
foreach (char c in str)
Expand All @@ -33,13 +41,16 @@ public static string ToPythonStyle(this string str)
build.Append('_');
else
isStart = false;
build.Append(char.ToLower(c));
build.Append(char.ToLower(c, CultureInfo.InvariantCulture));
}
return build.ToString();
}

public static string ToCamelCase(this string str)
{
_ = str ??
throw new NetDaemonArgumentNullException(nameof(str));

var build = new StringBuilder();
bool nextIsUpper = false;
bool isFirstCharacter = true;
Expand All @@ -51,7 +62,7 @@ public static string ToCamelCase(this string str)
continue;
}

build.Append(nextIsUpper || isFirstCharacter ? char.ToUpper(c) : c);
build.Append(nextIsUpper || isFirstCharacter ? char.ToUpper(c, CultureInfo.InvariantCulture) : c);
nextIsUpper = false;
isFirstCharacter = false;
}
Expand Down
17 changes: 11 additions & 6 deletions src/Daemon/NetDaemon.Daemon/Daemon/Config/YamlAppConfig.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using NetDaemon.Common;
Expand All @@ -26,6 +27,8 @@ public YamlAppConfig(IEnumerable<Type> types, TextReader reader, IYamlConfig yam
_yamlFilePath = yamlFilePath;
}

[SuppressMessage("", "CA1508")]
[SuppressMessage("", "CA1065")]
public IEnumerable<INetDaemonAppBase> Instances
{
get
Expand Down Expand Up @@ -59,7 +62,7 @@ public IEnumerable<INetDaemonAppBase> Instances
}
}
}
catch (System.Exception e)
catch (Exception e)
{
throw new NetDaemonException($"Error instancing application {appId}", e);
}
Expand All @@ -74,10 +77,10 @@ public IEnumerable<INetDaemonAppBase> Instances
YamlMappingNode appNode,
string? appId)
{
var netDaemonApp = (INetDaemonAppBase?)Activator.CreateInstance(netDaemonAppType);
_ = appNode ??
throw new NetDaemonArgumentNullException(nameof(appNode));

if (netDaemonApp == null)
return null;
var netDaemonApp = (INetDaemonAppBase?)Activator.CreateInstance(netDaemonAppType);

foreach (KeyValuePair<YamlNode, YamlNode> entry in appNode.Children)
{
Expand Down Expand Up @@ -106,7 +109,8 @@ public IEnumerable<INetDaemonAppBase> Instances
return netDaemonApp;
}

private object? InstanceProperty(Object? parent, Type instanceType, YamlNode node)
[SuppressMessage("", "CA1508")] // Weird bug that this should not warn!
private object? InstanceProperty(object? parent, Type instanceType, YamlNode node)
{
if (node.NodeType == YamlNodeType.Scalar)
{
Expand Down Expand Up @@ -197,7 +201,8 @@ private void ReplaceSecretIfExists(YamlScalarNode scalarNode)
{
return null;
}
return ((YamlScalarNode)classChild.Value)?.Value?.ToLowerInvariant();
var scalarNode = (YamlScalarNode)classChild.Value;
return scalarNode.Value?.ToLowerInvariant();
}
}
}
13 changes: 10 additions & 3 deletions src/Daemon/NetDaemon.Daemon/Daemon/Config/YamlConfig.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Options;
Expand All @@ -24,7 +25,11 @@ public class YamlConfig : IYamlConfig

public YamlConfig(IOptions<NetDaemonSettings> netDaemonSettings)
{
_ = netDaemonSettings ??
throw new NetDaemonArgumentNullException(nameof(netDaemonSettings));

_configFolder = netDaemonSettings.Value.GetAppSourceDirectory();

_secrets = GetAllSecretsFromPath(_configFolder);
}

Expand Down Expand Up @@ -53,9 +58,11 @@ public IEnumerable<string> GetAllConfigFilePaths()

internal static Dictionary<string, string> GetSecretsFromSecretsYaml(string file)
{
return GetSecretsFromSecretsYaml(File.OpenText(file));
using var fileReader = File.OpenText(file);
return GetSecretsFromSecretsYaml(fileReader);
}

[SuppressMessage("", "CA1508")] // TODO: Need to refactor this
internal static Dictionary<string, string> GetSecretsFromSecretsYaml(TextReader reader)
{
var result = new Dictionary<string, string>();
Expand Down Expand Up @@ -94,8 +101,8 @@ public IEnumerable<string> GetAllConfigFilePaths()

if (!result.ContainsKey(fileDirectory))
{
var secretsFromFile = GetSecretsFromSecretsYaml(file);
result[fileDirectory] = secretsFromFile;
result[fileDirectory] = (Dictionary<string, string>?)GetSecretsFromSecretsYaml(file) ??
new Dictionary<string, string>();
}
}
return result;
Expand Down
11 changes: 11 additions & 0 deletions src/Daemon/NetDaemon.Daemon/Daemon/Config/YamlExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using NetDaemon.Common.Exceptions;
using YamlDotNet.RepresentationModel;

[assembly: InternalsVisibleTo("NetDaemon.Daemon.Tests")]
Expand All @@ -25,14 +26,24 @@ public static class YamlExtensions
{
public static PropertyInfo? GetYamlProperty(this Type type, string propertyName)
{
_ = type ??
throw new NetDaemonArgumentNullException(nameof(type));

// Lets try convert from python style to CamelCase

var prop = type.GetProperty(propertyName) ?? type.GetProperty(propertyName.ToCamelCase());
return prop;
}

public static object? ToObject(this YamlScalarNode node, Type valueType)
{
_ = valueType ??
throw new NetDaemonArgumentNullException(nameof(valueType));
_ = node ??
throw new NetDaemonArgumentNullException(nameof(node));

Type? underlyingNullableType = Nullable.GetUnderlyingType(valueType);

if (underlyingNullableType != null)
{
// It is nullable type
Expand Down
28 changes: 18 additions & 10 deletions src/Daemon/NetDaemon.Daemon/Daemon/DaemonAppExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NetDaemon.Common;
using NetDaemon.Common.Exceptions;
using NetDaemon.Common.Fluent;
using NetDaemon.Common.Reactive;
using NetDaemon.Daemon.Config;
Expand All @@ -16,9 +18,15 @@ namespace NetDaemon.Daemon
{
public static class DaemonAppExtensions
{
public static async Task HandleAttributeInitialization(this INetDaemonAppBase netDaemonApp, INetDaemon _daemon)
public static async Task HandleAttributeInitialization(this INetDaemonAppBase netDaemonApp, INetDaemon daemon)
{
_ = daemon ??
throw new NetDaemonArgumentNullException(nameof(daemon));
_ = netDaemonApp ??
throw new NetDaemonArgumentNullException(nameof(netDaemonApp));

var netDaemonAppType = netDaemonApp.GetType();

foreach (var method in netDaemonAppType.GetMethods())
{
foreach (var attr in method.GetCustomAttributes(false))
Expand All @@ -28,11 +36,11 @@ public static async Task HandleAttributeInitialization(this INetDaemonAppBase ne
switch (attr)
{
case HomeAssistantServiceCallAttribute:
await HandleServiceCallAttribute(_daemon, daemonApp, method, true).ConfigureAwait(false);
await HandleServiceCallAttribute(daemon, daemonApp, method, true).ConfigureAwait(false);
break;

case HomeAssistantStateChangedAttribute hassStateChangedAttribute:
HandleStateChangedAttribute(_daemon, hassStateChangedAttribute, daemonApp, method);
HandleStateChangedAttribute(daemon, hassStateChangedAttribute, daemonApp, method);
break;
}
}
Expand All @@ -41,7 +49,7 @@ public static async Task HandleAttributeInitialization(this INetDaemonAppBase ne
switch (attr)
{
case HomeAssistantServiceCallAttribute:
await HandleServiceCallAttribute(_daemon, daemonRxApp, method, false).ConfigureAwait(false);
await HandleServiceCallAttribute(daemon, daemonRxApp, method, false).ConfigureAwait(false);
break;
}
}
Expand Down Expand Up @@ -91,6 +99,7 @@ private static (bool, string) CheckIfStateChangedSignatureIsOk(MethodInfo method
return (true, string.Empty);
}

[SuppressMessage("", "CA1031")]
private static async Task HandleServiceCallAttribute(INetDaemon _daemon, NetDaemonAppBase netDaemonApp, MethodInfo method, bool async = true)
{
var (signatureOk, err) = CheckIfServiceCallSignatureIsOk(method, async);
Expand Down Expand Up @@ -121,6 +130,7 @@ private static async Task HandleServiceCallAttribute(INetDaemon _daemon, NetDaem
});
}

[SuppressMessage("", "CA1031")]
private static void HandleStateChangedAttribute(
INetDaemon _daemon,
HomeAssistantStateChangedAttribute hassStateChangedAttribute,
Expand All @@ -141,16 +151,14 @@ MethodInfo method
{
try
{
if (hassStateChangedAttribute.To != null)
if (hassStateChangedAttribute.To != null && (dynamic)hassStateChangedAttribute.To != to?.State)
{
if ((dynamic)hassStateChangedAttribute.To != to?.State)
return;
return;
}
if (hassStateChangedAttribute.From != null)
if (hassStateChangedAttribute.From != null && (dynamic)hassStateChangedAttribute.From != from?.State)
{
if ((dynamic)hassStateChangedAttribute.From != from?.State)
return;
return;
}
// If we don´t accept all changes in the state change
Expand Down
16 changes: 10 additions & 6 deletions src/Daemon/NetDaemon.Daemon/Daemon/HttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ public HttpClient CreateHttpClient(string? name = null)
{
_ = _httpClientFactory ?? throw new NetDaemonNullReferenceException("No IHttpClientFactory provided, please add AddHttpClient() in configure services!");

var httpClient = _httpClientFactory.CreateClient();
using var httpClient = _httpClientFactory.CreateClient();

AddHeaders(httpClient, headers);

var streamTask = httpClient.GetStreamAsync(url)
var streamTask = httpClient.GetStreamAsync(new Uri(url))
?? throw new NetDaemonException($"Unexpected, nothing returned from {url}");

return await JsonSerializer.DeserializeAsync<T>(await streamTask.ConfigureAwait(false), options).ConfigureAwait(false);
Expand All @@ -40,14 +40,16 @@ public HttpClient CreateHttpClient(string? name = null)
public async Task<T?> PostJson<T>(string url, object request, JsonSerializerOptions? options = null, params (string, object)[] headers)
{
_ = _httpClientFactory ?? throw new NetDaemonNullReferenceException("No IHttpClientFactory provided, please add AddHttpClient() in configure services!");
_ = request ?? throw new NetDaemonArgumentNullException(nameof(request));

var httpClient = _httpClientFactory.CreateClient();
using var httpClient = _httpClientFactory.CreateClient();

AddHeaders(httpClient, headers);

var bytesToPost = JsonSerializer.SerializeToUtf8Bytes(request, request.GetType(), options);
using var content = new ByteArrayContent(bytesToPost);

var response = await httpClient.PostAsync(url, new ByteArrayContent(bytesToPost)).ConfigureAwait(false);
var response = await httpClient.PostAsync(new Uri(url), content).ConfigureAwait(false);

response.EnsureSuccessStatusCode();

Expand All @@ -58,14 +60,16 @@ public HttpClient CreateHttpClient(string? name = null)
public async Task PostJson(string url, object request, JsonSerializerOptions? options = null, params (string, object)[] headers)
{
_ = _httpClientFactory ?? throw new NetDaemonNullReferenceException("No IHttpClientFactory provided, please add AddHttpClient() in configure services!");
_ = request ?? throw new NetDaemonArgumentNullException(nameof(request));

var httpClient = _httpClientFactory.CreateClient();
using var httpClient = _httpClientFactory.CreateClient();

AddHeaders(httpClient, headers);

var bytesToPost = JsonSerializer.SerializeToUtf8Bytes(request, request.GetType(), options);
using var content = new ByteArrayContent(bytesToPost);

var response = await httpClient.PostAsync(url, new ByteArrayContent(bytesToPost)).ConfigureAwait(false);
var response = await httpClient.PostAsync(new Uri(url), content).ConfigureAwait(false);

response.EnsureSuccessStatusCode();
}
Expand Down
Loading

0 comments on commit d9e8c40

Please sign in to comment.