Skip to content

Commit afc8eed

Browse files
committed
C# 11 Cleanup and fixes
1 parent dfd08fe commit afc8eed

File tree

92 files changed

+404
-605
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

92 files changed

+404
-605
lines changed

.editorconfig

+9-20
Original file line numberDiff line numberDiff line change
@@ -103,23 +103,12 @@ dotnet_naming_symbols.constant_fields.required_modifiers = const
103103
dotnet_naming_style.prefix_underscore.capitalization = camel_case
104104
dotnet_naming_style.prefix_underscore.required_prefix = _
105105

106-
# CA1027: Mark enums with FlagsAttribute
107-
dotnet_diagnostic.CA1027.severity = none
108-
109-
# CA1031: Do not catch general exception types
110-
dotnet_diagnostic.CA1031.severity = none
111-
112-
# CA1034: Nested types should not be visible
113-
dotnet_diagnostic.CA1034.severity = none
114-
115-
# CA1063: Implement IDisposable Correctly
116-
dotnet_diagnostic.CA1063.severity = none
117-
118-
# CA1810: Initialize reference type static fields inline
119-
dotnet_diagnostic.CA1810.severity = none
120-
121-
# CA1819: Properties should not return arrays
122-
dotnet_diagnostic.CA1819.severity = none
123-
124-
# CA1822: Mark members as static
125-
dotnet_diagnostic.CA1822.severity = none
106+
dotnet_diagnostic.CA1027.severity = none # CA1027: Mark enums with FlagsAttribute
107+
dotnet_diagnostic.CA1031.severity = none # CA1031: Do not catch general exception types
108+
dotnet_diagnostic.CA1034.severity = none # CA1034: Nested types should not be visible
109+
dotnet_diagnostic.CA1063.severity = none # CA1063: Implement IDisposable Correctly
110+
dotnet_diagnostic.CA1810.severity = none # CA1810: Initialize reference type static fields inline
111+
dotnet_diagnostic.CA1819.severity = none # CA1819: Properties should not return arrays
112+
dotnet_diagnostic.CA1822.severity = none # CA1822: Mark members as static
113+
114+
dotnet_diagnostic.IDE0130.severity = none # IDE0130: Namespace does not match folder structure

src/Directory.Build.props

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<Project>
22
<PropertyGroup>
3-
<LangVersion>8.0</LangVersion>
3+
<LangVersion>11.0</LangVersion>
44
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
55
<CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)Opserver.ruleset</CodeAnalysisRuleSet>
66
<!--<GenerateDocumentationFile>true</GenerateDocumentationFile>-->

src/Opserver.Core/Data/Cache.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public class Cache<T> : Cache where T : class
2020
private int _hasData;
2121
internal override object InnerCache => Data;
2222
public override Type Type => typeof (T);
23-
private readonly SemaphoreSlim _pollSemaphoreSlim = new SemaphoreSlim(1);
23+
private readonly SemaphoreSlim _pollSemaphoreSlim = new(1);
2424

2525
public override string InventoryDescription
2626
{
@@ -116,7 +116,7 @@ private async Task<T> UpdateAsync(bool force)
116116
private string MiniProfilerDescription { get; }
117117

118118
// ReSharper disable once StaticMemberInGenericType
119-
private static readonly MiniProfilerBaseOptions _profilerOptions = new MiniProfilerBaseOptions
119+
private static readonly MiniProfilerBaseOptions _profilerOptions = new()
120120
{
121121
Storage = new NullStorage(),
122122
ProfilerProvider = new DefaultProfilerProvider()

src/Opserver.Core/Data/CloudFlare/CloudFlareAPI.Zones.cs

+6-13
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ public partial class CloudflareAPI
1212
public Cache<List<CloudflareZone>> Zones =>
1313
_zones ??= GetCloudflareCache(5.Minutes(), () => Get<List<CloudflareZone>>("zones"));
1414

15-
private static readonly NameValueCollection _dnsRecordFetchParams = new NameValueCollection
15+
private static readonly NameValueCollection _dnsRecordFetchParams = new()
1616
{
1717
["per_page"] = "100"
1818
};
@@ -45,19 +45,12 @@ public CloudflareZone GetZoneFromUrl(string url) =>
4545
/// </summary>
4646
/// <param name="record">The DNS record to get an IP for</param>
4747
/// <returns>Root IP Addresses for this record.</returns>
48-
public List<IPAddress> GetIPs(CloudflareDNSRecord record)
48+
public List<IPAddress> GetIPs(CloudflareDNSRecord record) => record.Type switch
4949
{
50-
switch (record.Type)
51-
{
52-
case DNSRecordType.A:
53-
case DNSRecordType.AAAA:
54-
return new List<IPAddress> { record.IPAddress };
55-
case DNSRecordType.CNAME:
56-
return GetIPs(record.Content);
57-
default:
58-
return null;
59-
}
60-
}
50+
DNSRecordType.A or DNSRecordType.AAAA => new List<IPAddress> { record.IPAddress },
51+
DNSRecordType.CNAME => GetIPs(record.Content),
52+
_ => null,
53+
};
6154

6255
/// <summary>
6356
/// Get the IP Addresses for a given fully qualified host (star records not supported), even through CNAME chains.

src/Opserver.Core/Data/CloudFlare/CloudFlareModule.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public CloudflareModule(IConfiguration config, PollingService poller) : base(con
3636
public List<CloudflareDNSRecord> GetDNSRecords(CloudflareZone zone) =>
3737
API.DNSRecords.Data?.Where(r => r.ZoneId == zone.Id).ToList() ?? new List<CloudflareDNSRecord>();
3838

39-
private static readonly NameValueCollection _purgeAllParams = new NameValueCollection
39+
private static readonly NameValueCollection _purgeAllParams = new()
4040
{
4141
["purge_everything"] = "true"
4242
};
@@ -69,7 +69,7 @@ public IEnumerable<string> GetMaskedIPs(List<IPAddress> addresses)
6969
}
7070
}
7171

