Skip to content

Commit f6d08d1

Browse files
Fix warnings and cleanup. (#3089)
* Fix warnings and cleanup. * misc
1 parent 32e8ae3 commit f6d08d1

File tree

129 files changed

+115
-10648
lines changed

Some content is hidden

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

129 files changed

+115
-10648
lines changed

.publicApi/Microsoft.ApplicationInsights.dll/Stable/PublicAPI.Unshipped.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ override Microsoft.ApplicationInsights.DataContracts.RequestTelemetry.Success.ge
273273
override Microsoft.ApplicationInsights.DataContracts.RequestTelemetry.Success.set -> void
274274
override Microsoft.ApplicationInsights.DataContracts.RequestTelemetry.Timestamp.get -> System.DateTimeOffset
275275
override Microsoft.ApplicationInsights.DataContracts.RequestTelemetry.Timestamp.set -> void
276-
override Microsoft.ApplicationInsights.Metrics.MetricIdentifier.Equals(object otherObj) -> bool
276+
override Microsoft.ApplicationInsights.Metrics.MetricIdentifier.Equals(object obj) -> bool
277277
override Microsoft.ApplicationInsights.Metrics.MetricIdentifier.GetHashCode() -> int
278278
override Microsoft.ApplicationInsights.Metrics.MetricIdentifier.ToString() -> string
279279
static Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault() -> Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration

BASE/src/Microsoft.ApplicationInsights/DataContracts/ExceptionTelemetry.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,9 @@ private static Exception ReconstructExceptionFromDetails(IReadOnlyList<Exception
287287
}
288288

289289
// Create exception with inner if it exists
290+
#pragma warning disable CA2201 // Exception reconstruction requires generic Exception type
290291
var exception = innerException != null ? new Exception(message, innerException) : new Exception(message);
292+
#pragma warning restore CA2201
291293
exceptionDict[detail.Id] = exception;
292294
}
293295

BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/OperationHolder.cs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -36,18 +36,8 @@ public OperationHolder(TelemetryClient telemetryClient, T telemetry, Activity ac
3636
/// <param name="suppressedActivity">An ambient activity that was suppressed to create a root operation and should be restored on dispose.</param>
3737
public OperationHolder(TelemetryClient telemetryClient, T telemetry, Activity activity, Activity suppressedActivity)
3838
{
39-
if (telemetryClient == null)
40-
{
41-
throw new ArgumentNullException(nameof(telemetryClient));
42-
}
43-
44-
if (telemetry == null)
45-
{
46-
throw new ArgumentNullException(nameof(telemetry));
47-
}
48-
49-
this.telemetryClient = telemetryClient;
50-
this.Telemetry = telemetry;
39+
this.telemetryClient = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
40+
this.Telemetry = telemetry ?? throw new ArgumentNullException(nameof(telemetry));
5141
this.activity = activity;
5242
this.suppressedActivity = suppressedActivity;
5343
}

BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Tracing/SelfDiagnosticsConfigParser.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,14 @@ public bool TryGetConfiguration(out string logDirectory, out int fileSizeInKB, o
7474
this.configBuffer = buffer;
7575
}
7676

77-
file.Read(buffer, 0, buffer.Length);
78-
string configJson = Encoding.UTF8.GetString(buffer);
77+
int totalBytesRead = 0;
78+
int bytesRead;
79+
while (totalBytesRead < buffer.Length && (bytesRead = file.Read(buffer, totalBytesRead, buffer.Length - totalBytesRead)) > 0)
80+
{
81+
totalBytesRead += bytesRead;
82+
}
83+
84+
string configJson = Encoding.UTF8.GetString(buffer, 0, totalBytesRead);
7985

8086
if (logDirectory == null && !TryParseLogDirectory(configJson, out logDirectory))
8187
{
@@ -102,7 +108,11 @@ public bool TryGetConfiguration(out string logDirectory, out int fileSizeInKB, o
102108
return false;
103109
}
104110

111+
#if NETCOREAPP
112+
logLevel = Enum.Parse<EventLevel>(logLevelString);
113+
#else
105114
logLevel = (EventLevel)Enum.Parse(typeof(EventLevel), logLevelString);
115+
#endif
106116
return true;
107117
}
108118
}

