Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C# 11 Updates and simplifications #445

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 9 additions & 20 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -103,23 +103,12 @@ dotnet_naming_symbols.constant_fields.required_modifiers = const
dotnet_naming_style.prefix_underscore.capitalization = camel_case
dotnet_naming_style.prefix_underscore.required_prefix = _

# CA1027: Mark enums with FlagsAttribute
dotnet_diagnostic.CA1027.severity = none

# CA1031: Do not catch general exception types
dotnet_diagnostic.CA1031.severity = none

# CA1034: Nested types should not be visible
dotnet_diagnostic.CA1034.severity = none

# CA1063: Implement IDisposable Correctly
dotnet_diagnostic.CA1063.severity = none

# CA1810: Initialize reference type static fields inline
dotnet_diagnostic.CA1810.severity = none

# CA1819: Properties should not return arrays
dotnet_diagnostic.CA1819.severity = none

# CA1822: Mark members as static
dotnet_diagnostic.CA1822.severity = none
dotnet_diagnostic.CA1027.severity = none # CA1027: Mark enums with FlagsAttribute
dotnet_diagnostic.CA1031.severity = none # CA1031: Do not catch general exception types
dotnet_diagnostic.CA1034.severity = none # CA1034: Nested types should not be visible
dotnet_diagnostic.CA1063.severity = none # CA1063: Implement IDisposable Correctly
dotnet_diagnostic.CA1810.severity = none # CA1810: Initialize reference type static fields inline
dotnet_diagnostic.CA1819.severity = none # CA1819: Properties should not return arrays
dotnet_diagnostic.CA1822.severity = none # CA1822: Mark members as static

dotnet_diagnostic.IDE0130.severity = none # IDE0130: Namespace does not match folder structure
40 changes: 40 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="BuildBundlerMinifier" Version="3.2.449"/>
<PackageVersion Include="BuildWebCompiler" Version="1.12.405" />
<PackageVersion Include="Dapper" Version="2.1.35" />
<PackageVersion Include="Enums.NET" Version="5.0.0" />
<PackageVersion Include="Jil" Version="2.17.0" />
<PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="8.0.10" />
<PackageVersion Include="Microsoft.Data.SqlClient" Version="5.2.2" />
<PackageVersion Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.2" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.1" />
<PackageVersion Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="8.1.2" />
<PackageVersion Include="Microsoft.Net.Http.Headers" Version="8.0.10" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="MiniProfiler.AspNetCore.Mvc" Version="4.5.4" />
<PackageVersion Include="MiniProfiler.Shared" Version="4.5.4" />
<PackageVersion Include="Sigil" Version="5.0.0" />
<PackageVersion Include="StackExchange.Exceptional.AspNetCore" Version="3.0.1" />
<PackageVersion Include="StackExchange.Exceptional.Shared" Version="3.0.1" />
<PackageVersion Include="StackExchange.Redis" Version="2.8.22" />
<PackageVersion Include="StackExchange.Utils.Http" Version="0.3.48" />
<PackageVersion Include="System.DirectoryServices" Version="8.0.0" />
<PackageVersion Include="System.DirectoryServices.AccountManagement" Version="8.0.1" />
<PackageVersion Include="System.Management" Version="8.0.0" />
<PackageVersion Include="System.Runtime.Caching" Version="8.0.1" />
<PackageVersion Include="xunit" Version="2.9.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.8.2" />
</ItemGroup>
<ItemGroup>
<GlobalPackageReference Condition="'$(TargetFramework)'!='net462'" Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3" />
<GlobalPackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" />
<GlobalPackageReference Include="Nerdbank.GitVersioning" Version="3.6.146" />
</ItemGroup>
</Project>
5 changes: 3 additions & 2 deletions Opserver.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29021.104
# Visual Studio Version 17
VisualStudioVersion = 17.12.35521.163 d17.12
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Opserver.Core", "src\Opserver.Core\Opserver.Core.csproj", "{C58AFF99-F4D9-4A83-866E-18DA0A633F6B}"
EndProject
Expand All @@ -12,6 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
appveyor.yml = appveyor.yml
azure-pipelines.yml = azure-pipelines.yml
Build.bat = Build.bat
Directory.Packages.props = Directory.Packages.props
global.json = global.json
nuget.config = nuget.config
readme.md = readme.md
Expand Down
1 change: 0 additions & 1 deletion nuget.config
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
<configuration>
<packageSources>
<clear />
<add key="MyGet: Stack Overflow" value="https://www.myget.org/F/stackoverflow/api/v3/index.json" />
<add key="NuGet" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
7 changes: 1 addition & 6 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<LangVersion>8.0</LangVersion>
<LangVersion>11.0</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Opserver.ruleset</CodeAnalysisRuleSet>
<!--<GenerateDocumentationFile>true</GenerateDocumentationFile>-->
Expand All @@ -16,15 +16,10 @@
<DefaultLanguage>en-US</DefaultLanguage>
<IncludeSymbols>false</IncludeSymbols>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<!--<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>-->
</PropertyGroup>
<!-- File nesting! -->
<ItemGroup>
<ProjectCapability Include="DynamicDependentFile" />
<ProjectCapability Include="DynamicFileNesting" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Nerdbank.GitVersioning" Version="3.5.119" PrivateAssets="all" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All"/>
</ItemGroup>
</Project>
4 changes: 2 additions & 2 deletions src/Opserver.Core/Data/Cache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class Cache<T> : Cache where T : class
private int _hasData;
internal override object InnerCache => Data;
public override Type Type => typeof (T);
private readonly SemaphoreSlim _pollSemaphoreSlim = new SemaphoreSlim(1);
private readonly SemaphoreSlim _pollSemaphoreSlim = new(1);