72-
private readonly ConcurrentDictionary<IPAddress, string> _cached = new ConcurrentDictionary<IPAddress, string>();
72+
private readonly ConcurrentDictionary<IPAddress, string> _cached = new();
7373

7474
private string GetMaskedIP(IPAddress address)
7575
{

src/Opserver.Core/Data/CloudFlare/CloudFlareResponse.cs

+7-20
Original file line numberDiff line numberDiff line change
@@ -94,27 +94,14 @@ public class CloudflareZone : IMonitorStatus
9494
[DataMember(Name = "permissions")]
9595
public List<string> Permissons { get; set; }
9696

97-
public MonitorStatus MonitorStatus
97+
public MonitorStatus MonitorStatus => Status switch
9898
{
99-
get
100-
{
101-
switch (Status)
102-
{
103-
case ZoneStatus.Active:
104-
return MonitorStatus.Good;
105-
case ZoneStatus.Pending:
106-
case ZoneStatus.Initializing:
107-
case ZoneStatus.Moved:
108-
return MonitorStatus.Warning;
109-
case ZoneStatus.Deleted:
110-
return MonitorStatus.Critical;
111-
case ZoneStatus.Deactivated:
112-
return MonitorStatus.Maintenance;
113-
default:
114-
return MonitorStatus.Unknown;
115-
}
116-
}
117-
}
99+
ZoneStatus.Active => MonitorStatus.Good,
100+
ZoneStatus.Pending or ZoneStatus.Initializing or ZoneStatus.Moved => MonitorStatus.Warning,
101+
ZoneStatus.Deleted => MonitorStatus.Critical,
102+
ZoneStatus.Deactivated => MonitorStatus.Maintenance,
103+
_ => MonitorStatus.Unknown,
104+
};
118105

119106
public string MonitorStatusReason => "Current status: " + Status;
120107
}

src/Opserver.Core/Data/Dashboard/HardwareSummary.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Collections.Generic;
2+
using System;
23

