Skip to content

Commit

Permalink
C# 11 Cleanup and fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
NickCraver committed Nov 30, 2024
1 parent dfd08fe commit afc8eed
Show file tree
Hide file tree
Showing 92 changed files with 404 additions and 605 deletions.
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
2 changes: 1 addition & 1 deletion 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 Down
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,
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ async Task addMetric(string metricName, string[] tags)
var tagDict = tags?.ToDictionary(t => t, _ => "*");
var apiResult = await GetMetric(metricName, result.StartTime, tags: tagDict);
if (apiResult == null) return;
if (tags?.Any() ?? false)
if (tags?.Length > 0)
{
result.MultiSeries[metricName] = apiResult.Series
.GroupBy(s => s.Host)
Expand Down Expand Up @@ -171,15 +171,14 @@ public static class TagValues
public static class TagCombos
{
public static readonly Dictionary<string, string>
AllNetDirections = new Dictionary<string, string> {[Tags.Direction] = "*" },
AllDisks = new Dictionary<string, string> {[Tags.Disk] = "*" };
AllNetDirections = new() { [Tags.Direction] = "*" },
AllDisks = new() { [Tags.Disk] = "*" };

public static Dictionary<string, string> AllDirectionsForInterface(string ifaceId)
=> new Dictionary<string, string>
{
[Tags.Direction] = "*",
[Tags.IFace] = ifaceId
};
public static Dictionary<string, string> AllDirectionsForInterface(string ifaceId) => new()
{
[Tags.Direction] = "*",
[Tags.IFace] = ifaceId
};
}

public static bool IsCounter(string metric, string host)
Expand All @@ -189,18 +188,11 @@ public static bool IsCounter(string metric, string host)
{
metric = metric.Replace($"__{host}.", "");
}
switch (metric)
return metric switch
{
case Globals.CPU:
case Globals.NetBytes:
case Globals.NetBondBytes:
case Globals.NetOtherBytes:
case Globals.NetTunnelBytes:
case Globals.NetVirtualBytes:
return true;
default:
return false;
}
Globals.CPU or Globals.NetBytes or Globals.NetBondBytes or Globals.NetOtherBytes or Globals.NetTunnelBytes or Globals.NetVirtualBytes => true,
_ => false,
};
}

public static string InterfaceMetricName(Interface i) =>
Expand All @@ -215,7 +207,7 @@ public static string InterfaceMetricName(Interface i) =>

public static string GetDenormalized(string metric, string host, Dictionary<string, List<string>> metricCache)
{
if (host == null || host.Contains("*") || host.Contains("|"))
if (host == null || host.Contains('*') || host.Contains('|'))
{
return metric;
}
Expand Down Expand Up @@ -264,17 +256,17 @@ public class BosunMetricResponse
/// </summary>
public class PointSeries
{
private static readonly Regex HostRegex = new Regex(@"\{host=(.*)[,|\}]", RegexOptions.Compiled);
private static readonly Regex HostRegex = new(@"\{host=(.*)[,|\}]", RegexOptions.Compiled);
private string _host;
public string Host
{
get
{
if (_host == null)
{
if (Tags.ContainsKey("host"))
if (Tags.TryGetValue("host", out string value))
{
Host = Tags["host"];
Host = value;
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,16 +265,14 @@ public async Task<List<Node>> GetAllNodesAsync()
AppName = key,
NiceName = key
};
BosunHost.ProcessInfo process = null;
if (h.Processes?.TryGetValue(key, out process) == true)
if (h.Processes?.TryGetValue(key, out var process) == true)
{
app.PercentCPU = (decimal)process.CPUPercentUsed;
app.CurrentPercentCPU = process.CPUPercentUsed;
app.MemoryUsed = process.UsedRealBytes;
app.VirtualMemoryUsed = process.UsedVirtualBytes;
}
BosunHost.ServiceInfo service = null;
if (h.Services?.TryGetValue(key, out service) == true)
if (h.Services?.TryGetValue(key, out var service) == true)
{
app.IsRunning = service.Running;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Jil;
using StackExchange.Profiling;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public virtual IEnumerable<string> GetExceptions()
public Node GetNodeByHostname(string hostName)
{
if (!Module.Settings.Enabled || hostName.IsNullOrEmpty()) return null;
return AllNodes.Find(s => s.Name.IndexOf(hostName, StringComparison.InvariantCultureIgnoreCase) >= 0);
return AllNodes.Find(s => s.Name.Contains(hostName, StringComparison.InvariantCultureIgnoreCase));
}

public virtual IEnumerable<Node> GetNodesByIP(IPAddress ip) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public EmptyDataProvider(DashboardModule module, string uniqueKey) : base(module
protected override IEnumerable<MonitorStatus> GetMonitorStatus() => Enumerable.Empty<MonitorStatus>();
protected override string GetMonitorStatusReason() => null;

private static readonly List<Node> EmptyAllNodes = new List<Node>();
private static readonly List<Node> EmptyAllNodes = new();

public override IEnumerable<string> GetExceptions() => Enumerable.Empty<string>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ Inner Join APM_ProcessEvidence pe
{
n.Issues = new List<Issue<Node>>
{
new Issue<Node>(n, "Orion", n.PrettyName)
new(n, "Orion", n.PrettyName)
{
Date = n.LastSync ?? DateTime.UtcNow,
Description = n.StatusDescription,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using StackExchange.Exceptional;
Expand Down
Loading

0 comments on commit afc8eed

Please sign in to comment.