From a26a43f012ef6afca563b43b16ab019698a3f062 Mon Sep 17 00:00:00 2001 From: Timothy Mothra Date: Tue, 17 Dec 2019 17:49:41 -0800 Subject: [PATCH] update fxcop to version 2.9.8 (#1499) * update fxcop to version 2.9.8 and fixing issues --- .rulesets/ApplicationInsightsSDKRules.ruleset | 10 +++--- .../Channel/InMemoryTransmitter.cs | 2 ++ .../Channel/SamplingScoreGenerator.cs | 5 +++ .../Channel/Transmission.cs | 5 +++ .../DataContracts/AvailabilityTelemetry.cs | 5 +++ .../DataContracts/EventTelemetry.cs | 5 +++ .../DataContracts/ExceptionTelemetry.cs | 5 +++ .../DataContracts/MetricTelemetry.cs | 5 +++ .../PageViewPerformanceTelemetry.cs | 5 +++ .../DataContracts/PageViewTelemetry.cs | 5 +++ .../DataContracts/TraceTelemetry.cs | 5 +++ .../ExperimentalFeaturesExtension.cs | 5 +++ .../Implementation/JsonSerializer.cs | 5 +++ .../TelemetryConfigurationExtensions.cs | 11 +++++++ .../TelemetryConfigurationFactory.cs | 2 ++ .../TelemetryContextExtensions.cs | 6 ++++ .../Implementation/TelemetryDebugWriter.cs | 5 +++ .../Implementation/Tracing/Extensions.cs | 11 +++++-- ...perationCorrelationTelemetryInitializer.cs | 6 ++++ .../SequencePropertyInitializer.cs | 5 +++ .../W3C/W3CActivityExtensions.cs | 30 +++++++++++++++++ .../Metrics/Extensibility/MetricExtensions.cs | 5 +++ .../Extensibility/MetricSeriesExtensions.cs | 5 +++ .../Microsoft.ApplicationInsights.csproj | 20 +++++++++-- .../OperationTelemetryExtensions.cs | 20 +++++++++++ .../TelemetryClient.cs | 15 +++++++++ .../ApplicationFolderProvider.cs | 12 ++++--- .../Implementation/TransmissionExtensions.cs | 4 ++- .../ServerTelemetryChannel.cs | 6 ++++ .../TelemetryChannel.csproj | 20 +++++++++-- CHANGELOG.md | 2 +- .../DiagnosticSourceListener.csproj | 20 +++++++++-- LOGGING/src/EtwCollector/EtwCollector.csproj | 20 +++++++++-- .../EventSourceListener.csproj | 20 +++++++++-- .../EventSourceTelemetryModule.cs | 10 ++++++ .../Implementation/EventDataExtensions.cs | 25 +++++++++++++- .../src/ILogger/ApplicationInsightsLogger.cs | 5 +++ ...icationInsightsLoggingBuilderExtensions.cs | 19 +++++++++-- LOGGING/src/ILogger/ILogger.csproj | 20 +++++++++-- .../ApplicationInsightsAppender.cs | 5 +++ .../Log4NetAppender/Log4NetAppender.csproj | 20 +++++++++-- .../NLogTarget/ApplicationInsightsTarget.cs | 11 +++++-- LOGGING/src/NLogTarget/NLogTarget.csproj | 20 +++++++++-- .../src/TraceListener/TraceListener.csproj | 20 +++++++++-- .../HostingDiagnosticListener.cs | 17 +++++++++- .../Implementation/MvcDiagnosticsListener.cs | 11 +++++++ ...icationInsightsWebHostBuilderExtensions.cs | 10 ++++++ .../Extensions/RequestCollectionOptions.cs | 3 +- .../Implementation/RoleNameContainer.cs | 8 ++--- .../TelemetryConfigurationOptions.cs | 7 +++- .../JavaScriptSnippet.cs | 10 ++++-- .../ApplicationInsightsLogger.cs | 8 +++++ ...licationInsightsLoggerFactoryExtensions.cs | 6 ++++ .../ApplicationInsightsLoggerProvider.cs | 7 ++++ ...soft.ApplicationInsights.AspNetCore.csproj | 22 +++++++++++-- .../RequestTrackingTelemetryModule.cs | 14 +++++--- ...ceRoleNameFromHostNameHeaderInitializer.cs | 8 ++++- .../ClientIpHeaderTelemetryInitializer.cs | 15 +++++++++ .../OperationNameTelemetryInitializer.cs | 16 +++++++++ .../SyntheticTelemetryInitializer.cs | 11 +++++++ .../WebSessionTelemetryInitializer.cs | 16 +++++++++ .../WebUserTelemetryInitializer.cs | 16 +++++++++ ...t.ApplicationInsights.WorkerService.csproj | 24 ++++++++++++-- .../ApplicationInsightsExtensions.cs | 9 +++-- .../ITelemetryModuleConfigurator.cs | 1 + .../Implementation/NoOpTelemetryModule.cs | 2 ++ .../TelemetryConfigurationOptionsSetup.cs | 7 ++++ .../ComponentVersionTelemetryInitializer.cs | 13 +++++++- ...ainNameRoleInstanceTelemetryInitializer.cs | 5 +++ .../ApplicationInsightsExtensionsTests.cs | 6 ++-- .../Logging/ApplicationInsightsLoggerTests.cs | 2 ++ .../Common/ConditionalWeakTableExtensions.cs | 6 ++++ .../DependencyCollector.csproj | 22 +++++++++++-- .../EventCounterCollector.csproj | 20 +++++++++-- .../HostingStartup/HostingStartup.csproj | 20 +++++++++-- .../TraceSourceForEventSource.cs | 5 +++ .../QuickPulse/QuickPulseServiceClient.cs | 33 +++++++++++-------- .../Perf.Shared/QuickPulseTelemetryModule.cs | 2 ++ .../PerformanceCollector/Perf.csproj | 20 +++++++++-- .../AccountIdTelemetryInitializer.cs | 21 +++++++++--- ...AuthenticatedUserIdTelemetryInitializer.cs | 21 +++++++++--- ...ceRoleNameFromHostNameHeaderInitializer.cs | 7 +++- .../ClientIpHeaderTelemetryInitializer.cs | 15 +++++++++ ...perationCorrelationTelemetryInitializer.cs | 21 +++++++++--- .../OperationNameTelemetryInitializer.cs | 23 ++++++++++--- .../RequestTrackingTelemetryModule.cs | 2 +- .../SessionTelemetryInitializer.cs | 21 +++++++++--- .../SyntheticUserAgentTelemetryInitializer.cs | 5 +++ .../UserTelemetryInitializer.cs | 20 ++++++++--- .../WebTestTelemetryInitializer.cs | 16 ++++++--- .../Web/AspNetDiagnosticTelemetryModule.cs | 5 +++ WEB/Src/Web/Web/Web.csproj | 20 +++++++++-- ...zureRoleEnvironmentTelemetryInitializer.cs | 5 +++ ...bAppRoleEnvironmentTelemetryInitializer.cs | 5 +++ ...ModeWithDebuggerAttachedTelemetryModule.cs | 5 +++ .../UnhandledExceptionTelemetryModule.cs | 2 ++ .../WindowsServer/WindowsServer.csproj | 22 +++++++++++-- 97 files changed, 981 insertions(+), 124 deletions(-) diff --git a/.rulesets/ApplicationInsightsSDKRules.ruleset b/.rulesets/ApplicationInsightsSDKRules.ruleset index 21db2911c4..959dd35d14 100644 --- a/.rulesets/ApplicationInsightsSDKRules.ruleset +++ b/.rulesets/ApplicationInsightsSDKRules.ruleset @@ -17,10 +17,10 @@ - - + + + @@ -85,9 +85,7 @@ - - + diff --git a/BASE/src/Microsoft.ApplicationInsights/Channel/InMemoryTransmitter.cs b/BASE/src/Microsoft.ApplicationInsights/Channel/InMemoryTransmitter.cs index 83c85d0bf2..9c80f20676 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Channel/InMemoryTransmitter.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Channel/InMemoryTransmitter.cs @@ -28,6 +28,8 @@ internal class InMemoryTransmitter : IDisposable /// A lock object to serialize the sending calls from Flush, OnFull event and the Runner. /// private object sendingLockObj = new object(); + + [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", Justification = "Object is disposed within the using statement of the " + nameof(Runner) + " method.")] private AutoResetEvent startRunnerEvent; private bool enabled = true; diff --git a/BASE/src/Microsoft.ApplicationInsights/Channel/SamplingScoreGenerator.cs b/BASE/src/Microsoft.ApplicationInsights/Channel/SamplingScoreGenerator.cs index 8596dd0859..44d79bc178 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Channel/SamplingScoreGenerator.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Channel/SamplingScoreGenerator.cs @@ -25,6 +25,11 @@ public static double GetSamplingScore(string value) /// Item sampling score. public static double GetSamplingScore(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + double samplingScore = 0; if (telemetry.Context.Operation.Id != null) diff --git a/BASE/src/Microsoft.ApplicationInsights/Channel/Transmission.cs b/BASE/src/Microsoft.ApplicationInsights/Channel/Transmission.cs index 37a5347435..a04dc8ad44 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Channel/Transmission.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Channel/Transmission.cs @@ -227,6 +227,11 @@ public virtual async Task SendAsync() /// public virtual Tuple Split(Func calculateLength) { + if (calculateLength == null) + { + throw new ArgumentNullException(nameof(calculateLength)); + } + Transmission transmissionA = this; Transmission transmissionB = null; diff --git a/BASE/src/Microsoft.ApplicationInsights/DataContracts/AvailabilityTelemetry.cs b/BASE/src/Microsoft.ApplicationInsights/DataContracts/AvailabilityTelemetry.cs index b78433941d..63d6c02e38 100644 --- a/BASE/src/Microsoft.ApplicationInsights/DataContracts/AvailabilityTelemetry.cs +++ b/BASE/src/Microsoft.ApplicationInsights/DataContracts/AvailabilityTelemetry.cs @@ -186,6 +186,11 @@ public ITelemetry DeepClone() /// public void SerializeData(ISerializationWriter serializationWriter) { + if (serializationWriter == null) + { + throw new ArgumentNullException(nameof(serializationWriter)); + } + serializationWriter.WriteProperty(this.Data); } diff --git a/BASE/src/Microsoft.ApplicationInsights/DataContracts/EventTelemetry.cs b/BASE/src/Microsoft.ApplicationInsights/DataContracts/EventTelemetry.cs index f101e939bb..2c2079ed8e 100644 --- a/BASE/src/Microsoft.ApplicationInsights/DataContracts/EventTelemetry.cs +++ b/BASE/src/Microsoft.ApplicationInsights/DataContracts/EventTelemetry.cs @@ -152,6 +152,11 @@ void ITelemetry.Sanitize() /// public void SerializeData(ISerializationWriter serializationWriter) { + if (serializationWriter == null) + { + throw new ArgumentNullException(nameof(serializationWriter)); + } + serializationWriter.WriteProperty(this.Data); } } diff --git a/BASE/src/Microsoft.ApplicationInsights/DataContracts/ExceptionTelemetry.cs b/BASE/src/Microsoft.ApplicationInsights/DataContracts/ExceptionTelemetry.cs index 54b75ac455..1e92a2b175 100644 --- a/BASE/src/Microsoft.ApplicationInsights/DataContracts/ExceptionTelemetry.cs +++ b/BASE/src/Microsoft.ApplicationInsights/DataContracts/ExceptionTelemetry.cs @@ -299,6 +299,11 @@ public ITelemetry DeepClone() /// public void SerializeData(ISerializationWriter serializationWriter) { + if (serializationWriter == null) + { + throw new ArgumentNullException(nameof(serializationWriter)); + } + serializationWriter.WriteProperty(this.Data.Data); } diff --git a/BASE/src/Microsoft.ApplicationInsights/DataContracts/MetricTelemetry.cs b/BASE/src/Microsoft.ApplicationInsights/DataContracts/MetricTelemetry.cs index 6b71411179..608b1ed138 100644 --- a/BASE/src/Microsoft.ApplicationInsights/DataContracts/MetricTelemetry.cs +++ b/BASE/src/Microsoft.ApplicationInsights/DataContracts/MetricTelemetry.cs @@ -259,6 +259,11 @@ public ITelemetry DeepClone() /// public void SerializeData(ISerializationWriter serializationWriter) { + if (serializationWriter == null) + { + throw new ArgumentNullException(nameof(serializationWriter)); + } + serializationWriter.WriteProperty(this.Data); } diff --git a/BASE/src/Microsoft.ApplicationInsights/DataContracts/PageViewPerformanceTelemetry.cs b/BASE/src/Microsoft.ApplicationInsights/DataContracts/PageViewPerformanceTelemetry.cs index 6e8a8dfbd2..1c2acb604f 100644 --- a/BASE/src/Microsoft.ApplicationInsights/DataContracts/PageViewPerformanceTelemetry.cs +++ b/BASE/src/Microsoft.ApplicationInsights/DataContracts/PageViewPerformanceTelemetry.cs @@ -242,6 +242,11 @@ void ITelemetry.Sanitize() /// public void SerializeData(ISerializationWriter serializationWriter) { + if (serializationWriter == null) + { + throw new ArgumentNullException(nameof(serializationWriter)); + } + serializationWriter.WriteProperty(this.Data); } } diff --git a/BASE/src/Microsoft.ApplicationInsights/DataContracts/PageViewTelemetry.cs b/BASE/src/Microsoft.ApplicationInsights/DataContracts/PageViewTelemetry.cs index 042dee389d..2d4c4568c2 100644 --- a/BASE/src/Microsoft.ApplicationInsights/DataContracts/PageViewTelemetry.cs +++ b/BASE/src/Microsoft.ApplicationInsights/DataContracts/PageViewTelemetry.cs @@ -197,6 +197,11 @@ public ITelemetry DeepClone() /// public void SerializeData(ISerializationWriter serializationWriter) { + if (serializationWriter == null) + { + throw new ArgumentNullException(nameof(serializationWriter)); + } + serializationWriter.WriteProperty(this.Data); } diff --git a/BASE/src/Microsoft.ApplicationInsights/DataContracts/TraceTelemetry.cs b/BASE/src/Microsoft.ApplicationInsights/DataContracts/TraceTelemetry.cs index d8e95ca2ab..f6a5eb2a90 100644 --- a/BASE/src/Microsoft.ApplicationInsights/DataContracts/TraceTelemetry.cs +++ b/BASE/src/Microsoft.ApplicationInsights/DataContracts/TraceTelemetry.cs @@ -153,6 +153,11 @@ public ITelemetry DeepClone() /// public void SerializeData(ISerializationWriter serializationWriter) { + if (serializationWriter == null) + { + throw new ArgumentNullException(nameof(serializationWriter)); + } + serializationWriter.WriteProperty(this.Data); } diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Experimental/ExperimentalFeaturesExtension.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Experimental/ExperimentalFeaturesExtension.cs index 17e178ee04..fa211143f1 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Experimental/ExperimentalFeaturesExtension.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Experimental/ExperimentalFeaturesExtension.cs @@ -25,6 +25,11 @@ public static class ExperimentalFeaturesExtension [EditorBrowsable(EditorBrowsableState.Never)] public static bool EvaluateExperimentalFeature(this TelemetryConfiguration telemetryConfiguration, string featureName) { + if (telemetryConfiguration == null) + { + throw new ArgumentNullException(nameof(telemetryConfiguration)); + } + return telemetryConfiguration.ExperimentalFeatures.Any(x => x.Equals(featureName, StringComparison.OrdinalIgnoreCase)); } } diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/JsonSerializer.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/JsonSerializer.cs index 9abfd3409f..a9e933e53f 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/JsonSerializer.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/JsonSerializer.cs @@ -52,6 +52,11 @@ public static string ContentType [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Disposing a MemoryStream multiple times is harmless.")] public static byte[] Serialize(IEnumerable telemetryItems, bool compress = true) { + if (telemetryItems == null) + { + throw new ArgumentNullException(nameof(telemetryItems)); + } + var memoryStream = new MemoryStream(); using (Stream compressedStream = compress ? CreateCompressedStream(memoryStream) : memoryStream) { diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryConfigurationExtensions.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryConfigurationExtensions.cs index f591c57adb..dc2f9dfd90 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryConfigurationExtensions.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryConfigurationExtensions.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Extensibility.Implementation { + using System; using System.ComponentModel; using Microsoft.ApplicationInsights.DataContracts; @@ -14,6 +15,11 @@ public static class TelemetryConfigurationExtensions /// public static double GetLastObservedSamplingPercentage(this TelemetryConfiguration configuration, SamplingTelemetryItemTypes samplingItemType) { + if (configuration == null) + { + throw new ArgumentNullException(nameof(configuration)); + } + return configuration.LastKnownSampleRateStore.GetLastObservedSamplingPercentage(samplingItemType); } @@ -22,6 +28,11 @@ public static double GetLastObservedSamplingPercentage(this TelemetryConfigurati /// public static void SetLastObservedSamplingPercentage(this TelemetryConfiguration configuration, SamplingTelemetryItemTypes samplingItemType, double value) { + if (configuration == null) + { + throw new ArgumentNullException(nameof(configuration)); + } + configuration.LastKnownSampleRateStore.SetLastObservedSamplingPercentage(samplingItemType, value); } } diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryConfigurationFactory.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryConfigurationFactory.cs index 0899194d2a..7ac8836080 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryConfigurationFactory.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryConfigurationFactory.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; @@ -50,6 +51,7 @@ public static TelemetryConfigurationFactory Instance set { instance = value; } } + [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "We want objects created in this method to live for the life of the application.")] public virtual void Initialize(TelemetryConfiguration configuration, TelemetryModules modules, string serializedConfiguration) { try diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryContextExtensions.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryContextExtensions.cs index 8bfd04bffe..4df795f08c 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryContextExtensions.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryContextExtensions.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Extensibility.Implementation { + using System; using System.ComponentModel; using Microsoft.ApplicationInsights.DataContracts; @@ -16,6 +17,11 @@ public static class TelemetryContextExtensions /// Internal context for TelemetryContext. public static InternalContext GetInternalContext(this TelemetryContext context) { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + return context.Internal; } } diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryDebugWriter.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryDebugWriter.cs index a211fbe45a..9cbb66e455 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryDebugWriter.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/TelemetryDebugWriter.cs @@ -30,6 +30,11 @@ public class TelemetryDebugWriter : IDebugOutput /// If specified, indicates the telemetry item was filtered out and not sent to the API. public static void WriteTelemetry(ITelemetry telemetry, string filteredBy = null) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + var output = PlatformSingleton.Current.GetDebugOutput(); if (output.IsAttached() && output.IsLogging()) { diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Tracing/Extensions.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Tracing/Extensions.cs index fbb859838d..64f61601f0 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Tracing/Extensions.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/Implementation/Tracing/Extensions.cs @@ -17,14 +17,19 @@ public static class Extensions /// public static string ToInvariantString(this Exception exception) { -#if !NETSTANDARD1_3 + if (exception == null) + { + return string.Empty; + } + +#if NETSTANDARD1_3 + return exception.ToString(); +#else CultureInfo originalUICulture = Thread.CurrentThread.CurrentUICulture; try { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; -#endif return exception.ToString(); -#if !NETSTANDARD1_3 } finally { diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/OperationCorrelationTelemetryInitializer.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/OperationCorrelationTelemetryInitializer.cs index 0b343f8a83..499db9c564 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/OperationCorrelationTelemetryInitializer.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/OperationCorrelationTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Extensibility { + using System; using System.Diagnostics; using Microsoft.ApplicationInsights; @@ -22,6 +23,11 @@ public class OperationCorrelationTelemetryInitializer : ITelemetryInitializer /// Target telemetry item to add operation context. public void Initialize(ITelemetry telemetryItem) { + if (telemetryItem == null) + { + throw new ArgumentNullException(nameof(telemetryItem)); + } + var itemOperationContext = telemetryItem.Context.Operation; var telemetryProp = telemetryItem as ISupportProperties; diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/SequencePropertyInitializer.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/SequencePropertyInitializer.cs index 6c9dd39961..1b5a58a9dc 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/SequencePropertyInitializer.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/SequencePropertyInitializer.cs @@ -20,6 +20,11 @@ public sealed class SequencePropertyInitializer : ITelemetryInitializer /// public void Initialize(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (string.IsNullOrEmpty(telemetry.Sequence)) { telemetry.Sequence = this.stablePrefix + Interlocked.Increment(ref this.currentNumber).ToString(CultureInfo.InvariantCulture); diff --git a/BASE/src/Microsoft.ApplicationInsights/Extensibility/W3C/W3CActivityExtensions.cs b/BASE/src/Microsoft.ApplicationInsights/Extensibility/W3C/W3CActivityExtensions.cs index 8d934799c9..f1167f71fe 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Extensibility/W3C/W3CActivityExtensions.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Extensibility/W3C/W3CActivityExtensions.cs @@ -65,6 +65,11 @@ public static Activity UpdateContextOnActivity(this Activity activity) [Obsolete("Activity from System.Diagnostics.DiagnosticSource 4.6.0 onwards natively support W3C.")] public static string GetTraceparent(this Activity activity) { + if (activity == null) + { + throw new ArgumentNullException(nameof(activity)); + } + // Activity.ID is the trasceparent header. return activity.Id; } @@ -90,6 +95,11 @@ public static void SetTraceparent(this Activity activity, string value) [Obsolete("Activity from System.Diagnostics.DiagnosticSource 4.6.0 onwards natively support W3C.")] public static string GetTracestate(this Activity activity) { + if (activity == null) + { + throw new ArgumentNullException(nameof(activity)); + } + return activity.TraceStateString; } @@ -102,6 +112,11 @@ public static string GetTracestate(this Activity activity) [Obsolete("Activity from System.Diagnostics.DiagnosticSource 4.6.0 onwards natively support W3C.")] public static void SetTracestate(this Activity activity, string value) { + if (activity == null) + { + throw new ArgumentNullException(nameof(activity)); + } + activity.TraceStateString = value; } @@ -114,6 +129,11 @@ public static void SetTracestate(this Activity activity, string value) [Obsolete("Activity from System.Diagnostics.DiagnosticSource 4.6.0 onwards natively support W3C. Use Activity.TraceId to get Trace ID")] public static string GetTraceId(this Activity activity) { + if (activity == null) + { + throw new ArgumentNullException(nameof(activity)); + } + return activity.TraceId.ToHexString(); } @@ -126,6 +146,11 @@ public static string GetTraceId(this Activity activity) [Obsolete("Activity from System.Diagnostics.DiagnosticSource 4.6.0 onwards natively support W3C. Use Activity.SpanId to get Span ID")] public static string GetSpanId(this Activity activity) { + if (activity == null) + { + throw new ArgumentNullException(nameof(activity)); + } + return activity.SpanId.ToHexString(); } @@ -138,6 +163,11 @@ public static string GetSpanId(this Activity activity) [Obsolete("Activity from System.Diagnostics.DiagnosticSource 4.6.0 onwards natively support W3C. Use Activity.ParentSpanId to get ParentSpan ID")] public static string GetParentSpanId(this Activity activity) { + if (activity == null) + { + throw new ArgumentNullException(nameof(activity)); + } + return activity.ParentSpanId.ToHexString(); } diff --git a/BASE/src/Microsoft.ApplicationInsights/Metrics/Extensibility/MetricExtensions.cs b/BASE/src/Microsoft.ApplicationInsights/Metrics/Extensibility/MetricExtensions.cs index ea2696b9cb..6723eeaf57 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Metrics/Extensibility/MetricExtensions.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Metrics/Extensibility/MetricExtensions.cs @@ -15,6 +15,11 @@ public static class MetricExtensions /// The configuration of the metric. public static MetricConfiguration GetConfiguration(this Metric metric) { + if (metric == null) + { + throw new ArgumentNullException(nameof(metric)); + } + return metric.configuration; } diff --git a/BASE/src/Microsoft.ApplicationInsights/Metrics/Extensibility/MetricSeriesExtensions.cs b/BASE/src/Microsoft.ApplicationInsights/Metrics/Extensibility/MetricSeriesExtensions.cs index 2e0a511786..9383914e74 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Metrics/Extensibility/MetricSeriesExtensions.cs +++ b/BASE/src/Microsoft.ApplicationInsights/Metrics/Extensibility/MetricSeriesExtensions.cs @@ -16,6 +16,11 @@ public static class MetricSeriesExtensions /// Configuration of the specified series. public static IMetricSeriesConfiguration GetConfiguration(this MetricSeries metricSeries) { + if (metricSeries == null) + { + throw new ArgumentNullException(nameof(metricSeries)); + } + return metricSeries.configuration; } } diff --git a/BASE/src/Microsoft.ApplicationInsights/Microsoft.ApplicationInsights.csproj b/BASE/src/Microsoft.ApplicationInsights/Microsoft.ApplicationInsights.csproj index ae454fa899..718921babf 100644 --- a/BASE/src/Microsoft.ApplicationInsights/Microsoft.ApplicationInsights.csproj +++ b/BASE/src/Microsoft.ApplicationInsights/Microsoft.ApplicationInsights.csproj @@ -18,7 +18,7 @@ - + All @@ -26,7 +26,7 @@ All - + All @@ -34,6 +34,22 @@ + + + + + false + true + + + + + false + false + + + + diff --git a/BASE/src/Microsoft.ApplicationInsights/OperationTelemetryExtensions.cs b/BASE/src/Microsoft.ApplicationInsights/OperationTelemetryExtensions.cs index 333eec4527..8caf4d3a9b 100644 --- a/BASE/src/Microsoft.ApplicationInsights/OperationTelemetryExtensions.cs +++ b/BASE/src/Microsoft.ApplicationInsights/OperationTelemetryExtensions.cs @@ -28,6 +28,11 @@ public static void Start(this OperationTelemetry telemetry) /// A high-resolution timestamp from . public static void Start(this OperationTelemetry telemetry, long timestamp) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + telemetry.Timestamp = PreciseTimestamp.GetUtcNow(); // Begin time is used internally for calculating duration of operation at the end call, @@ -44,6 +49,11 @@ public static void Start(this OperationTelemetry telemetry, long timestamp) /// Telemetry item object that calls this extension method. public static void Stop(this OperationTelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (telemetry.BeginTimeInTicks != 0L) { StopImpl(telemetry, timestamp: Stopwatch.GetTimestamp()); @@ -61,6 +71,11 @@ public static void Stop(this OperationTelemetry telemetry) /// A high-resolution timestamp from . public static void Stop(this OperationTelemetry telemetry, long timestamp) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (telemetry.BeginTimeInTicks != 0L) { StopImpl(telemetry, timestamp); @@ -77,6 +92,11 @@ public static void Stop(this OperationTelemetry telemetry, long timestamp) /// Telemetry to initialize Operation id for. public static void GenerateOperationId(this OperationTelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + telemetry.GenerateId(); } diff --git a/BASE/src/Microsoft.ApplicationInsights/TelemetryClient.cs b/BASE/src/Microsoft.ApplicationInsights/TelemetryClient.cs index 5fdf86697e..4e1bf7a6b8 100644 --- a/BASE/src/Microsoft.ApplicationInsights/TelemetryClient.cs +++ b/BASE/src/Microsoft.ApplicationInsights/TelemetryClient.cs @@ -437,6 +437,11 @@ public void TrackAvailability(AvailabilityTelemetry telemetry) [EditorBrowsable(EditorBrowsableState.Never)] public void Track(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + // TALK TO YOUR TEAM MATES BEFORE CHANGING THIS. // This method needs to be public so that we can build and ship new telemetry types without having to ship core. // It is hidden from intellisense to prevent customer confusion. @@ -461,6 +466,11 @@ public void Track(ITelemetry telemetry) [EditorBrowsable(EditorBrowsableState.Never)] public void InitializeInstrumentationKey(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + string instrumentationKey = this.Context.InstrumentationKey; if (string.IsNullOrEmpty(instrumentationKey)) @@ -478,6 +488,11 @@ public void InitializeInstrumentationKey(ITelemetry telemetry) [EditorBrowsable(EditorBrowsableState.Never)] public void Initialize(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + ISupportAdvancedSampling telemetryWithSampling = telemetry as ISupportAdvancedSampling; // Telemetry can be already sampled out if that decision was made before calling Track() diff --git a/BASE/src/ServerTelemetryChannel/Implementation/ApplicationFolderProvider.cs b/BASE/src/ServerTelemetryChannel/Implementation/ApplicationFolderProvider.cs index 75e1241a2a..03ca2ad367 100644 --- a/BASE/src/ServerTelemetryChannel/Implementation/ApplicationFolderProvider.cs +++ b/BASE/src/ServerTelemetryChannel/Implementation/ApplicationFolderProvider.cs @@ -121,12 +121,16 @@ private static void CheckAccessPermissions(DirectoryInfo telemetryDirectory) private static string GetSHA256Hash(string input) { - byte[] inputBits = Encoding.Unicode.GetBytes(input); - byte[] hashBits = CreateSHA256().ComputeHash(inputBits); var hashString = new StringBuilder(); - foreach (byte b in hashBits) + + byte[] inputBits = Encoding.Unicode.GetBytes(input); + using (var sha256 = CreateSHA256()) { - hashString.Append(b.ToString("x2", CultureInfo.InvariantCulture)); + byte[] hashBits = sha256.ComputeHash(inputBits); + foreach (byte b in hashBits) + { + hashString.Append(b.ToString("x2", CultureInfo.InvariantCulture)); + } } return hashString.ToString(); diff --git a/BASE/src/ServerTelemetryChannel/Implementation/TransmissionExtensions.cs b/BASE/src/ServerTelemetryChannel/Implementation/TransmissionExtensions.cs index 1d6857731e..94f72352f6 100644 --- a/BASE/src/ServerTelemetryChannel/Implementation/TransmissionExtensions.cs +++ b/BASE/src/ServerTelemetryChannel/Implementation/TransmissionExtensions.cs @@ -1,6 +1,7 @@ namespace Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.Implementation { using System; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; @@ -15,6 +16,7 @@ internal static class TransmissionExtensions /// Loads a new transmission from the specified . /// /// Return transmission loaded from file; throws FormatException is file is corrupted. + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposing the StreamReader will also dispose the stream.")] public static Transmission Load(Stream stream) { var reader = new StreamReader(stream); @@ -28,10 +30,10 @@ public static Transmission Load(Stream stream) /// /// Saves the transmission to the specified . /// + [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposing the StreamWriter will also dispose the stream.")] public static void Save(this Transmission transmission, Stream stream) { var writer = new StreamWriter(stream); - writer.WriteLine(transmission.EndpointAddress.ToString()); writer.Write(ContentTypeHeader); diff --git a/BASE/src/ServerTelemetryChannel/ServerTelemetryChannel.cs b/BASE/src/ServerTelemetryChannel/ServerTelemetryChannel.cs index 1fdaa3eb5a..440eefeb6e 100644 --- a/BASE/src/ServerTelemetryChannel/ServerTelemetryChannel.cs +++ b/BASE/src/ServerTelemetryChannel/ServerTelemetryChannel.cs @@ -30,6 +30,7 @@ public sealed class ServerTelemetryChannel : ITelemetryChannel, ITelemetryModule /// Initializes a new instance of the class. /// #if !NETSTANDARD + [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "WebApplicationLifecycle is needed for the life of the application.")] public ServerTelemetryChannel() : this(new Network(), new WebApplicationLifecycle()) #else // TODO: IApplicationLifecycle implementation for netcore need to be written instead of null here. @@ -315,6 +316,11 @@ public void Flush() [SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings", Justification = "Private variable, low risk.")] public void Initialize(TelemetryConfiguration configuration) { + if (configuration == null) + { + throw new ArgumentNullException(nameof(configuration)); + } + this.Transmitter.Initialize(); this.EndpointAddress = new Uri(configuration.EndpointContainer.Ingestion, "v2/track").AbsoluteUri; diff --git a/BASE/src/ServerTelemetryChannel/TelemetryChannel.csproj b/BASE/src/ServerTelemetryChannel/TelemetryChannel.csproj index f508204b77..4915d239de 100644 --- a/BASE/src/ServerTelemetryChannel/TelemetryChannel.csproj +++ b/BASE/src/ServerTelemetryChannel/TelemetryChannel.csproj @@ -25,7 +25,7 @@ True - + All @@ -33,7 +33,7 @@ All - + All @@ -41,6 +41,22 @@ + + + + + false + true + + + + + false + false + + + + diff --git a/CHANGELOG.md b/CHANGELOG.md index ce7e7414ee..26a891bdcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ # Changelog ## VNext - +- [Upgraded FxCop and fixed several issues related to null checks and disposing objects.](https://github.com/microsoft/ApplicationInsights-dotnet/pull/1499) ## Version 2.12.0 - [Fix IndexOutOfRangeException in W3CUtilities.TryGetTraceId](https://github.com/microsoft/ApplicationInsights-dotnet/pull/1327) diff --git a/LOGGING/src/DiagnosticSourceListener/DiagnosticSourceListener.csproj b/LOGGING/src/DiagnosticSourceListener/DiagnosticSourceListener.csproj index 7247be29a4..00bc07586a 100644 --- a/LOGGING/src/DiagnosticSourceListener/DiagnosticSourceListener.csproj +++ b/LOGGING/src/DiagnosticSourceListener/DiagnosticSourceListener.csproj @@ -29,7 +29,7 @@ - + All @@ -37,11 +37,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/LOGGING/src/EtwCollector/EtwCollector.csproj b/LOGGING/src/EtwCollector/EtwCollector.csproj index bc96b794c6..3787099370 100644 --- a/LOGGING/src/EtwCollector/EtwCollector.csproj +++ b/LOGGING/src/EtwCollector/EtwCollector.csproj @@ -25,7 +25,7 @@ - + All @@ -33,11 +33,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/LOGGING/src/EventSourceListener/EventSourceListener.csproj b/LOGGING/src/EventSourceListener/EventSourceListener.csproj index 3ee3423c23..0699295275 100644 --- a/LOGGING/src/EventSourceListener/EventSourceListener.csproj +++ b/LOGGING/src/EventSourceListener/EventSourceListener.csproj @@ -30,7 +30,7 @@ - + All @@ -38,11 +38,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/LOGGING/src/EventSourceListener/EventSourceTelemetryModule.cs b/LOGGING/src/EventSourceListener/EventSourceTelemetryModule.cs index 14d8912d0c..218f6df424 100644 --- a/LOGGING/src/EventSourceListener/EventSourceTelemetryModule.cs +++ b/LOGGING/src/EventSourceListener/EventSourceTelemetryModule.cs @@ -156,6 +156,11 @@ public void Initialize(TelemetryConfiguration configuration) /// Event to process. protected override void OnEventWritten(EventWrittenEventArgs eventData) { + if (eventData == null) + { + throw new ArgumentNullException(nameof(eventData)); + } + // Suppress events from TplEventSource--they are mostly interesting for debugging task processing and interaction, // and not that useful for production tracing. However, TPL EventSource must be enabled to get hierarchical activity IDs. if (this.initialized && !TplActivities.TplEventSourceGuid.Equals(eventData.EventSource.Guid)) @@ -179,6 +184,11 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) /// Then, as new EventSources are created, the EventListener will receive notifications about them. protected override void OnEventSourceCreated(EventSource eventSource) { + if (eventSource == null) + { + throw new ArgumentNullException(nameof(eventSource)); + } + // There is a bug in the EventListener library that causes this override to be called before the object is fully constructed. // We need to remember all EventSources we get notified about to do the initialization correctly (event if it happens multiple times). // If we are initialized, we can follow up with enabling the source straight away. diff --git a/LOGGING/src/EventSourceListener/Implementation/EventDataExtensions.cs b/LOGGING/src/EventSourceListener/Implementation/EventDataExtensions.cs index a87c9bd697..7605974988 100644 --- a/LOGGING/src/EventSourceListener/Implementation/EventDataExtensions.cs +++ b/LOGGING/src/EventSourceListener/Implementation/EventDataExtensions.cs @@ -41,6 +41,11 @@ public static class EventDataExtensions /// The source for the telemetry data. public static TraceTelemetry CreateTraceTelementry(this EventWrittenEventArgs eventSourceEvent) { + if (eventSourceEvent == null) + { + throw new ArgumentNullException(nameof(eventSourceEvent)); + } + string formattedMessage = null; if (eventSourceEvent.Message != null) { @@ -66,6 +71,16 @@ public static TraceTelemetry CreateTraceTelementry(this EventWrittenEventArgs ev /// Event to extract values from. public static TraceTelemetry PopulateStandardProperties(this TraceTelemetry telemetry, EventWrittenEventArgs eventSourceEvent) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (eventSourceEvent == null) + { + throw new ArgumentNullException(nameof(eventSourceEvent)); + } + if (!string.IsNullOrWhiteSpace(eventSourceEvent.EventSource.Name)) { telemetry.AddProperty(ProviderNameProperty, eventSourceEvent.EventSource.Name); @@ -111,7 +126,15 @@ public static TraceTelemetry PopulateStandardProperties(this TraceTelemetry tele /// Event to extract values from. public static TraceTelemetry PopulatePayloadProperties(this TraceTelemetry telemetry, EventWrittenEventArgs eventSourceEvent) { - Debug.Assert(telemetry != null, "Should have received a valid TraceTelemetry object"); + if (eventSourceEvent == null) + { + throw new ArgumentNullException(nameof(eventSourceEvent)); + } + + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } if (eventSourceEvent.Payload == null || eventSourceEvent.PayloadNames == null) { diff --git a/LOGGING/src/ILogger/ApplicationInsightsLogger.cs b/LOGGING/src/ILogger/ApplicationInsightsLogger.cs index 3e086e9d9c..32e2c25022 100644 --- a/LOGGING/src/ILogger/ApplicationInsightsLogger.cs +++ b/LOGGING/src/ILogger/ApplicationInsightsLogger.cs @@ -78,6 +78,11 @@ public bool IsEnabled(LogLevel logLevel) /// Function to create a string message of the and . public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) { + if (formatter == null) + { + throw new ArgumentNullException(nameof(formatter)); + } + if (this.IsEnabled(logLevel)) { if (exception == null || !this.applicationInsightsLoggerOptions.TrackExceptionsAsExceptionTelemetry) diff --git a/LOGGING/src/ILogger/ApplicationInsightsLoggingBuilderExtensions.cs b/LOGGING/src/ILogger/ApplicationInsightsLoggingBuilderExtensions.cs index 80e65e2f8e..7bd729a9af 100644 --- a/LOGGING/src/ILogger/ApplicationInsightsLoggingBuilderExtensions.cs +++ b/LOGGING/src/ILogger/ApplicationInsightsLoggingBuilderExtensions.cs @@ -34,10 +34,13 @@ public static ILoggingBuilder AddApplicationInsights(this ILoggingBuilder builde /// The to use. /// Application insights instrumentation key. /// Logging builder with Application Insights added to it. - public static ILoggingBuilder AddApplicationInsights( - this ILoggingBuilder builder, - string instrumentationKey) + public static ILoggingBuilder AddApplicationInsights(this ILoggingBuilder builder, string instrumentationKey) { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + return builder.AddApplicationInsights( (telemetryConfiguration) => telemetryConfiguration.InstrumentationKey = instrumentationKey, (applicationInsightsOptions) => { }); @@ -55,6 +58,11 @@ public static ILoggingBuilder AddApplicationInsights( string instrumentationKey, Action configureApplicationInsightsLoggerOptions) { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + return builder.AddApplicationInsights( (telemetryConfiguration) => telemetryConfiguration.InstrumentationKey = instrumentationKey, configureApplicationInsightsLoggerOptions); @@ -69,6 +77,11 @@ public static ILoggingBuilder AddApplicationInsights( this ILoggingBuilder builder, Action configureApplicationInsightsLoggerOptions) { + if (builder == null) + { + throw new ArgumentNullException(nameof(builder)); + } + return builder.AddApplicationInsights( (telemetryConfiguration) => { }, configureApplicationInsightsLoggerOptions); diff --git a/LOGGING/src/ILogger/ILogger.csproj b/LOGGING/src/ILogger/ILogger.csproj index 6915f50237..b48e9a016b 100644 --- a/LOGGING/src/ILogger/ILogger.csproj +++ b/LOGGING/src/ILogger/ILogger.csproj @@ -32,7 +32,7 @@ true - + All @@ -40,11 +40,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/LOGGING/src/Log4NetAppender/ApplicationInsightsAppender.cs b/LOGGING/src/Log4NetAppender/ApplicationInsightsAppender.cs index 650ce009d7..fd6420e96a 100644 --- a/LOGGING/src/Log4NetAppender/ApplicationInsightsAppender.cs +++ b/LOGGING/src/Log4NetAppender/ApplicationInsightsAppender.cs @@ -84,6 +84,11 @@ public override bool Flush(int millisecondsTimeout) /// Events to be logged. protected override void Append(LoggingEvent loggingEvent) { + if (loggingEvent == null) + { + throw new ArgumentNullException(nameof(loggingEvent)); + } + if (loggingEvent.ExceptionObject != null) { this.SendException(loggingEvent); diff --git a/LOGGING/src/Log4NetAppender/Log4NetAppender.csproj b/LOGGING/src/Log4NetAppender/Log4NetAppender.csproj index 5692768681..11818643c3 100644 --- a/LOGGING/src/Log4NetAppender/Log4NetAppender.csproj +++ b/LOGGING/src/Log4NetAppender/Log4NetAppender.csproj @@ -19,7 +19,7 @@ $(PackageTags) Log4Net - + All @@ -27,11 +27,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs index 454fa4ab44..7d5e65d079 100644 --- a/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs +++ b/LOGGING/src/NLogTarget/ApplicationInsightsTarget.cs @@ -96,7 +96,7 @@ internal void BuildPropertyBag(LogEventInfo logEvent, ITelemetry trace) var contextProperty = this.ContextProperties[i]; if (!string.IsNullOrEmpty(contextProperty.Name) && contextProperty.Layout != null) { - string propertyValue = RenderLogEvent(contextProperty.Layout, logEvent); + string propertyValue = this.RenderLogEvent(contextProperty.Layout, logEvent); PopulatePropertyBag(propertyBag, contextProperty.Name, propertyValue); } } @@ -156,6 +156,11 @@ protected override void Write(LogEventInfo logEvent) /// The asynchronous continuation. protected override void FlushAsync(AsyncContinuation asyncContinuation) { + if (asyncContinuation == null) + { + throw new ArgumentNullException(nameof(asyncContinuation)); + } + try { this.TelemetryClient.Flush(); @@ -256,7 +261,7 @@ private void SendException(LogEventInfo logEvent) Message = $"{logEvent.Exception.GetType().ToString()}: {logEvent.Exception.Message}", }; - string logMessage = RenderLogEvent(this.Layout, logEvent); + string logMessage = this.RenderLogEvent(this.Layout, logEvent); if (!string.IsNullOrEmpty(logMessage)) { exceptionTelemetry.Properties.Add("Message", logMessage); @@ -268,7 +273,7 @@ private void SendException(LogEventInfo logEvent) private void SendTrace(LogEventInfo logEvent) { - string logMessage = RenderLogEvent(this.Layout, logEvent); + string logMessage = this.RenderLogEvent(this.Layout, logEvent); var trace = new TraceTelemetry(logMessage) { SeverityLevel = GetSeverityLevel(logEvent.Level), diff --git a/LOGGING/src/NLogTarget/NLogTarget.csproj b/LOGGING/src/NLogTarget/NLogTarget.csproj index e2d0661d52..6c1b9d8c11 100644 --- a/LOGGING/src/NLogTarget/NLogTarget.csproj +++ b/LOGGING/src/NLogTarget/NLogTarget.csproj @@ -19,7 +19,7 @@ $(PackageTags) NLog - + All @@ -27,11 +27,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/LOGGING/src/TraceListener/TraceListener.csproj b/LOGGING/src/TraceListener/TraceListener.csproj index c3abc37da2..2f2505bfb6 100644 --- a/LOGGING/src/TraceListener/TraceListener.csproj +++ b/LOGGING/src/TraceListener/TraceListener.csproj @@ -19,7 +19,7 @@ $(PackageTags) TraceListener - + All @@ -27,11 +27,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/DiagnosticListeners/Implementation/HostingDiagnosticListener.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/DiagnosticListeners/Implementation/HostingDiagnosticListener.cs index 5b60f46564..d529d11f52 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/DiagnosticListeners/Implementation/HostingDiagnosticListener.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/DiagnosticListeners/Implementation/HostingDiagnosticListener.cs @@ -147,6 +147,8 @@ public void OnSubscribe() /// /// Diagnostic event handler method for 'Microsoft.AspNetCore.Mvc.BeforeAction' event. /// + /// HttpContext is used to retrieve information about the Request and Response. + /// Used to get the name of the request. public void OnBeforeAction(HttpContext httpContext, IDictionary routeValues) { var telemetry = httpContext.Features.Get(); @@ -165,6 +167,7 @@ public void OnBeforeAction(HttpContext httpContext, IDictionary /// /// Diagnostic event handler method for 'Microsoft.AspNetCore.Hosting.HttpRequestIn.Start' event. This is from 2.XX runtime. /// + /// HttpContext is used to retrieve information about the Request and Response. public void OnHttpRequestInStart(HttpContext httpContext) { if (this.client.IsEnabled()) @@ -296,6 +299,7 @@ public void OnHttpRequestInStart(HttpContext httpContext) /// /// Diagnostic event handler method for 'Microsoft.AspNetCore.Hosting.HttpRequestIn.Stop' event. This is from 2.XX runtime. /// + /// HttpContext is used to retrieve information about the Request and Response. public void OnHttpRequestInStop(HttpContext httpContext) { this.EndRequest(httpContext, Stopwatch.GetTimestamp()); @@ -304,6 +308,8 @@ public void OnHttpRequestInStop(HttpContext httpContext) /// /// Diagnostic event handler method for 'Microsoft.AspNetCore.Hosting.BeginRequest' event. This is from 1.XX runtime. /// + /// HttpContext is used to retrieve information about the Request and Response. + /// Used to set the request start property. public void OnBeginRequest(HttpContext httpContext, long timestamp) { if (this.client.IsEnabled() && this.aspNetCoreMajorVersion == AspNetCoreMajorVersion.One) @@ -384,6 +390,8 @@ public void OnBeginRequest(HttpContext httpContext, long timestamp) /// /// Diagnostic event handler method for 'Microsoft.AspNetCore.Hosting.EndRequest' event. This is from 1.XX runtime. /// + /// HttpContext is used to retrieve information about the Request and Response. + /// Used to set request stop property. public void OnEndRequest(HttpContext httpContext, long timestamp) { if (this.aspNetCoreMajorVersion == AspNetCoreMajorVersion.One) @@ -395,6 +403,8 @@ public void OnEndRequest(HttpContext httpContext, long timestamp) /// /// Diagnostic event handler method for 'Microsoft.AspNetCore.Hosting.UnhandledException' event. /// + /// HttpContext is used to retrieve information about the Request and Response. + /// Used to create exception telemetry. public void OnHostingException(HttpContext httpContext, Exception exception) { this.OnException(httpContext, exception); @@ -410,6 +420,8 @@ public void OnHostingException(HttpContext httpContext, Exception exception) /// /// Diagnostic event handler method for 'Microsoft.AspNetCore.Hosting.HandledException' event. /// + /// HttpContext is used to retrieve information about the Request and Response. + /// Used to create exception telemetry. public void OnDiagnosticsHandledException(HttpContext httpContext, Exception exception) { this.OnException(httpContext, exception); @@ -418,6 +430,8 @@ public void OnDiagnosticsHandledException(HttpContext httpContext, Exception exc /// /// Diagnostic event handler method for 'Microsoft.AspNetCore.Diagnostics.UnhandledException' event. /// + /// HttpContext is used to retrieve information about the Request and Response. + /// Used to create exception telemetry. public void OnDiagnosticsUnhandledException(HttpContext httpContext, Exception exception) { this.OnException(httpContext, exception); @@ -429,6 +443,7 @@ public void Dispose() SubscriptionManager.Detach(this); } + /// public void OnNext(KeyValuePair value) { HttpContext httpContext = null; @@ -929,7 +944,7 @@ private void OnException(HttpContext httpContext, Exception exception) } var exceptionTelemetry = new ExceptionTelemetry(exception); - exceptionTelemetry.HandledAt = ExceptionHandledAt.Platform; + exceptionTelemetry.Properties["handledAt"] = "Platform"; exceptionTelemetry.Context.GetInternalContext().SdkVersion = this.sdkVersion; this.client.Track(exceptionTelemetry); } diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/DiagnosticListeners/Implementation/MvcDiagnosticsListener.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/DiagnosticListeners/Implementation/MvcDiagnosticsListener.cs index fcf0f8ad01..cb7b1c4669 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/DiagnosticListeners/Implementation/MvcDiagnosticsListener.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/DiagnosticListeners/Implementation/MvcDiagnosticsListener.cs @@ -7,6 +7,7 @@ namespace Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners using Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners.Implementation; using Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.Tracing; using Microsoft.ApplicationInsights.DataContracts; + using Microsoft.ApplicationInsights.DependencyCollector; using Microsoft.AspNetCore.Http; /// @@ -31,10 +32,20 @@ public class MvcDiagnosticsListener : IApplicationInsightDiagnosticListener /// public void OnBeforeAction(HttpContext httpContext, IDictionary routeValues) { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + var telemetry = httpContext.Features.Get(); if (telemetry != null && string.IsNullOrEmpty(telemetry.Name)) { + if (routeValues == null) + { + throw new ArgumentNullException(nameof(routeValues)); + } + string name = GetNameFromRouteContext(routeValues); if (!string.IsNullOrEmpty(name)) { diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/ApplicationInsightsWebHostBuilderExtensions.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/ApplicationInsightsWebHostBuilderExtensions.cs index abad533467..2371cc6959 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/ApplicationInsightsWebHostBuilderExtensions.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/ApplicationInsightsWebHostBuilderExtensions.cs @@ -17,6 +17,11 @@ public static class ApplicationInsightsWebHostBuilderExtensions [Obsolete("This method is deprecated in favor of AddApplicationInsightsTelemetry() extension method on IServiceCollection.")] public static IWebHostBuilder UseApplicationInsights(this IWebHostBuilder webHostBuilder) { + if (webHostBuilder == null) + { + throw new ArgumentNullException(nameof(webHostBuilder)); + } + webHostBuilder.ConfigureServices(collection => { collection.AddApplicationInsightsTelemetry(); @@ -34,6 +39,11 @@ public static IWebHostBuilder UseApplicationInsights(this IWebHostBuilder webHos [Obsolete("This method is deprecated in favor of AddApplicationInsightsTelemetry(string instrumentationKey) extension method on IServiceCollection.")] public static IWebHostBuilder UseApplicationInsights(this IWebHostBuilder webHostBuilder, string instrumentationKey) { + if (webHostBuilder == null) + { + throw new ArgumentNullException(nameof(webHostBuilder)); + } + webHostBuilder.ConfigureServices(collection => collection.AddApplicationInsightsTelemetry(instrumentationKey)); return webHostBuilder; } diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/RequestCollectionOptions.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/RequestCollectionOptions.cs index 0cc1168550..1eed1d6d06 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/RequestCollectionOptions.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Extensions/RequestCollectionOptions.cs @@ -22,7 +22,6 @@ public RequestCollectionOptions() #else this.TrackExceptions = true; #endif - this.EnableW3CDistributedTracing = true; } /// @@ -41,6 +40,6 @@ public RequestCollectionOptions() /// Gets or sets a value indicating whether W3C distributed tracing standard is enabled. /// [Obsolete("This flag is obsolete and noop. Use System.Diagnostics.Activity.DefaultIdFormat (along with ForceDefaultIdFormat) flags instead.")] - public bool EnableW3CDistributedTracing { get; set; } + public bool EnableW3CDistributedTracing { get; set; } = true; } } diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Implementation/RoleNameContainer.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Implementation/RoleNameContainer.cs index eede7d4c72..edcbe26f76 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Implementation/RoleNameContainer.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Implementation/RoleNameContainer.cs @@ -13,7 +13,7 @@ internal class RoleNameContainer private const string WebAppHostNameHeaderName = "WAS-DEFAULT-HOSTNAME"; private const string WebAppHostNameEnvironmentVariable = "WEBSITE_HOSTNAME"; - private static string roleName = string.Empty; + private string roleName = string.Empty; /// /// Initializes a new instance of the class. @@ -39,13 +39,13 @@ public RoleNameContainer(string hostNameSuffix = ".azurewebsites.net") /// public string RoleName { - get => roleName; + get => this.roleName; set { - if (value != roleName) + if (value != this.roleName) { - Interlocked.Exchange(ref roleName, value); + Interlocked.Exchange(ref this.roleName, value); } } } diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Implementation/TelemetryConfigurationOptions.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Implementation/TelemetryConfigurationOptions.cs index 7369f26dde..dbfe9659e2 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Implementation/TelemetryConfigurationOptions.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Implementation/TelemetryConfigurationOptions.cs @@ -1,6 +1,7 @@ namespace Microsoft.Extensions.DependencyInjection { using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.Options; @@ -35,7 +36,9 @@ public TelemetryConfigurationOptions(IEnumerableTrue is TelemertryConfiguration.Active was previously configured. private static bool IsActiveConfigured(string instrumentationKey) { +#pragma warning disable CS0618 // This must be maintained for backwards compatibility. var active = TelemetryConfiguration.Active; +#pragma warning restore CS0618 if (string.IsNullOrEmpty(active.InstrumentationKey) && !string.IsNullOrEmpty(instrumentationKey)) { return false; diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/JavaScriptSnippet.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/JavaScriptSnippet.cs index 0b9d2c3e4e..e961bd2724 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/JavaScriptSnippet.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/JavaScriptSnippet.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore { + using System; using System.Globalization; using System.Security.Principal; using System.Text.Encodings.Web; @@ -43,6 +44,11 @@ public JavaScriptSnippet( IHttpContextAccessor httpContextAccessor, JavaScriptEncoder encoder = null) { + if (serviceOptions == null) + { + throw new ArgumentNullException(nameof(serviceOptions)); + } + this.telemetryConfiguration = telemetryConfiguration; this.httpContextAccessor = httpContextAccessor; this.enableAuthSnippet = serviceOptions.Value.EnableAuthenticationTrackingJavaScript; @@ -63,7 +69,7 @@ public string FullScript string insertConfig; if (!string.IsNullOrEmpty(this.telemetryConfiguration.ConnectionString)) { - insertConfig = string.Format(CultureInfo.InvariantCulture, "connectionString: '{0}'", this.telemetryConfiguration.ConnectionString); + insertConfig = string.Format(CultureInfo.InvariantCulture, "connectionString: '{0}'", this.telemetryConfiguration.ConnectionString); } else if (!string.IsNullOrEmpty(this.telemetryConfiguration.InstrumentationKey)) { @@ -87,7 +93,7 @@ public string FullScript } // Return full snippet - // Developer Note: If you recently updated the snippet and are now getting "FormatException: Input string was not in a correct format." you need to escape all the curly braces; '{' => '{{' and '}' => '}}'. + // Developer Note: If you recently updated the snippet and are now getting "FormatException: Input string was not in a correct format." you need to escape all the curly braces; '{' => '{{' and '}' => '}}'. return string.Format(CultureInfo.InvariantCulture, Snippet, insertConfig, insertAuthUserContext); } else diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLogger.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLogger.cs index 66888efe9b..e6e5d46db9 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLogger.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLogger.cs @@ -3,6 +3,7 @@ using System; using System.Collections; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using Microsoft.ApplicationInsights; @@ -11,9 +12,11 @@ using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.Extensions.Logging; +#pragma warning disable CS0618 // ApplicationInsightsLoggerOptions is obsolete. This will not be fixed because this class is also obsolete. /// /// implementation that forwards log messages as Application Insight trace events. /// + [SuppressMessage("Documentation Rules", "SA1614:ElementParameterDocumentationMustHaveText", Justification = "This class is obsolete and will not be completely documented.")] internal class ApplicationInsightsLogger : ILogger { #if NET451 || NET46 @@ -37,6 +40,10 @@ internal class ApplicationInsightsLogger : ILogger /// /// Initializes a new instance of the class. /// + /// + /// + /// + /// public ApplicationInsightsLogger(string name, TelemetryClient telemetryClient, Func filter, ApplicationInsightsLoggerOptions options) { this.categoryName = name; @@ -134,4 +141,5 @@ private SeverityLevel GetSeverityLevel(LogLevel logLevel) } } } +#pragma warning restore CS0618 } diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLoggerFactoryExtensions.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLoggerFactoryExtensions.cs index d986b75427..128cba4b56 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLoggerFactoryExtensions.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLoggerFactoryExtensions.cs @@ -63,12 +63,18 @@ public static ILoggerFactory AddApplicationInsights( /// Filter action. /// The callback that gets executed when another ApplicationInsights logger is added. [Obsolete("ApplicationInsightsLoggerProvider is now enabled by default when enabling ApplicationInsights monitoring using UseApplicationInsights extension method on IWebHostBuilder or AddApplicationInsightsTelemetry extension method on IServiceCollection. From 2.7.0-beta3 onwards, calling this method will result in double logging and filters applied will not get applied. If interested in using just logging provider, then please use Microsoft.Extensions.Logging.ApplicationInsightsLoggingBuilderExtensions.AddApplicationInsights from Microsoft.Extensions.Logging.ApplicationInsights package. Read more https://aka.ms/ApplicationInsightsILoggerFaq")] + [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Obsolete method.")] public static ILoggerFactory AddApplicationInsights( this ILoggerFactory factory, IServiceProvider serviceProvider, Func filter, Action loggerAddedCallback) { + if (factory == null) + { + throw new ArgumentNullException(nameof(factory)); + } + var client = serviceProvider.GetService(); var debugLoggerControl = serviceProvider.GetService(); var options = serviceProvider.GetService>(); diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLoggerProvider.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLoggerProvider.cs index 777f47eea3..b120773caf 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLoggerProvider.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Logging/Implementation/ApplicationInsightsLoggerProvider.cs @@ -1,9 +1,11 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Logging { using System; + using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +#pragma warning disable CS0618 // ApplicationInsightsLoggerOptions is obsolete. This will not be fixed because this class is also obsolete. /// /// implementation that creates returns instances of . /// @@ -11,6 +13,7 @@ // For NETSTANDARD2.0 We take dependency on Microsoft.Extensions.Logging.ApplicationInsights which has ApplicationInsightsProvider having the same ProviderAlias and don't want to clash with this ProviderAlias. [ProviderAlias("ApplicationInsights")] #endif + [SuppressMessage("Documentation Rules", "SA1614:ElementParameterDocumentationMustHaveText", Justification = "This class is obsolete and will not be completely documented.")] internal class ApplicationInsightsLoggerProvider : ILoggerProvider { private readonly TelemetryClient telemetryClient; @@ -20,6 +23,9 @@ internal class ApplicationInsightsLoggerProvider : ILoggerProvider /// /// Initializes a new instance of the class. /// + /// + /// + /// public ApplicationInsightsLoggerProvider(TelemetryClient telemetryClient, Func filter, IOptions options) { this.telemetryClient = telemetryClient; @@ -38,4 +44,5 @@ public void Dispose() { } } +#pragma warning restore CS0618 } \ No newline at end of file diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Microsoft.ApplicationInsights.AspNetCore.csproj b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Microsoft.ApplicationInsights.AspNetCore.csproj index d45d90c52b..7cf2b5ffec 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Microsoft.ApplicationInsights.AspNetCore.csproj +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/Microsoft.ApplicationInsights.AspNetCore.csproj @@ -34,7 +34,7 @@ 1701;1702 - + All @@ -42,7 +42,7 @@ All - + All @@ -53,6 +53,24 @@ + + + + + false + $(RulesetsRoot)\ApplicationInsightsSDKRules.ruleset + true + + + + + false + $(RulesetsRoot)\ApplicationInsightsSDKRules.ruleset + false + + + + diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/RequestTrackingTelemetryModule.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/RequestTrackingTelemetryModule.cs index a59cebda40..575c1768a5 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/RequestTrackingTelemetryModule.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/RequestTrackingTelemetryModule.cs @@ -19,9 +19,11 @@ namespace Microsoft.ApplicationInsights.AspNetCore /// public class RequestTrackingTelemetryModule : ITelemetryModule, IObserver, IDisposable { + internal bool IsInitialized = false; + // We are only interested in BeforeAction event from Microsoft.AspNetCore.Mvc source. // We are interested in Microsoft.AspNetCore.Hosting and Microsoft.AspNetCore.Diagnostics as well. - // Below filter achieves acceptable performance, character 22 shoudl not be M unless event is BeforeAction. + // Below filter achieves acceptable performance, character 22 should not be M unless event is BeforeAction. private static readonly Predicate HostingPredicate = (string eventName) => (eventName != null) ? !(eventName[21] == 'M') || eventName == "Microsoft.AspNetCore.Mvc.BeforeAction" : false; private readonly object lockObject = new object(); private readonly IApplicationIdProvider applicationIdProvider; @@ -29,7 +31,6 @@ public class RequestTrackingTelemetryModule : ITelemetryModule, IObserver subscriptions; private HostingDiagnosticListener diagnosticListener; - internal bool isInitialized = false; /// /// Initializes a new instance of the class. @@ -63,11 +64,11 @@ public void Initialize(TelemetryConfiguration configuration) { try { - if (!this.isInitialized) + if (!this.IsInitialized) { lock (this.lockObject) { - if (!this.isInitialized) + if (!this.IsInitialized) { this.telemetryClient = new TelemetryClient(configuration); @@ -96,6 +97,7 @@ public void Initialize(TelemetryConfiguration configuration) AspNetCoreEventSource.Instance.LogError($"Exception occured while attempting to find Asp.Net Core Major version. Assuming {aspNetCoreMajorVersion.ToString()} and continuing. Exception: {e.Message}"); } +#pragma warning disable CS0618 // EnableW3CDistributedTracing is obsolete. Ignore because the property inside this constructor is still in use. this.diagnosticListener = new HostingDiagnosticListener( configuration, this.telemetryClient, @@ -104,10 +106,11 @@ public void Initialize(TelemetryConfiguration configuration) this.CollectionOptions.TrackExceptions, this.CollectionOptions.EnableW3CDistributedTracing, aspNetCoreMajorVersion); +#pragma warning restore CS0618 this.subscriptions?.Add(DiagnosticListener.AllListeners.Subscribe(this)); - this.isInitialized = true; + this.IsInitialized = true; } } } @@ -149,6 +152,7 @@ void IObserver.OnCompleted() public void Dispose() { this.Dispose(true); + GC.SuppressFinalize(this); } /// diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/AzureAppServiceRoleNameFromHostNameHeaderInitializer.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/AzureAppServiceRoleNameFromHostNameHeaderInitializer.cs index 246304d598..709c896c12 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/AzureAppServiceRoleNameFromHostNameHeaderInitializer.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/AzureAppServiceRoleNameFromHostNameHeaderInitializer.cs @@ -1,7 +1,7 @@ namespace Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers { using System; - + using System.Diagnostics.CodeAnalysis; using Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.Tracing; using Microsoft.ApplicationInsights.AspNetCore.Implementation; using Microsoft.ApplicationInsights.Channel; @@ -45,6 +45,7 @@ public AzureAppServiceRoleNameFromHostNameHeaderInitializer(string webAppSuffix /// For US Gov Cloud: ".azurewebsites.us" /// For Azure Germany: ".azurewebsites.de". /// + [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "We want this to be an instance variable for configuration.")] public string WebAppSuffix { get => RoleNameContainer.Instance.HostNameSuffix; @@ -64,6 +65,11 @@ public string WebAppSuffix /// The telemetry item for which RoleName is to be set. public void Initialize(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + try { if (!RoleNameContainer.Instance.IsAzureWebApp) diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/ClientIpHeaderTelemetryInitializer.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/ClientIpHeaderTelemetryInitializer.cs index cc278f324c..de0f5c32f5 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/ClientIpHeaderTelemetryInitializer.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/ClientIpHeaderTelemetryInitializer.cs @@ -65,6 +65,16 @@ public string HeaderValueSeparators /// protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + if (!string.IsNullOrEmpty(telemetry.Context.Location.Ip)) { // Ip is already populated. @@ -76,6 +86,11 @@ protected override void OnInitializeTelemetry(HttpContext platformContext, Reque { string resultIp = null; + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + if (platformContext.Request?.Headers != null) { foreach (var name in this.HeaderNames) diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/OperationNameTelemetryInitializer.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/OperationNameTelemetryInitializer.cs index 10bce21dbb..d2389b45fc 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/OperationNameTelemetryInitializer.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/OperationNameTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers { + using System; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.AspNetCore.Http; @@ -21,14 +22,29 @@ public OperationNameTelemetryInitializer(IHttpContextAccessor httpContextAccesso /// protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (string.IsNullOrEmpty(telemetry.Context.Operation.Name)) { + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + if (!string.IsNullOrEmpty(requestTelemetry.Name)) { telemetry.Context.Operation.Name = requestTelemetry.Name; } else { + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + // We didn't get BeforeAction notification string name = platformContext.Request.Method + " " + platformContext.Request.Path.Value; telemetry.Context.Operation.Name = name; diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/SyntheticTelemetryInitializer.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/SyntheticTelemetryInitializer.cs index 334d7ac2df..019ff88eaa 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/SyntheticTelemetryInitializer.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/SyntheticTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers { + using System; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.AspNetCore.Http; @@ -26,8 +27,18 @@ public SyntheticTelemetryInitializer(IHttpContextAccessor httpContextAccessor) /// protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (string.IsNullOrEmpty(telemetry.Context.Operation.SyntheticSource)) { + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + var runIdHeader = platformContext.Request?.Headers[SyntheticTestRunId]; var locationHeader = platformContext.Request?.Headers[SyntheticTestLocation]; diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/WebSessionTelemetryInitializer.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/WebSessionTelemetryInitializer.cs index 4dd6f18a07..a00f4a0d43 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/WebSessionTelemetryInitializer.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/WebSessionTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers { + using System; using Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.Tracing; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; @@ -24,14 +25,29 @@ public WebSessionTelemetryInitializer(IHttpContextAccessor httpContextAccessor) /// protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (!string.IsNullOrEmpty(telemetry.Context.Session.Id)) { AspNetCoreEventSource.Instance.LogWebSessionTelemetryInitializerOnInitializeTelemetrySessionIdNull(); return; } + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + if (string.IsNullOrEmpty(requestTelemetry.Context.Session.Id)) { + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + UpdateRequestTelemetryFromPlatformContext(requestTelemetry, platformContext); } diff --git a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/WebUserTelemetryInitializer.cs b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/WebUserTelemetryInitializer.cs index 796bf9235b..e9244849c8 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/WebUserTelemetryInitializer.cs +++ b/NETCORE/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/WebUserTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers { + using System; using Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.Tracing; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; @@ -24,14 +25,29 @@ public WebUserTelemetryInitializer(IHttpContextAccessor httpContextAccessor) /// protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (!string.IsNullOrEmpty(telemetry.Context.User.Id)) { AspNetCoreEventSource.Instance.LogWebUserTelemetryInitializerOnInitializeTelemetrySessionIdNull(); return; } + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + if (string.IsNullOrEmpty(requestTelemetry.Context.User.Id)) { + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + UpdateRequestTelemetryFromPlatformContext(requestTelemetry, platformContext); } diff --git a/NETCORE/src/Microsoft.ApplicationInsights.WorkerService/Microsoft.ApplicationInsights.WorkerService.csproj b/NETCORE/src/Microsoft.ApplicationInsights.WorkerService/Microsoft.ApplicationInsights.WorkerService.csproj index 18863abbbd..7f169d4929 100644 --- a/NETCORE/src/Microsoft.ApplicationInsights.WorkerService/Microsoft.ApplicationInsights.WorkerService.csproj +++ b/NETCORE/src/Microsoft.ApplicationInsights.WorkerService/Microsoft.ApplicationInsights.WorkerService.csproj @@ -29,7 +29,8 @@ true - + + All @@ -37,7 +38,7 @@ All - + All @@ -48,6 +49,25 @@ + + + + + false + $(RulesetsRoot)\ApplicationInsightsSDKRules.ruleset + true + + + + + false + $(RulesetsRoot)\ApplicationInsightsSDKRules.ruleset + false + + + + + diff --git a/NETCORE/src/Shared/Extensions/ApplicationInsightsExtensions.cs b/NETCORE/src/Shared/Extensions/ApplicationInsightsExtensions.cs index 64a006870c..7fb1d83811 100644 --- a/NETCORE/src/Shared/Extensions/ApplicationInsightsExtensions.cs +++ b/NETCORE/src/Shared/Extensions/ApplicationInsightsExtensions.cs @@ -167,6 +167,11 @@ public static IConfigurationBuilder AddApplicationInsightsSettings( string instrumentationKey = null, string connectionString = null) { + if (configurationSourceRoot == null) + { + throw new ArgumentNullException(nameof(configurationSourceRoot)); + } + var telemetryConfigValues = new List>(); bool wasAnythingSet = false; @@ -221,7 +226,7 @@ public static IConfigurationBuilder AddApplicationInsightsSettings( /// } /// }. /// - /// Or + /// Or. /// /// "ApplicationInsights": { /// "ConnectionString" : "InstrumentationKey=11111111-2222-3333-4444-555555555555;IngestionEndpoint=http://dc.services.visualstudio.com" @@ -302,7 +307,7 @@ private static void AddCommonInitializers(IServiceCollection services) services.AddSingleton(); #else services.AddSingleton(); -#endif +#endif services.AddSingleton(); services.AddSingleton(); } diff --git a/NETCORE/src/Shared/Implementation/ITelemetryModuleConfigurator.cs b/NETCORE/src/Shared/Implementation/ITelemetryModuleConfigurator.cs index 7fed84327a..d35a673cb9 100644 --- a/NETCORE/src/Shared/Implementation/ITelemetryModuleConfigurator.cs +++ b/NETCORE/src/Shared/Implementation/ITelemetryModuleConfigurator.cs @@ -29,6 +29,7 @@ public interface ITelemetryModuleConfigurator /// [Obsolete("Use Configure(ITelemetryModule telemetryModule, ApplicationInsightsServiceOptions options) instead.")] [SuppressMessage("Documentation Rules", "SA1600:ElementsMustBeDocumented", Justification = "This method is obsolete.")] + [SuppressMessage("Documentation Rules", "SA1611:ElementParametersMustBeDocumented", Justification = "This method is obsolete.")] void Configure(ITelemetryModule telemetryModule); /// diff --git a/NETCORE/src/Shared/Implementation/NoOpTelemetryModule.cs b/NETCORE/src/Shared/Implementation/NoOpTelemetryModule.cs index 5b6bb45cbd..bee0a3c8b7 100644 --- a/NETCORE/src/Shared/Implementation/NoOpTelemetryModule.cs +++ b/NETCORE/src/Shared/Implementation/NoOpTelemetryModule.cs @@ -1,10 +1,12 @@ namespace Shared.Implementation { + using System.Diagnostics.CodeAnalysis; using Microsoft.ApplicationInsights.Extensibility; /// /// No-op telemetry module that is added instead of actual one, when the actual module is disabled. /// + [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "This class is instantiated by Dependency Injection.")] internal class NoOpTelemetryModule : ITelemetryModule { /// diff --git a/NETCORE/src/Shared/Implementation/TelemetryConfigurationOptionsSetup.cs b/NETCORE/src/Shared/Implementation/TelemetryConfigurationOptionsSetup.cs index 605f7f12f6..7f41919758 100644 --- a/NETCORE/src/Shared/Implementation/TelemetryConfigurationOptionsSetup.cs +++ b/NETCORE/src/Shared/Implementation/TelemetryConfigurationOptionsSetup.cs @@ -46,6 +46,12 @@ internal class TelemetryConfigurationOptionsSetup : IConfigureOptions /// Initializes a new instance of the class. /// + /// Instance of IServiceProvider. + /// Instance of IOptions<ApplicationInsightsServiceOptions>. + /// Instance of IEnumerable<ITelemetryInitializer>. + /// Instance of IEnumerable<ITelemetryModule>. + /// Instance of IEnumerable<ITelemetryProcessorFactory>. + /// Instance of IEnumerable<ITelemetryModuleConfigurator>. public TelemetryConfigurationOptionsSetup( IServiceProvider serviceProvider, IOptions applicationInsightsServiceOptions, @@ -216,6 +222,7 @@ public void Configure(TelemetryConfiguration configuration) continue; } } + module.Initialize(configuration); } diff --git a/NETCORE/src/Shared/TelemetryInitializers/ComponentVersionTelemetryInitializer.cs b/NETCORE/src/Shared/TelemetryInitializers/ComponentVersionTelemetryInitializer.cs index e7d51151ec..a8acab62f8 100644 --- a/NETCORE/src/Shared/TelemetryInitializers/ComponentVersionTelemetryInitializer.cs +++ b/NETCORE/src/Shared/TelemetryInitializers/ComponentVersionTelemetryInitializer.cs @@ -4,6 +4,7 @@ namespace Microsoft.ApplicationInsights.AspNetCore.TelemetryInitializers namespace Microsoft.ApplicationInsights.WorkerService.TelemetryInitializers #endif { + using System; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; #if AI_ASPNETCORE_WEB @@ -26,12 +27,22 @@ public class ComponentVersionTelemetryInitializer : ITelemetryInitializer /// Provides the Application Version to be added to the telemetry. public ComponentVersionTelemetryInitializer(IOptions options) { - this.version = options.Value.ApplicationVersion; + if (options == null) + { + throw new ArgumentNullException(nameof(options)); + } + + this.version = options.Value.ApplicationVersion; } /// public void Initialize(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (string.IsNullOrEmpty(telemetry.Context.Component.Version)) { if (!string.IsNullOrEmpty(this.version)) diff --git a/NETCORE/src/Shared/TelemetryInitializers/DomainNameRoleInstanceTelemetryInitializer.cs b/NETCORE/src/Shared/TelemetryInitializers/DomainNameRoleInstanceTelemetryInitializer.cs index d462817590..de13c505df 100644 --- a/NETCORE/src/Shared/TelemetryInitializers/DomainNameRoleInstanceTelemetryInitializer.cs +++ b/NETCORE/src/Shared/TelemetryInitializers/DomainNameRoleInstanceTelemetryInitializer.cs @@ -26,6 +26,11 @@ public class DomainNameRoleInstanceTelemetryInitializer : ITelemetryInitializer /// Telemetry item. public void Initialize(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleInstance)) { var name = LazyInitializer.EnsureInitialized(ref this.roleInstanceName, this.GetMachineName); diff --git a/NETCORE/test/Microsoft.ApplicationInsights.AspNetCore.Tests/Extensions/ApplicationInsightsExtensionsTests.cs b/NETCORE/test/Microsoft.ApplicationInsights.AspNetCore.Tests/Extensions/ApplicationInsightsExtensionsTests.cs index e4f1255d82..3332d28403 100644 --- a/NETCORE/test/Microsoft.ApplicationInsights.AspNetCore.Tests/Extensions/ApplicationInsightsExtensionsTests.cs +++ b/NETCORE/test/Microsoft.ApplicationInsights.AspNetCore.Tests/Extensions/ApplicationInsightsExtensionsTests.cs @@ -36,8 +36,9 @@ namespace Microsoft.Extensions.DependencyInjection.Test using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.Options; + using Microsoft.Extensions.Options; +#pragma warning disable CS0618 // TelemetryConfiguration.Active is obsolete. We still test with this for backwards compatibility. public static class ApplicationInsightsExtensionsTests { /// Constant instrumentation key value for testintg. @@ -710,7 +711,7 @@ public static void UserCanDisableRequestCounterCollectorModule() var req = modules.OfType().First(); // But the module will not be initialized. - Assert.False(req.isInitialized); + Assert.False(req.IsInitialized); } [Fact] @@ -1506,4 +1507,5 @@ public void AddProvider(ILoggerProvider provider) } } } +#pragma warning restore CS0618 // TelemetryConfiguration.Active is obsolete. We still test with this for backwards compatibility. } \ No newline at end of file diff --git a/NETCORE/test/Microsoft.ApplicationInsights.AspNetCore.Tests/Logging/ApplicationInsightsLoggerTests.cs b/NETCORE/test/Microsoft.ApplicationInsights.AspNetCore.Tests/Logging/ApplicationInsightsLoggerTests.cs index b7b2edd4d4..e02fb89d0a 100644 --- a/NETCORE/test/Microsoft.ApplicationInsights.AspNetCore.Tests/Logging/ApplicationInsightsLoggerTests.cs +++ b/NETCORE/test/Microsoft.ApplicationInsights.AspNetCore.Tests/Logging/ApplicationInsightsLoggerTests.cs @@ -8,6 +8,7 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Tests.Logging { +#pragma warning disable CS0618 // ApplicationInsightsLoggerOptions is obsolete. Are we ready to delete these tests? /// /// Tests for the Application Insights ILogger implementation. /// @@ -464,4 +465,5 @@ public void TestUninitializedLoggerDoesNotThrowExceptions() logger.LogTrace("This won't do anything.", new object[] { }); } } +#pragma warning restore CS0618 // ApplicationInsightsLoggerOptions is obsolete. Are we ready to delete these tests? } diff --git a/WEB/Src/Common/ConditionalWeakTableExtensions.cs b/WEB/Src/Common/ConditionalWeakTableExtensions.cs index 73853d7846..be6fc86ca2 100644 --- a/WEB/Src/Common/ConditionalWeakTableExtensions.cs +++ b/WEB/Src/Common/ConditionalWeakTableExtensions.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Common { + using System; using System.Runtime.CompilerServices; /// @@ -12,6 +13,11 @@ public static class ConditionalWeakTableExtensions /// public static void AddIfNotExists(this ConditionalWeakTable conditionalWeakTable, TKey key, TValue value) where TKey : class where TValue : class { + if (conditionalWeakTable == null) + { + throw new ArgumentNullException(nameof(conditionalWeakTable)); + } + if (!conditionalWeakTable.TryGetValue(key, out TValue testValue)) { conditionalWeakTable.Add(key, value); diff --git a/WEB/Src/DependencyCollector/DependencyCollector/DependencyCollector.csproj b/WEB/Src/DependencyCollector/DependencyCollector/DependencyCollector.csproj index 0475e9cd79..9f6b9a9233 100644 --- a/WEB/Src/DependencyCollector/DependencyCollector/DependencyCollector.csproj +++ b/WEB/Src/DependencyCollector/DependencyCollector/DependencyCollector.csproj @@ -23,7 +23,7 @@ Azure Monitoring Analytics ApplicationInsights Telemetry AppInsights - + All @@ -31,11 +31,27 @@ All - - All + + All + + + + + false + true + + + + + false + false + + + + diff --git a/WEB/Src/EventCounterCollector/EventCounterCollector/EventCounterCollector.csproj b/WEB/Src/EventCounterCollector/EventCounterCollector/EventCounterCollector.csproj index 92ac61be45..f0d103b32a 100644 --- a/WEB/Src/EventCounterCollector/EventCounterCollector/EventCounterCollector.csproj +++ b/WEB/Src/EventCounterCollector/EventCounterCollector/EventCounterCollector.csproj @@ -16,7 +16,7 @@ Azure Monitoring Analytics ApplicationInsights Telemetry ASP.NET aspnetcore Web Azure Server Services ASPX Websites Event Counters Performance Collection - + All @@ -24,11 +24,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/WEB/Src/HostingStartup/HostingStartup/HostingStartup.csproj b/WEB/Src/HostingStartup/HostingStartup/HostingStartup.csproj index e04f5c59d0..39fce1a5d3 100644 --- a/WEB/Src/HostingStartup/HostingStartup/HostingStartup.csproj +++ b/WEB/Src/HostingStartup/HostingStartup/HostingStartup.csproj @@ -18,7 +18,7 @@ Azure Monitoring Analytics ApplicationInsights Telemetry AppInsights - + All @@ -26,11 +26,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/WEB/Src/HostingStartup/HostingStartup/Implementation/TraceSourceForEventSource.cs b/WEB/Src/HostingStartup/HostingStartup/Implementation/TraceSourceForEventSource.cs index 7aad65c104..288788e1c4 100644 --- a/WEB/Src/HostingStartup/HostingStartup/Implementation/TraceSourceForEventSource.cs +++ b/WEB/Src/HostingStartup/HostingStartup/Implementation/TraceSourceForEventSource.cs @@ -106,6 +106,11 @@ protected virtual void Dispose(bool disposeManaged = true) /// Event to trace. protected void TraceEvent(EventWrittenEventArgs eventData) { + if (eventData == null) + { + throw new ArgumentNullException(nameof(eventData)); + } + try { if (eventData.Payload != null) diff --git a/WEB/Src/PerformanceCollector/Perf.Shared.NetStandard/Implementation/QuickPulse/QuickPulseServiceClient.cs b/WEB/Src/PerformanceCollector/Perf.Shared.NetStandard/Implementation/QuickPulse/QuickPulseServiceClient.cs index 9c25f1714a..ba0d7ac2b6 100644 --- a/WEB/Src/PerformanceCollector/Perf.Shared.NetStandard/Implementation/QuickPulse/QuickPulseServiceClient.cs +++ b/WEB/Src/PerformanceCollector/Perf.Shared.NetStandard/Implementation/QuickPulse/QuickPulseServiceClient.cs @@ -138,24 +138,29 @@ public void Dispose() { try { - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri); - this.AddHeaders(request, includeIdentityHeaders, configurationETag, authApiKey); - - using (MemoryStream stream = new MemoryStream()) + using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri)) { - onWriteRequestBody(stream); - stream.Flush(); - ArraySegment buffer = stream.TryGetBuffer(out buffer) ? buffer : new ArraySegment(); - request.Content = new ByteArrayContent(buffer.Array, buffer.Offset, buffer.Count); + this.AddHeaders(request, includeIdentityHeaders, configurationETag, authApiKey); - HttpResponseMessage response = this.httpClient.SendAsync(request, new CancellationTokenSource(this.timeout).Token).GetAwaiter().GetResult(); - if (response == null) + using (MemoryStream stream = new MemoryStream()) { - configurationInfo = null; - return null; + onWriteRequestBody(stream); + stream.Flush(); + ArraySegment buffer = stream.TryGetBuffer(out buffer) ? buffer : new ArraySegment(); + request.Content = new ByteArrayContent(buffer.Array, buffer.Offset, buffer.Count); + + using (var cancellationToken = new CancellationTokenSource(this.timeout)) + { + HttpResponseMessage response = this.httpClient.SendAsync(request, cancellationToken.Token).GetAwaiter().GetResult(); + if (response == null) + { + configurationInfo = null; + return null; + } + + return this.ProcessResponse(response, configurationETag, out configurationInfo); + } } - - return this.ProcessResponse(response, configurationETag, out configurationInfo); } } catch (Exception e) diff --git a/WEB/Src/PerformanceCollector/Perf.Shared/QuickPulseTelemetryModule.cs b/WEB/Src/PerformanceCollector/Perf.Shared/QuickPulseTelemetryModule.cs index 65c24bedc5..9a3d3523f0 100644 --- a/WEB/Src/PerformanceCollector/Perf.Shared/QuickPulseTelemetryModule.cs +++ b/WEB/Src/PerformanceCollector/Perf.Shared/QuickPulseTelemetryModule.cs @@ -52,8 +52,10 @@ public sealed class QuickPulseTelemetryModule : ITelemetryModule, IDisposable private TelemetryConfiguration config; + [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", Justification = "This object self-disposes with this class's Dispose method.")] private IQuickPulseModuleSchedulerHandle collectionThread; + [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", Justification = "This object self-disposes with this class's Dispose method.")] private IQuickPulseModuleSchedulerHandle stateThread; private Clock timeProvider; diff --git a/WEB/Src/PerformanceCollector/PerformanceCollector/Perf.csproj b/WEB/Src/PerformanceCollector/PerformanceCollector/Perf.csproj index db3f0b796f..b8c2e94775 100644 --- a/WEB/Src/PerformanceCollector/PerformanceCollector/Perf.csproj +++ b/WEB/Src/PerformanceCollector/PerformanceCollector/Perf.csproj @@ -17,7 +17,7 @@ Azure Monitoring Analytics ApplicationInsights Telemetry ASP.NET ASMX Web Azure Server Services ASPX Websites Performance Counters Performance Collection - + All @@ -25,11 +25,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/WEB/Src/Web/Web.Shared.Net/AccountIdTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/AccountIdTelemetryInitializer.cs index 03a1552775..b664e4c571 100644 --- a/WEB/Src/Web/Web.Shared.Net/AccountIdTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/AccountIdTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Web { + using System; using System.Web; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; @@ -43,11 +44,23 @@ internal static void GetAuthUserContextFromUserCookie(HttpCookie authUserCookie, /// Http context. /// Request telemetry object associated with the current request. /// Telemetry item to initialize. - protected override void OnInitializeTelemetry( - HttpContext platformContext, - RequestTelemetry requestTelemetry, - ITelemetry telemetry) + protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + if (string.IsNullOrEmpty(telemetry.Context.User.AccountId)) { if (string.IsNullOrEmpty(requestTelemetry.Context.User.AccountId)) diff --git a/WEB/Src/Web/Web.Shared.Net/AuthenticatedUserIdTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/AuthenticatedUserIdTelemetryInitializer.cs index 2aa48da215..c4e3c2a70b 100644 --- a/WEB/Src/Web/Web.Shared.Net/AuthenticatedUserIdTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/AuthenticatedUserIdTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Web { + using System; using System.Web; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; @@ -43,11 +44,23 @@ internal static void GetAuthUserContextFromUserCookie(HttpCookie authUserCookie, /// Http context. /// Request telemetry object associated with the current request. /// Telemetry item to initialize. - protected override void OnInitializeTelemetry( - HttpContext platformContext, - RequestTelemetry requestTelemetry, - ITelemetry telemetry) + protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + if (string.IsNullOrEmpty(telemetry.Context.User.AuthenticatedUserId)) { if (string.IsNullOrEmpty(requestTelemetry.Context.User.AuthenticatedUserId)) diff --git a/WEB/Src/Web/Web.Shared.Net/AzureAppServiceRoleNameFromHostNameHeaderInitializer.cs b/WEB/Src/Web/Web.Shared.Net/AzureAppServiceRoleNameFromHostNameHeaderInitializer.cs index 7e41ff9342..cef0bfd96f 100644 --- a/WEB/Src/Web/Web.Shared.Net/AzureAppServiceRoleNameFromHostNameHeaderInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/AzureAppServiceRoleNameFromHostNameHeaderInitializer.cs @@ -41,7 +41,7 @@ public AzureAppServiceRoleNameFromHostNameHeaderInitializer() : this(".azurewebs /// WebApp name suffix. public AzureAppServiceRoleNameFromHostNameHeaderInitializer(string webAppSuffix) { - this.WebAppSuffix = webAppSuffix; + this.WebAppSuffix = webAppSuffix ?? throw new ArgumentNullException(nameof(webAppSuffix)); try { var result = Environment.GetEnvironmentVariable(WebAppHostNameEnvironmentVariable); @@ -80,6 +80,11 @@ public AzureAppServiceRoleNameFromHostNameHeaderInitializer(string webAppSuffix) /// The telemetry item for which RoleName is to be set. public void Initialize(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + try { if (!this.isAzureWebApp) diff --git a/WEB/Src/Web/Web.Shared.Net/ClientIpHeaderTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/ClientIpHeaderTelemetryInitializer.cs index f7031f5ff1..af39d10d96 100644 --- a/WEB/Src/Web/Web.Shared.Net/ClientIpHeaderTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/ClientIpHeaderTelemetryInitializer.cs @@ -75,6 +75,21 @@ public string HeaderValueSeparators /// Telemetry item to initialize. protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + if (string.IsNullOrEmpty(telemetry.Context.Location.Ip)) { var location = requestTelemetry.Context.Location; diff --git a/WEB/Src/Web/Web.Shared.Net/OperationCorrelationTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/OperationCorrelationTelemetryInitializer.cs index 591c76deb0..e658622a4b 100644 --- a/WEB/Src/Web/Web.Shared.Net/OperationCorrelationTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/OperationCorrelationTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Web { + using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Web; @@ -63,11 +64,23 @@ public string RootOperationIdHeaderName /// Http context. /// Request telemetry object associated with the current request. /// Telemetry item to initialize. - protected override void OnInitializeTelemetry( - HttpContext platformContext, - RequestTelemetry requestTelemetry, - ITelemetry telemetry) + protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + // Telemetry is initialized by Base SDK OperationCorrelationTelemetryInitializer from the call context /Current Activity // However we still may lose CorrelationContext/AsyncLocal due to IIS managed/native thread hops. // We protect from it with PreRequestHandlerExecute event, that happens right before the handler diff --git a/WEB/Src/Web/Web.Shared.Net/OperationNameTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/OperationNameTelemetryInitializer.cs index 3f28e574b2..016a0287b0 100644 --- a/WEB/Src/Web/Web.Shared.Net/OperationNameTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/OperationNameTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Web { + using System; using System.Web; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; @@ -18,14 +19,26 @@ public class OperationNameTelemetryInitializer : WebTelemetryInitializerBase /// Http context. /// Request telemetry object associated with the current request. /// Telemetry item to initialize. - protected override void OnInitializeTelemetry( - HttpContext platformContext, - RequestTelemetry rootRequestTelemetry, - ITelemetry telemetry) + protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry rootRequestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (rootRequestTelemetry == null) + { + throw new ArgumentNullException(nameof(rootRequestTelemetry)); + } + + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + if (string.IsNullOrEmpty(telemetry.Context.Operation.Name)) { - // Do not cache name because it may be too early to calculate it (e.g. traces on applicatio start). + // Do not cache name because it may be too early to calculate it (e.g. traces on application start). // When it is too early to calculate it only that telemetry will have incorrect operation name string name = string.IsNullOrEmpty(rootRequestTelemetry.Name) ? platformContext.CreateRequestNamePrivate() : diff --git a/WEB/Src/Web/Web.Shared.Net/RequestTrackingTelemetryModule.cs b/WEB/Src/Web/Web.Shared.Net/RequestTrackingTelemetryModule.cs index 5ecdeb9eca..6ff52f0b02 100644 --- a/WEB/Src/Web/Web.Shared.Net/RequestTrackingTelemetryModule.cs +++ b/WEB/Src/Web/Web.Shared.Net/RequestTrackingTelemetryModule.cs @@ -246,7 +246,7 @@ public void AddTargetHashForResponseHeader(HttpContext context) /// Telemetry configuration to use for initialization. public void Initialize(TelemetryConfiguration configuration) { - this.telemetryConfiguration = configuration; + this.telemetryConfiguration = configuration ?? throw new ArgumentNullException(nameof(configuration)); this.telemetryClient = new TelemetryClient(configuration); this.telemetryClient.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("web:"); diff --git a/WEB/Src/Web/Web.Shared.Net/SessionTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/SessionTelemetryInitializer.cs index dd046ad2f7..9b8f8e0f40 100644 --- a/WEB/Src/Web/Web.Shared.Net/SessionTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/SessionTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Web { + using System; using System.Web; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; @@ -44,11 +45,23 @@ internal static void GetSessionContextFromUserCookie(HttpCookie sessionCookie, R /// Http context. /// Request telemetry object associated with the current request. /// Telemetry item to initialize. - protected override void OnInitializeTelemetry( - HttpContext platformContext, - RequestTelemetry requestTelemetry, - ITelemetry telemetry) + protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + if (string.IsNullOrEmpty(telemetry.Context.Session.Id)) { if (string.IsNullOrEmpty(requestTelemetry.Context.Session.Id)) diff --git a/WEB/Src/Web/Web.Shared.Net/SyntheticUserAgentTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/SyntheticUserAgentTelemetryInitializer.cs index 51e148dacf..ad70e74a78 100644 --- a/WEB/Src/Web/Web.Shared.Net/SyntheticUserAgentTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/SyntheticUserAgentTelemetryInitializer.cs @@ -48,6 +48,11 @@ public string Filters /// Telemetry item to initialize. protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (string.IsNullOrEmpty(telemetry.Context.Operation.SyntheticSource)) { if (platformContext != null) diff --git a/WEB/Src/Web/Web.Shared.Net/UserTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/UserTelemetryInitializer.cs index b628fa0929..793c3bbf99 100644 --- a/WEB/Src/Web/Web.Shared.Net/UserTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/UserTelemetryInitializer.cs @@ -45,11 +45,23 @@ internal static void GetUserContextFromUserCookie(HttpCookie userCookie, Request /// Http context. /// Request telemetry object associated with the current request. /// Telemetry item to initialize. - protected override void OnInitializeTelemetry( - HttpContext platformContext, - RequestTelemetry requestTelemetry, - ITelemetry telemetry) + protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (requestTelemetry == null) + { + throw new ArgumentNullException(nameof(requestTelemetry)); + } + + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + if (string.IsNullOrEmpty(telemetry.Context.User.Id)) { if (string.IsNullOrEmpty(requestTelemetry.Context.User.Id)) diff --git a/WEB/Src/Web/Web.Shared.Net/WebTestTelemetryInitializer.cs b/WEB/Src/Web/Web.Shared.Net/WebTestTelemetryInitializer.cs index cafa2e5780..fca743c783 100644 --- a/WEB/Src/Web/Web.Shared.Net/WebTestTelemetryInitializer.cs +++ b/WEB/Src/Web/Web.Shared.Net/WebTestTelemetryInitializer.cs @@ -1,5 +1,6 @@ namespace Microsoft.ApplicationInsights.Web { + using System; using System.Web; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; @@ -20,11 +21,18 @@ public class WebTestTelemetryInitializer : WebTelemetryInitializerBase /// Http context. /// Request telemetry object associated with the current request. /// Telemetry item to initialize. - protected override void OnInitializeTelemetry( - HttpContext platformContext, - RequestTelemetry requestTelemetry, - ITelemetry telemetry) + protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + + if (platformContext == null) + { + throw new ArgumentNullException(nameof(platformContext)); + } + if (string.IsNullOrEmpty(telemetry.Context.Operation.SyntheticSource)) { // platformContext and request != null checks are in the base class diff --git a/WEB/Src/Web/Web/AspNetDiagnosticTelemetryModule.cs b/WEB/Src/Web/Web/AspNetDiagnosticTelemetryModule.cs index 442300afde..8678eed6b9 100644 --- a/WEB/Src/Web/Web/AspNetDiagnosticTelemetryModule.cs +++ b/WEB/Src/Web/Web/AspNetDiagnosticTelemetryModule.cs @@ -66,6 +66,11 @@ public void Initialize(TelemetryConfiguration configuration) /// DiagnosticListener value. public void OnNext(DiagnosticListener value) { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + if (this.isEnabled && value.Name == AspNetListenerName) { var eventListener = new AspNetEventObserver(this.requestModule, this.exceptionModule); diff --git a/WEB/Src/Web/Web/Web.csproj b/WEB/Src/Web/Web/Web.csproj index b0d2f2a491..85f7ea2c6f 100644 --- a/WEB/Src/Web/Web/Web.csproj +++ b/WEB/Src/Web/Web/Web.csproj @@ -18,7 +18,7 @@ Azure Monitoring Analytics ApplicationInsights Telemetry AppInsights - + All @@ -26,11 +26,27 @@ All - + All + + + + + false + true + + + + + false + false + + + + diff --git a/WEB/Src/WindowsServer/WindowsServer.Shared/AzureRoleEnvironmentTelemetryInitializer.cs b/WEB/Src/WindowsServer/WindowsServer.Shared/AzureRoleEnvironmentTelemetryInitializer.cs index 401cbe7a32..6d603be4c9 100644 --- a/WEB/Src/WindowsServer/WindowsServer.Shared/AzureRoleEnvironmentTelemetryInitializer.cs +++ b/WEB/Src/WindowsServer/WindowsServer.Shared/AzureRoleEnvironmentTelemetryInitializer.cs @@ -47,6 +47,11 @@ public AzureRoleEnvironmentTelemetryInitializer() /// The telemetry to initialize. public void Initialize(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName)) { telemetry.Context.Cloud.RoleName = this.roleName; diff --git a/WEB/Src/WindowsServer/WindowsServer.Shared/AzureWebAppRoleEnvironmentTelemetryInitializer.cs b/WEB/Src/WindowsServer/WindowsServer.Shared/AzureWebAppRoleEnvironmentTelemetryInitializer.cs index 65205e4a27..5b45cb9bd6 100644 --- a/WEB/Src/WindowsServer/WindowsServer.Shared/AzureWebAppRoleEnvironmentTelemetryInitializer.cs +++ b/WEB/Src/WindowsServer/WindowsServer.Shared/AzureWebAppRoleEnvironmentTelemetryInitializer.cs @@ -40,6 +40,11 @@ public AzureWebAppRoleEnvironmentTelemetryInitializer() /// The telemetry to initialize. public void Initialize(ITelemetry telemetry) { + if (telemetry == null) + { + throw new ArgumentNullException(nameof(telemetry)); + } + if (this.updateEnvVars) { this.roleName = this.GetRoleName(); diff --git a/WEB/Src/WindowsServer/WindowsServer.Shared/DeveloperModeWithDebuggerAttachedTelemetryModule.cs b/WEB/Src/WindowsServer/WindowsServer.Shared/DeveloperModeWithDebuggerAttachedTelemetryModule.cs index f0da53dc1b..7e73c938ef 100644 --- a/WEB/Src/WindowsServer/WindowsServer.Shared/DeveloperModeWithDebuggerAttachedTelemetryModule.cs +++ b/WEB/Src/WindowsServer/WindowsServer.Shared/DeveloperModeWithDebuggerAttachedTelemetryModule.cs @@ -20,6 +20,11 @@ public class DeveloperModeWithDebuggerAttachedTelemetryModule : ITelemetryModule /// Configuration object. public void Initialize(TelemetryConfiguration configuration) { + if (configuration == null) + { + throw new ArgumentNullException(nameof(configuration)); + } + if (!configuration.TelemetryChannel.DeveloperMode.HasValue && IsDebuggerAttached()) { // Note that when debugger is not attached we are preserving default null value diff --git a/WEB/Src/WindowsServer/WindowsServer.Shared/UnhandledExceptionTelemetryModule.cs b/WEB/Src/WindowsServer/WindowsServer.Shared/UnhandledExceptionTelemetryModule.cs index b7b9a03204..0cff039af1 100644 --- a/WEB/Src/WindowsServer/WindowsServer.Shared/UnhandledExceptionTelemetryModule.cs +++ b/WEB/Src/WindowsServer/WindowsServer.Shared/UnhandledExceptionTelemetryModule.cs @@ -1,6 +1,7 @@ namespace Microsoft.ApplicationInsights.WindowsServer { using System; + using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Common; @@ -68,6 +69,7 @@ private static void CopyConfiguration(TelemetryConfiguration source, TelemetryCo } } + [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "TelemetryConfiguration is needed for the life of the application.")] private TelemetryClient GetTelemetryClient(TelemetryConfiguration sourceConfiguration) { this.channel.EndpointAddress = sourceConfiguration.TelemetryChannel.EndpointAddress; diff --git a/WEB/Src/WindowsServer/WindowsServer/WindowsServer.csproj b/WEB/Src/WindowsServer/WindowsServer/WindowsServer.csproj index ed8c54dc6a..c5750c917b 100644 --- a/WEB/Src/WindowsServer/WindowsServer/WindowsServer.csproj +++ b/WEB/Src/WindowsServer/WindowsServer/WindowsServer.csproj @@ -20,8 +20,8 @@ $(DefineConstants);NETSTANDARD; - - + + All @@ -29,11 +29,27 @@ All - + All + + + + + false + true + + + + + false + false + + + +