34
namespace Opserver.Data.Dashboard
45
{
@@ -48,7 +49,7 @@ public int? Label
4849
if (Bank == null) return null;
4950
if (Name.Length > Bank.Length)
5051
{
51-
if (int.TryParse(Name.Substring(Bank.Length), out int position))
52+
if (int.TryParse(Name.AsSpan(Bank.Length), out int position))
5253
{
5354
_label = position;
5455
}

src/Opserver.Core/Data/Dashboard/Interface.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public partial class Interface : IMonitorStatus
1919
public string Alias { get; internal set; }
2020
public string TypeDescription { get; internal set; }
2121
public string PhysicalAddress { get; internal set; }
22-
public bool IsTeam => TeamMembers?.Any() ?? false;
22+
public bool IsTeam => TeamMembers?.Count > 0;
2323
public bool IsUnwatched { get; internal set; }
2424

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

43-
private static readonly Dictionary<string, string> _prettyNameReplacements = new Dictionary<string, string>
43+
private static readonly Dictionary<string, string> _prettyNameReplacements = new()
4444
{
4545
["Microsoft Network Adapter Multiplexor Driver"] = "Microsoft Team",
4646
["Quad Port Server Adapter"] = "Quad Port SA",
@@ -72,7 +72,7 @@ public string PrettySpeed
7272
get {
7373
if (!Speed.HasValue)
7474
{
75-
if (!(TeamMembers?.Any() ?? false))
75+
if (!(TeamMembers?.Count > 0))
7676
{
7777
return "n/a";
7878
}
@@ -91,7 +91,7 @@ public string PrettySpeed
9191

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

9797
internal bool IsLikelyPrimary(Regex pattern) => pattern != null

src/Opserver.Core/Data/Dashboard/Node.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ public NodeService GetService(string id)
269269
return null;
270270
}
271271

272-
private static readonly List<IPNet> EmptyIPs = new List<IPNet>();
272+
private static readonly List<IPNet> EmptyIPs = new();
273273

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

src/Opserver.Core/Data/Dashboard/NodeStatus.cs

+10-25
Original file line numberDiff line numberDiff line change
@@ -27,30 +27,15 @@ public enum NodeStatus
2727

2828
public static class ServerStatusExtensions
2929
{
30-
public static MonitorStatus ToMonitorStatus(this NodeStatus status)
30+
public static MonitorStatus ToMonitorStatus(this NodeStatus status) => status switch
3131
{
32-
switch (status)
33-
{
34-
case NodeStatus.Unmanaged:
35-
return MonitorStatus.Maintenance;
36-
case NodeStatus.Active:
37-
case NodeStatus.External:
38-
case NodeStatus.Up:
39-
case NodeStatus.Shutdown:
40-
return MonitorStatus.Good;
41-
case NodeStatus.Down:
42-
case NodeStatus.Critical:
43-
return MonitorStatus.Critical;
44-
case NodeStatus.Unreachable:
45-
case NodeStatus.Warning:
46-
case NodeStatus.PartlyAvailable:
47-
case NodeStatus.Unconfirmed:
48-
return MonitorStatus.Warning;
49-
//case NodeStatus.Inactive:
50-
//case NodeStatus.Unplugged:
51-
default:
52-
return MonitorStatus.Unknown;
53-
}
54-
}
32+
NodeStatus.Unmanaged => MonitorStatus.Maintenance,
33+
NodeStatus.Active or NodeStatus.External or NodeStatus.Up or NodeStatus.Shutdown => MonitorStatus.Good,
34+
NodeStatus.Down or NodeStatus.Critical => MonitorStatus.Critical,
35+
NodeStatus.Unreachable or NodeStatus.Warning or NodeStatus.PartlyAvailable or NodeStatus.Unconfirmed => MonitorStatus.Warning,
36+
//case NodeStatus.Inactive:
37+
//case NodeStatus.Unplugged:
38+
_ => MonitorStatus.Unknown,
39+
};
5540
}
56-
}
41+
}

src/Opserver.Core/Data/Dashboard/Providers/BosunDataProvider.Metrics.cs

+16-24
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ async Task addMetric(string metricName, string[] tags)
8787
var tagDict = tags?.ToDictionary(t => t, _ => "*");
8888
var apiResult = await GetMetric(metricName, result.StartTime, tags: tagDict);
8989
if (apiResult == null) return;
90-
if (tags?.Any() ?? false)
90+
if (tags?.Length > 0)
9191
{
9292
result.MultiSeries[metricName] = apiResult.Series
9393
.GroupBy(s => s.Host)
@@ -171,15 +171,14 @@ public static class TagValues
171171
public static class TagCombos
172172
{
173173
public static readonly Dictionary<string, string>
174-
AllNetDirections = new Dictionary<string, string> {[Tags.Direction] = "*" },
175-
AllDisks = new Dictionary<string, string> {[Tags.Disk] = "*" };
174+
AllNetDirections = new() { [Tags.Direction] = "*" },
175+
AllDisks = new() { [Tags.Disk] = "*" };
176176

177-
public static Dictionary<string, string> AllDirectionsForInterface(string ifaceId)
178-
=> new Dictionary<string, string>
179-
{
180-
[Tags.Direction] = "*",
181-
[Tags.IFace] = ifaceId
182-
};
177+
public static Dictionary<string, string> AllDirectionsForInterface(string ifaceId) => new()
178+
{
179+
[Tags.Direction] = "*",
180+
[Tags.IFace] = ifaceId
181+
};
183182
}
184183

185184
public static bool IsCounter(string metric, string host)
@@ -189,18 +188,11 @@ public static bool IsCounter(string metric, string host)
189188
{
190189
metric = metric.Replace($"__{host}.", "");
191190
}
192-
switch (metric)
191+
return metric switch
193192
{
194-
case Globals.CPU:
195-
case Globals.NetBytes:
196-
case Globals.NetBondBytes:
197-
case Globals.NetOtherBytes:
198-
case Globals.NetTunnelBytes:
199-
case Globals.NetVirtualBytes:
200-
return true;
201-
default:
202-
return false;
203-
}
193+
Globals.CPU or Globals.NetBytes or Globals.NetBondBytes or Globals.NetOtherBytes or Globals.NetTunnelBytes or Globals.NetVirtualBytes => true,
194+
_ => false,
195+
};
204196
}
205197

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