BASE/src/Microsoft.ApplicationInsights/Extensibility/TelemetryConfiguration.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,11 +256,14 @@ public static TelemetryConfiguration CreateDefault()
256256
public void ConfigureOpenTelemetryBuilder(Action<IOpenTelemetryBuilder> configure)
257257
{
258258
this.ThrowIfBuilt();
259-
259+
#if NET6_0_OR_GREATER
260+
ArgumentNullException.ThrowIfNull(configure);
261+
#else
260262
if (configure == null)
261263
{
262264
throw new ArgumentNullException(nameof(configure));
263265
}
266+
#endif
264267

265268
// Chain the configurations
266269
var previousConfiguration = this.builderConfiguration;
@@ -291,11 +294,14 @@ public void Dispose()
291294
public void SetAzureTokenCredential(TokenCredential tokenCredential)
292295
{
293296
this.ThrowIfBuilt();
294-
297+
#if NET6_0_OR_GREATER
298+
ArgumentNullException.ThrowIfNull(tokenCredential);
299+
#else
295300
if (tokenCredential == null)
296301
{
297302
throw new ArgumentNullException(nameof(tokenCredential));
298303
}
304+
#endif
299305

300306
// Configure the OpenTelemetry builder to pass the credential to Azure Monitor Exporter
301307
this.ConfigureOpenTelemetryBuilder(builder =>

BASE/src/Microsoft.ApplicationInsights/Internal/FeatureMetricEmissionHelper.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ private static Dictionary<string, object> GetVmMetadata()
123123
using (var httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(2) })
124124
{
125125
httpClient.DefaultRequestHeaders.Add("Metadata", "True");
126-
var responseString = httpClient.GetStringAsync(StatsbeatConstants.AMSUrl);
126+
var responseString = httpClient.GetStringAsync(new Uri(StatsbeatConstants.AMSUrl));
127127
return JsonSerializer.Deserialize<Dictionary<string, object>>(responseString.Result);
128128
}
129129
}
@@ -168,7 +168,9 @@ private string GetResourceProvider()
168168
if (vmMetadata.TryGetValue("osType", out var osType) && osType is string)
169169
{
170170
// osType takes precedence over the platform-observed OS.
171-
this.os = (osType as string).ToLower(CultureInfo.InvariantCulture);
171+
#pragma warning disable CA1308 // Normalize strings to uppercase
172+
this.os = (osType as string).ToLowerInvariant();
173+
#pragma warning restore CA1308 // Normalize strings to uppercase
172174
}
173175
else
174176
{

BASE/src/Microsoft.ApplicationInsights/Metrics/MetricIdentifier.cs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
namespace Microsoft.ApplicationInsights.Metrics
22
{
33
using System;
4+
#if NET8_0_OR_GREATER
5+
using System.Buffers;
6+
#endif
47
using System.Collections.Generic;
58
using System.Runtime.CompilerServices;
69
using System.Text;
@@ -16,11 +19,20 @@ public sealed class MetricIdentifier : IEquatable<MetricIdentifier>
1619

1720
private const string NoNamespaceIdentifierStringComponent = "<NoNamespace>";
1821

22+
#if NET8_0_OR_GREATER
23+
private static readonly SearchValues<char> InvalidMetricCharsSearchValues = SearchValues.Create(
24+
new char[]
25+
{
26+
'\0', '"', '\'', '(', ')', '[', ']', '{', '}', '<', '>', '=', ',',
27+
'`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '+', '?',
28+
});
29+
#else
1930
private static readonly char[] InvalidMetricChars = new char[]
2031
{
2132
'\0', '"', '\'', '(', ')', '[', ']', '{', '}', '<', '>', '=', ',',
2233
'`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '+', '?',
2334
};
35+
#endif
2436

2537
private static string defaultMetricNamespace = String.Empty;
2638

@@ -65,7 +77,11 @@ private static void ValidateLiteral(string partValue, string partName, bool allo
6577
}
6678
}
6779

68-
int pos = partName.IndexOfAny(InvalidMetricChars);
80+
#if NET8_0_OR_GREATER
81+
int pos = partValue.AsSpan().IndexOfAny(InvalidMetricCharsSearchValues);
82+
#else
83+
int pos = partValue.IndexOfAny(InvalidMetricChars);
84+
#endif
6985
if (pos >= 0)
7086
{
7187
throw new ArgumentException(Invariant($"{partName} (\"{partValue}\") contains a disallowed character at position {pos}."));
@@ -501,17 +517,17 @@ public override int GetHashCode()
501517
/// Determines whether the specified object is a <c>MetricIdentifier</c> that is equal to this <c>MetricIdentifier</c> based on the
502518
/// respective metric namespaces, metric IDs and the number and the names of dimensions.
503519
/// </summary>
504-
/// <param name="otherObj">Another object.</param>
520+
/// <param name="obj">Another object.</param>
505521
/// <returns>Whether the specified other object is equal to this object based on the respective namespaces, IDs and dimension names.</returns>
506-
public override bool Equals(object otherObj)
522+
public override bool Equals(object obj)
507523
{
508-
if (otherObj is MetricIdentifier otherMetricIdentifier)
524+
if (obj is MetricIdentifier otherMetricIdentifier)
509525
{
510526
return this.Equals(otherMetricIdentifier);
511527
}
512528
else
513529
{
514-
return base.Equals(otherObj);
530+
return base.Equals(obj);
515531
}
516532
}
517533

@@ -617,7 +633,11 @@ private static void EnsureDimensionNameValid(ref int dimensionCount, ref string
617633
+ " they must contain at least 1 printable character.");
618634
}
619635

636+
#if NET8_0_OR_GREATER
637+
int pos = dimensionName.AsSpan().IndexOfAny(InvalidMetricCharsSearchValues);
638+
#else
620639
int pos = dimensionName.IndexOfAny(InvalidMetricChars);
640+
#endif
621641
if (pos >= 0)
622642
{
623643
throw new ArgumentException(Invariant($"Name for dimension number {thisDimensionNumber} (\"{dimensionName}\")")

BASE/src/Microsoft.ApplicationInsights/TelemetryClient.cs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ public void TrackException(Exception exception, IDictionary<string, string> prop
473473
this.Configuration.FeatureReporter.MarkFeatureInUse(StatsbeatFeatures.TrackException);
474474
if (exception == null)
475475
{
476-
exception = new Exception(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName));
476+
exception = new InvalidOperationException(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName));
477477
}
478478

479479
var state = new DictionaryLogState(this.Context, properties, exception.Message);
@@ -493,7 +493,7 @@ public void TrackException(ExceptionTelemetry telemetry)
493493
// TODO investigate how problem id, custom message, etc should appear in portal
494494
if (telemetry == null)
495495
{
496-
var exception = new Exception(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName));
496+
var exception = new InvalidOperationException(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName));
497497
telemetry = new ExceptionTelemetry(exception);
498498
}
499499

@@ -697,10 +697,14 @@ public void TrackDependency(DependencyTelemetry telemetry)
697697
[EditorBrowsable(EditorBrowsableState.Never)]
698698
public void Track(ITelemetry telemetry)
699699
{
700+
#if NET6_0_OR_GREATER
701+
ArgumentNullException.ThrowIfNull(telemetry);
702+
#else
700703
if (telemetry == null)
701704
{
702705
throw new ArgumentNullException(nameof(telemetry));
703706
}
707+
#endif
704708

705709
switch (telemetry)
706710
{
@@ -1119,10 +1123,14 @@ public Metric GetMetric(
11191123
public Metric GetMetric(
11201124
MetricIdentifier metricIdentifier)
11211125
{
1126+
#if NET6_0_OR_GREATER
1127+
ArgumentNullException.ThrowIfNull(metricIdentifier);
1128+
#else
11221129
if (metricIdentifier == null)
11231130
{
11241131
throw new ArgumentNullException(nameof(metricIdentifier));
11251132
}
1133+
#endif
11261134

11271135
// Build dimension names array from MetricIdentifier
11281136
string[] dimensionNames = null;
@@ -1231,10 +1239,14 @@ private static ActivityKind GetActivityKindForDependency(string dependencyType)
12311239
/// <returns>A reconstructed Exception with all diagnostic details.</returns>
12321240
private static Exception ConvertToException(ExceptionTelemetry telemetry)
12331241
{
1242+
#if NET6_0_OR_GREATER
1243+
ArgumentNullException.ThrowIfNull(telemetry);
1244+
#else
12341245
if (telemetry == null)
12351246
{
12361247
throw new ArgumentNullException(nameof(telemetry));
12371248
}
1249+
#endif
12381250

12391251
Exception rootException = null;
12401252

@@ -1252,7 +1264,9 @@ private static Exception ConvertToException(ExceptionTelemetry telemetry)
12521264
else
12531265
{
12541266
// Fallback: create a generic exception with the message
1267+
#pragma warning disable CA2201 // Exception reconstruction requires generic Exception type
12551268
rootException = new Exception(telemetry.Message ?? "<no message>");
1269+
#pragma warning restore CA2201
12561270
}
12571271

12581272
// Enrich the exception with metadata
@@ -1270,7 +1284,9 @@ private static Exception ReconstructExceptionChain(IReadOnlyList<ExceptionDetail
12701284
{
12711285
if (exceptionDetailsList == null || exceptionDetailsList.Count == 0)
12721286
{
1287+
#pragma warning disable CA2201 // Exception reconstruction requires generic Exception type
12731288
return new Exception("<no exception details>");
1289+
#pragma warning restore CA2201
12741290
}
12751291

12761292
// Process from innermost (index 0) to outermost (last index)
@@ -1287,6 +1303,7 @@ private static Exception ReconstructExceptionChain(IReadOnlyList<ExceptionDetail
12871303
// Include the type name in the message since we can't safely create typed exceptions via reflection
12881304
Exception currentException;
12891305

1306+
#pragma warning disable CA2201 // Exception reconstruction requires generic Exception type
12901307
if (innerException != null)
12911308
{
12921309
currentException = new Exception($"[{typeName}] {message}", innerException);
@@ -1295,6 +1312,7 @@ private static Exception ReconstructExceptionChain(IReadOnlyList<ExceptionDetail
12951312
{
12961313
currentException = new Exception($"[{typeName}] {message}");
12971314
}
1315+
#pragma warning restore CA2201
12981316

12991317
// Set the current exception as the inner for the next iteration
13001318
innerException = currentException;

BASE/src/Microsoft.ApplicationInsights/TelemetryClientExtensions.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,14 @@ public static IOperationHolder<T> StartOperation<T>(
5353
string parentOperationId = null)
5454
where T : OperationTelemetry, new()
5555
{
56+
#if NET6_0_OR_GREATER
57+
ArgumentNullException.ThrowIfNull(telemetryClient);
58+
#else
5659
if (telemetryClient == null)
5760
{
5861
throw new ArgumentNullException(nameof(telemetryClient));
5962
}
63+
#endif
6064

6165
telemetryClient.Configuration.FeatureReporter.MarkFeatureInUse(Internal.StatsbeatFeatures.StartOperation);
6266

@@ -137,6 +141,10 @@ public static IOperationHolder<T> StartOperation<T>(
137141
T operationTelemetry)
138142
where T : OperationTelemetry
139143
{
144+
#if NET6_0_OR_GREATER
145+
ArgumentNullException.ThrowIfNull(telemetryClient);
146+
ArgumentNullException.ThrowIfNull(operationTelemetry);
147+
#else
140148
if (telemetryClient == null)
141149
{
142150
throw new ArgumentNullException(nameof(telemetryClient));
@@ -146,6 +154,7 @@ public static IOperationHolder<T> StartOperation<T>(
146154
{
147155
throw new ArgumentNullException(nameof(operationTelemetry));
148156
}
157+
#endif
149158

150159
if (string.IsNullOrEmpty(operationTelemetry.Name))
151160
{
@@ -221,10 +230,14 @@ public static IOperationHolder<T> StartOperation<T>(
221230
Activity activity)
222231
where T : OperationTelemetry, new()
223232
{
233+
#if NET6_0_OR_GREATER
234+
ArgumentNullException.ThrowIfNull(telemetryClient);
235+
#else
224236
if (telemetryClient == null)
225237
{
226238
throw new ArgumentNullException(nameof(telemetryClient));
227239
}
240+
#endif
228241

229242
if (activity == null)
230243
{
@@ -275,10 +288,14 @@ public static void StopOperation<T>(
275288
IOperationHolder<T> operation)
276289
where T : OperationTelemetry
277290
{
291+
#if NET6_0_OR_GREATER
292+
ArgumentNullException.ThrowIfNull(telemetryClient);
293+
#else
278294
if (telemetryClient == null)
279295
{
280296
throw new ArgumentNullException(nameof(telemetryClient));
281297
}
298+
#endif
282299

283300
if (operation == null)
284301
{

0 commit comments

Comments
 (0)