Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ override Microsoft.ApplicationInsights.DataContracts.RequestTelemetry.Success.ge
override Microsoft.ApplicationInsights.DataContracts.RequestTelemetry.Success.set -> void
override Microsoft.ApplicationInsights.DataContracts.RequestTelemetry.Timestamp.get -> System.DateTimeOffset
override Microsoft.ApplicationInsights.DataContracts.RequestTelemetry.Timestamp.set -> void
override Microsoft.ApplicationInsights.Metrics.MetricIdentifier.Equals(object otherObj) -> bool
override Microsoft.ApplicationInsights.Metrics.MetricIdentifier.Equals(object obj) -> bool
override Microsoft.ApplicationInsights.Metrics.MetricIdentifier.GetHashCode() -> int
override Microsoft.ApplicationInsights.Metrics.MetricIdentifier.ToString() -> string
static Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.CreateDefault() -> Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,9 @@ private static Exception ReconstructExceptionFromDetails(IReadOnlyList<Exception
}

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,8 @@ public OperationHolder(TelemetryClient telemetryClient, T telemetry, Activity ac
/// <param name="suppressedActivity">An ambient activity that was suppressed to create a root operation and should be restored on dispose.</param>
public OperationHolder(TelemetryClient telemetryClient, T telemetry, Activity activity, Activity suppressedActivity)
{
if (telemetryClient == null)
{
throw new ArgumentNullException(nameof(telemetryClient));
}

if (telemetry == null)
{
throw new ArgumentNullException(nameof(telemetry));
}

this.telemetryClient = telemetryClient;
this.Telemetry = telemetry;
this.telemetryClient = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
this.Telemetry = telemetry ?? throw new ArgumentNullException(nameof(telemetry));
this.activity = activity;
this.suppressedActivity = suppressedActivity;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,14 @@ public bool TryGetConfiguration(out string logDirectory, out int fileSizeInKB, o
this.configBuffer = buffer;
}

file.Read(buffer, 0, buffer.Length);
string configJson = Encoding.UTF8.GetString(buffer);
int totalBytesRead = 0;
int bytesRead;
while (totalBytesRead < buffer.Length && (bytesRead = file.Read(buffer, totalBytesRead, buffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
}

string configJson = Encoding.UTF8.GetString(buffer, 0, totalBytesRead);

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

#if NETCOREAPP
logLevel = Enum.Parse<EventLevel>(logLevelString);
#else
logLevel = (EventLevel)Enum.Parse(typeof(EventLevel), logLevelString);
#endif
return true;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,11 +256,14 @@ public static TelemetryConfiguration CreateDefault()
public void ConfigureOpenTelemetryBuilder(Action<IOpenTelemetryBuilder> configure)
{
this.ThrowIfBuilt();

#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(configure);
#else
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
#endif

// Chain the configurations
var previousConfiguration = this.builderConfiguration;
Expand Down Expand Up @@ -291,11 +294,14 @@ public void Dispose()
public void SetAzureTokenCredential(TokenCredential tokenCredential)
{
this.ThrowIfBuilt();

#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(tokenCredential);
#else
if (tokenCredential == null)
{
throw new ArgumentNullException(nameof(tokenCredential));
}
#endif

// Configure the OpenTelemetry builder to pass the credential to Azure Monitor Exporter
this.ConfigureOpenTelemetryBuilder(builder =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ private static Dictionary<string, object> GetVmMetadata()
using (var httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(2) })
{
httpClient.DefaultRequestHeaders.Add("Metadata", "True");
var responseString = httpClient.GetStringAsync(StatsbeatConstants.AMSUrl);
var responseString = httpClient.GetStringAsync(new Uri(StatsbeatConstants.AMSUrl));
return JsonSerializer.Deserialize<Dictionary<string, object>>(responseString.Result);
}
}
Expand Down Expand Up @@ -168,7 +168,7 @@ private string GetResourceProvider()
if (vmMetadata.TryGetValue("osType", out var osType) && osType is string)
{
// osType takes precedence over the platform-observed OS.
this.os = (osType as string).ToLower(CultureInfo.InvariantCulture);
this.os = (osType as string).ToUpperInvariant();
}
else
{
Expand Down
30 changes: 25 additions & 5 deletions BASE/src/Microsoft.ApplicationInsights/Metrics/MetricIdentifier.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
namespace Microsoft.ApplicationInsights.Metrics
{
using System;
#if NET8_0_OR_GREATER
using System.Buffers;
#endif
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
Expand All @@ -16,11 +19,20 @@ public sealed class MetricIdentifier : IEquatable<MetricIdentifier>

private const string NoNamespaceIdentifierStringComponent = "<NoNamespace>";

#if NET8_0_OR_GREATER
private static readonly SearchValues<char> InvalidMetricCharsSearchValues = SearchValues.Create(
new char[]
{
'\0', '"', '\'', '(', ')', '[', ']', '{', '}', '<', '>', '=', ',',
'`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '+', '?',
});
#else
private static readonly char[] InvalidMetricChars = new char[]
{
'\0', '"', '\'', '(', ')', '[', ']', '{', '}', '<', '>', '=', ',',
'`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '+', '?',
};
#endif

private static string defaultMetricNamespace = String.Empty;

Expand Down Expand Up @@ -65,7 +77,11 @@ private static void ValidateLiteral(string partValue, string partName, bool allo
}
}

int pos = partName.IndexOfAny(InvalidMetricChars);
#if NET8_0_OR_GREATER
int pos = partValue.AsSpan().IndexOfAny(InvalidMetricCharsSearchValues);
#else
int pos = partValue.IndexOfAny(InvalidMetricChars);
#endif
if (pos >= 0)
{
throw new ArgumentException(Invariant($"{partName} (\"{partValue}\") contains a disallowed character at position {pos}."));
Expand Down Expand Up @@ -501,17 +517,17 @@ public override int GetHashCode()
/// Determines whether the specified object is a <c>MetricIdentifier</c> that is equal to this <c>MetricIdentifier</c> based on the
/// respective metric namespaces, metric IDs and the number and the names of dimensions.
/// </summary>
/// <param name="otherObj">Another object.</param>
/// <param name="obj">Another object.</param>
/// <returns>Whether the specified other object is equal to this object based on the respective namespaces, IDs and dimension names.</returns>
public override bool Equals(object otherObj)
public override bool Equals(object obj)
{
if (otherObj is MetricIdentifier otherMetricIdentifier)
if (obj is MetricIdentifier otherMetricIdentifier)
{
return this.Equals(otherMetricIdentifier);
}
else
{
return base.Equals(otherObj);
return base.Equals(obj);
}
}

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

#if NET8_0_OR_GREATER
int pos = dimensionName.AsSpan().IndexOfAny(InvalidMetricCharsSearchValues);
#else
int pos = dimensionName.IndexOfAny(InvalidMetricChars);
#endif
if (pos >= 0)
{
throw new ArgumentException(Invariant($"Name for dimension number {thisDimensionNumber} (\"{dimensionName}\")")
Expand Down
22 changes: 20 additions & 2 deletions BASE/src/Microsoft.ApplicationInsights/TelemetryClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ public void TrackException(Exception exception, IDictionary<string, string> prop
this.Configuration.FeatureReporter.MarkFeatureInUse(StatsbeatFeatures.TrackException);
if (exception == null)
{
exception = new Exception(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName));
exception = new InvalidOperationException(Utils.PopulateRequiredStringValue(null, "message", typeof(ExceptionTelemetry).FullName));
}

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

Expand Down Expand Up @@ -697,10 +697,14 @@ public void TrackDependency(DependencyTelemetry telemetry)
[EditorBrowsable(EditorBrowsableState.Never)]
public void Track(ITelemetry telemetry)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(telemetry);
#else
if (telemetry == null)
{
throw new ArgumentNullException(nameof(telemetry));
}
#endif

switch (telemetry)
{
Expand Down Expand Up @@ -1119,10 +1123,14 @@ public Metric GetMetric(
public Metric GetMetric(
MetricIdentifier metricIdentifier)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(metricIdentifier);
#else
if (metricIdentifier == null)
{
throw new ArgumentNullException(nameof(metricIdentifier));
}
#endif

// Build dimension names array from MetricIdentifier
string[] dimensionNames = null;
Expand Down Expand Up @@ -1231,10 +1239,14 @@ private static ActivityKind GetActivityKindForDependency(string dependencyType)
/// <returns>A reconstructed Exception with all diagnostic details.</returns>
private static Exception ConvertToException(ExceptionTelemetry telemetry)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(telemetry);
#else
if (telemetry == null)
{
throw new ArgumentNullException(nameof(telemetry));
}
#endif

Exception rootException = null;

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

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

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

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

// Set the current exception as the inner for the next iteration
innerException = currentException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,14 @@ public static IOperationHolder<T> StartOperation<T>(
string parentOperationId = null)
where T : OperationTelemetry, new()
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(telemetryClient);
#else
if (telemetryClient == null)
{
throw new ArgumentNullException(nameof(telemetryClient));
}
#endif

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

Expand Down Expand Up @@ -137,6 +141,10 @@ public static IOperationHolder<T> StartOperation<T>(
T operationTelemetry)
where T : OperationTelemetry
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(telemetryClient);
ArgumentNullException.ThrowIfNull(operationTelemetry);
#else
if (telemetryClient == null)
{
throw new ArgumentNullException(nameof(telemetryClient));
Expand All @@ -146,6 +154,7 @@ public static IOperationHolder<T> StartOperation<T>(
{
throw new ArgumentNullException(nameof(operationTelemetry));
}
#endif

if (string.IsNullOrEmpty(operationTelemetry.Name))
{
Expand Down Expand Up @@ -221,10 +230,14 @@ public static IOperationHolder<T> StartOperation<T>(
Activity activity)
where T : OperationTelemetry, new()
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(telemetryClient);
#else
if (telemetryClient == null)
{
throw new ArgumentNullException(nameof(telemetryClient));
}
#endif

if (activity == null)
{
Expand Down Expand Up @@ -275,10 +288,14 @@ public static void StopOperation<T>(
IOperationHolder<T> operation)
where T : OperationTelemetry
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(telemetryClient);
#else
if (telemetryClient == null)
{
throw new ArgumentNullException(nameof(telemetryClient));
}
#endif

if (operation == null)
{
Expand Down
Loading
Loading