public override string InventoryDescription
{
Expand Down Expand Up @@ -116,7 +116,7 @@ private async Task<T> UpdateAsync(bool force)
private string MiniProfilerDescription { get; }

// ReSharper disable once StaticMemberInGenericType
private static readonly MiniProfilerBaseOptions _profilerOptions = new MiniProfilerBaseOptions
private static readonly MiniProfilerBaseOptions _profilerOptions = new()
{
Storage = new NullStorage(),
ProfilerProvider = new DefaultProfilerProvider()
Expand Down
19 changes: 6 additions & 13 deletions src/Opserver.Core/Data/CloudFlare/CloudFlareAPI.Zones.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public partial class CloudflareAPI
public Cache<List<CloudflareZone>> Zones =>
_zones ??= GetCloudflareCache(5.Minutes(), () => Get<List<CloudflareZone>>("zones"));

private static readonly NameValueCollection _dnsRecordFetchParams = new NameValueCollection
private static readonly NameValueCollection _dnsRecordFetchParams = new()
{
["per_page"] = "100"
};
Expand Down Expand Up @@ -45,19 +45,12 @@ public CloudflareZone GetZoneFromUrl(string url) =>
/// </summary>
/// <param name="record">The DNS record to get an IP for</param>
/// <returns>Root IP Addresses for this record.</returns>
public List<IPAddress> GetIPs(CloudflareDNSRecord record)
public List<IPAddress> GetIPs(CloudflareDNSRecord record) => record.Type switch
{
switch (record.Type)
{
case DNSRecordType.A:
case DNSRecordType.AAAA:
return new List<IPAddress> { record.IPAddress };
case DNSRecordType.CNAME:
return GetIPs(record.Content);
default:
return null;
}
}
DNSRecordType.A or DNSRecordType.AAAA => new List<IPAddress> { record.IPAddress },
DNSRecordType.CNAME => GetIPs(record.Content),
_ => null,
};

/// <summary>
/// Get the IP Addresses for a given fully qualified host (star records not supported), even through CNAME chains.
Expand Down
4 changes: 2 additions & 2 deletions src/Opserver.Core/Data/CloudFlare/CloudFlareModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public CloudflareModule(IConfiguration config, PollingService poller) : base(con
public List<CloudflareDNSRecord> GetDNSRecords(CloudflareZone zone) =>
API.DNSRecords.Data?.Where(r => r.ZoneId == zone.Id).ToList() ?? new List<CloudflareDNSRecord>();

private static readonly NameValueCollection _purgeAllParams = new NameValueCollection
private static readonly NameValueCollection _purgeAllParams = new()
{
["purge_everything"] = "true"
};
Expand Down Expand Up @@ -69,7 +69,7 @@ public IEnumerable<string> GetMaskedIPs(List<IPAddress> addresses)
}
}

private readonly ConcurrentDictionary<IPAddress, string> _cached = new ConcurrentDictionary<IPAddress, string>();
private readonly ConcurrentDictionary<IPAddress, string> _cached = new();

private string GetMaskedIP(IPAddress address)
{
Expand Down
27 changes: 7 additions & 20 deletions src/Opserver.Core/Data/CloudFlare/CloudFlareResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,27 +94,14 @@ public class CloudflareZone : IMonitorStatus
[DataMember(Name = "permissions")]
public List<string> Permissons { get; set; }

public MonitorStatus MonitorStatus
public MonitorStatus MonitorStatus => Status switch
{
get
{
switch (Status)
{
case ZoneStatus.Active:
return MonitorStatus.Good;
case ZoneStatus.Pending:
case ZoneStatus.Initializing:
case ZoneStatus.Moved:
return MonitorStatus.Warning;
case ZoneStatus.Deleted:
return MonitorStatus.Critical;
case ZoneStatus.Deactivated:
return MonitorStatus.Maintenance;
default:
return MonitorStatus.Unknown;
}
}
}
ZoneStatus.Active => MonitorStatus.Good,
ZoneStatus.Pending or ZoneStatus.Initializing or ZoneStatus.Moved => MonitorStatus.Warning,
ZoneStatus.Deleted => MonitorStatus.Critical,
ZoneStatus.Deactivated => MonitorStatus.Maintenance,
_ => MonitorStatus.Unknown,
};