216208
public static string GetDenormalized(string metric, string host, Dictionary<string, List<string>> metricCache)
217209
{
218-
if (host == null || host.Contains("*") || host.Contains("|"))
210+
if (host == null || host.Contains('*') || host.Contains('|'))
219211
{
220212
return metric;
221213
}
@@ -264,17 +256,17 @@ public class BosunMetricResponse
264256
/// </summary>
265257
public class PointSeries
266258
{
267-
private static readonly Regex HostRegex = new Regex(@"\{host=(.*)[,|\}]", RegexOptions.Compiled);
259+
private static readonly Regex HostRegex = new(@"\{host=(.*)[,|\}]", RegexOptions.Compiled);
268260
private string _host;
269261
public string Host
270262
{
271263
get
272264
{
273265
if (_host == null)
274266
{
275-
if (Tags.ContainsKey("host"))
267+
if (Tags.TryGetValue("host", out string value))
276268
{
277-
Host = Tags["host"];
269+
Host = value;
278270
}
279271
else
280272
{

src/Opserver.Core/Data/Dashboard/Providers/BosunDataProvider.Nodes.cs

+2-4
Original file line numberDiff line numberDiff line change
@@ -265,16 +265,14 @@ public async Task<List<Node>> GetAllNodesAsync()
265265
AppName = key,
266266
NiceName = key
267267
};
268-
BosunHost.ProcessInfo process = null;
269-
if (h.Processes?.TryGetValue(key, out process) == true)
268+
if (h.Processes?.TryGetValue(key, out var process) == true)
270269
{
271270
app.PercentCPU = (decimal)process.CPUPercentUsed;
272271
app.CurrentPercentCPU = process.CPUPercentUsed;
273272
app.MemoryUsed = process.UsedRealBytes;
274273
app.VirtualMemoryUsed = process.UsedVirtualBytes;
275274
}
276-
BosunHost.ServiceInfo service = null;
277-
if (h.Services?.TryGetValue(key, out service) == true)
275+
if (h.Services?.TryGetValue(key, out var service) == true)
278276
{
279277
app.IsRunning = service.Running;
280278
}

src/Opserver.Core/Data/Dashboard/Providers/BosunDataProvider.cs

-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3-
using System.IO;
43
using System.Linq;
5-
using System.Net;
64
using System.Threading.Tasks;
75
using Jil;
86
using StackExchange.Profiling;

src/Opserver.Core/Data/Dashboard/Providers/DashboardDataProvider.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ public virtual IEnumerable<string> GetExceptions()
6464
public Node GetNodeByHostname(string hostName)
6565
{
6666
if (!Module.Settings.Enabled || hostName.IsNullOrEmpty()) return null;
67-
return AllNodes.Find(s => s.Name.IndexOf(hostName, StringComparison.InvariantCultureIgnoreCase) >= 0);
67+
return AllNodes.Find(s => s.Name.Contains(hostName, StringComparison.InvariantCultureIgnoreCase));
6868
}
6969

7070
public virtual IEnumerable<Node> GetNodesByIP(IPAddress ip) =>

src/Opserver.Core/Data/Dashboard/Providers/EmptyDataProvider.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public EmptyDataProvider(DashboardModule module, string uniqueKey) : base(module
1717
protected override IEnumerable<MonitorStatus> GetMonitorStatus() => Enumerable.Empty<MonitorStatus>();
1818
protected override string GetMonitorStatusReason() => null;
1919

20-
private static readonly List<Node> EmptyAllNodes = new List<Node>();
20+
private static readonly List<Node> EmptyAllNodes = new();
2121

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

src/Opserver.Core/Data/Dashboard/Providers/OrionDataProvider.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ Inner Join APM_ProcessEvidence pe
168168
{
169169
n.Issues = new List<Issue<Node>>
170170
{
171-
new Issue<Node>(n, "Orion", n.PrettyName)
171+
new(n, "Orion", n.PrettyName)
172172
{
173173
Date = n.LastSync ?? DateTime.UtcNow,
174174
Description = n.StatusDescription,

src/Opserver.Core/Data/Dashboard/Providers/SignalFxDataProvider.HostProperties.cs

-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
using System.Collections.Generic;
33
using System.Collections.Immutable;
44
using System.Linq;
5-
using System.Net;
6-
using System.Text.Json;
75
using System.Threading;
86
using System.Threading.Tasks;
97
using StackExchange.Exceptional;

0 commit comments

Comments
 (0)