public string MonitorStatusReason => "Current status: " + Status;
}
Expand Down
3 changes: 2 additions & 1 deletion src/Opserver.Core/Data/Dashboard/HardwareSummary.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;

namespace Opserver.Data.Dashboard
{
Expand Down Expand Up @@ -48,7 +49,7 @@ public int? Label
if (Bank == null) return null;
if (Name.Length > Bank.Length)
{
if (int.TryParse(Name.Substring(Bank.Length), out int position))
if (int.TryParse(Name.AsSpan(Bank.Length), out int position))
{
_label = position;
}
Expand Down
8 changes: 4 additions & 4 deletions src/Opserver.Core/Data/Dashboard/Interface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public partial class Interface : IMonitorStatus
public string Alias { get; internal set; }
public string TypeDescription { get; internal set; }
public string PhysicalAddress { get; internal set; }
public bool IsTeam => TeamMembers?.Any() ?? false;
public bool IsTeam => TeamMembers?.Count > 0;
public bool IsUnwatched { get; internal set; }

public NodeStatus Status { get; internal set; }
Expand All @@ -40,7 +40,7 @@ public partial class Interface : IMonitorStatus
// TODO: Implement
public string MonitorStatusReason => null;

private static readonly Dictionary<string, string> _prettyNameReplacements = new Dictionary<string, string>
private static readonly Dictionary<string, string> _prettyNameReplacements = new()
{
["Microsoft Network Adapter Multiplexor Driver"] = "Microsoft Team",
["Quad Port Server Adapter"] = "Quad Port SA",
Expand Down Expand Up @@ -72,7 +72,7 @@ public string PrettySpeed
get {
if (!Speed.HasValue)
{
if (!(TeamMembers?.Any() ?? false))
if (!(TeamMembers?.Count > 0))
{
return "n/a";
}
Expand All @@ -91,7 +91,7 @@ public string PrettySpeed

public string PrettyMAC =>
PhysicalAddress?.Length == 12
? $"{PhysicalAddress.Substring(0, 2)}-{PhysicalAddress.Substring(2, 2)}-{PhysicalAddress.Substring(4, 2)}-{PhysicalAddress.Substring(6, 2)}-{PhysicalAddress.Substring(8, 2)}-{PhysicalAddress.Substring(10, 2)}"
? $"{PhysicalAddress[..2]}-{PhysicalAddress.Substring(2, 2)}-{PhysicalAddress.Substring(4, 2)}-{PhysicalAddress.Substring(6, 2)}-{PhysicalAddress.Substring(8, 2)}-{PhysicalAddress.Substring(10, 2)}"
: PhysicalAddress;

internal bool IsLikelyPrimary(Regex pattern) => pattern != null
Expand Down
2 changes: 1 addition & 1 deletion src/Opserver.Core/Data/Dashboard/Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ public NodeService GetService(string id)
return null;
}

private static readonly List<IPNet> EmptyIPs = new List<IPNet>();
private static readonly List<IPNet> EmptyIPs = new();

public List<IPNet> IPs => Interfaces?.SelectMany(i => i.IPs).ToList() ?? EmptyIPs;

Expand Down
35 changes: 10 additions & 25 deletions src/Opserver.Core/Data/Dashboard/NodeStatus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,30 +27,15 @@ public enum NodeStatus

public static class ServerStatusExtensions
{
public static MonitorStatus ToMonitorStatus(this NodeStatus status)
public static MonitorStatus ToMonitorStatus(this NodeStatus status) => status switch
{
switch (status)
{
case NodeStatus.Unmanaged:
return MonitorStatus.Maintenance;
case NodeStatus.Active:
case NodeStatus.External:
case NodeStatus.Up:
case NodeStatus.Shutdown:
return MonitorStatus.Good;
case NodeStatus.Down:
case NodeStatus.Critical:
return MonitorStatus.Critical;
case NodeStatus.Unreachable:
case NodeStatus.Warning:
case NodeStatus.PartlyAvailable:
case NodeStatus.Unconfirmed:
return MonitorStatus.Warning;
//case NodeStatus.Inactive:
//case NodeStatus.Unplugged:
default:
return MonitorStatus.Unknown;
}
}
NodeStatus.Unmanaged => MonitorStatus.Maintenance,
NodeStatus.Active or NodeStatus.External or NodeStatus.Up or NodeStatus.Shutdown => MonitorStatus.Good,
NodeStatus.Down or NodeStatus.Critical => MonitorStatus.Critical,
NodeStatus.Unreachable or NodeStatus.Warning or NodeStatus.PartlyAvailable or NodeStatus.Unconfirmed => MonitorStatus.Warning,
//case NodeStatus.Inactive:
//case NodeStatus.Unplugged:
_ => MonitorStatus.Unknown,
};
}
}
}
Loading