1
0
Форкнуть 0

Revert "Make W3C Correlation default and leverage native W3C support from new System.Diagnostics.DiagnosticSource Activity (#958)"

This reverts commit b0ae600680.
This commit is contained in:
Cijo Thomas 2019-08-27 11:05:07 -07:00 коммит произвёл GitHub
Родитель b0ae600680
Коммит 914f3310df
39 изменённых файлов: 1342 добавлений и 1541 удалений

Просмотреть файл

@ -21,20 +21,25 @@ steps:
arguments: "--configuration Release"
- task: DotNetCoreCLI@1
displayName: Functional Tests 2.0
displayName: Test 2.0
continueOnError: true
inputs:
command: "test"
projects: "test/**/*Tests20.csproj"
arguments: "--configuration Release -l trx"
- task: DotNetCoreInstaller@0
displayName: install dotnet core 1.1.5
inputs:
version: "1.1.5"
- task: DotNetCoreCLI@1
displayName: Unit Tests
displayName: Test 1.1.5
continueOnError: true
inputs:
command: "test"
projects: "test/**/*AspNetCore.Tests.csproj"
arguments: "--configuration Release -l trx"
projects: "test/**/*Tests.csproj"
arguments: "--configuration Release -l trx --filter Category!=WindowsOnly"
- task: PublishTestResults@2
@ -42,6 +47,11 @@ steps:
testRunner: "VSTest"
testResultsFiles: "**/*.trx"
- task: DotNetCoreInstaller@0
displayName: install dotnet core 2.1.500
inputs:
version: "2.1.500"
- task: DotNetCoreCLI@1
displayName: Package Nuget
inputs:
@ -53,4 +63,4 @@ steps:
inputs:
PathtoPublish: "$(build.artifactstagingdirectory)"
ArtifactName: "drop"
ArtifactType: "Container"
ArtifactType: "Container"

Просмотреть файл

@ -1,10 +1,5 @@
# Changelog
## Version 2.8.0-beta3
- [Make W3C Correlation default and leverage native W3C support from Activity.](https://github.com/microsoft/ApplicationInsights-aspnetcore/pull/958)
- [Fixes Azure Functions performance degradation when W3C enabled.](https://github.com/microsoft/ApplicationInsights-aspnetcore/issues/900)
- [Fix: AppId is never set is Response Headers.](https://github.com/microsoft/ApplicationInsights-aspnetcore/issues/956)
## Version 2.8.0-beta2
- [Fix MVCBeforeAction property fetcher to work with .NET Core 3.0 changes.](https://github.com/microsoft/ApplicationInsights-aspnetcore/issues/936)
- [Catch generic exception from DiagnosticSourceListeners and log instead of failing user request.](https://github.com/microsoft/ApplicationInsights-aspnetcore/issues/957)

Просмотреть файл

@ -0,0 +1,50 @@
namespace Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners
{
#if NET451 || NET46
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
#else
using System.Threading;
#endif
/// <summary>
/// Represents ambient data that is local to a given asynchronous control flow, such as an asynchronous method.
/// </summary>
/// <typeparam name="T">The type of the ambient data. </typeparam>
internal class ContextData<T>
{
#if NET451 || NET46
private static readonly string Key = typeof(ContextData<T>).FullName;
/// <summary>
/// Gets or sets the value of the ambient data.
/// </summary>
/// <returns>The value of the ambient data. </returns>
public T Value
{
get
{
var handle = CallContext.LogicalGetData(Key) as ObjectHandle;
return handle != null ? (T)handle.Unwrap() : default(T);
}
set
{
CallContext.LogicalSetData(Key, new ObjectHandle(value));
}
}
#else
private readonly AsyncLocal<T> storage = new AsyncLocal<T>();
/// <summary>
/// Gets or sets the value of the ambient data.
/// </summary>
/// <returns>The value of the ambient data. </returns>
public T Value
{
get { return this.storage.Value; }
set { this.storage.Value = value; }
}
#endif
}
}

Просмотреть файл

@ -72,7 +72,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners
/// Http Headers only allow Printable US-ASCII characters.
/// Remove all other characters.
/// </summary>
/// <returns>sanitized string.</returns>
public static string SanitizeString(string input)
{
if (string.IsNullOrWhiteSpace(input))

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -9,20 +9,20 @@ namespace Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners
using Microsoft.AspNetCore.Http;
/// <summary>
/// <see cref="IApplicationInsightDiagnosticListener"/> implementation that listens for events specific to AspNetCore Mvc layer.
/// <see cref="IApplicationInsightDiagnosticListener"/> implementation that listens for evens specific to AspNetCore Mvc layer
/// </summary>
[Obsolete("This class was merged with HostingDiagnosticsListener to optimize Diagnostics Source subscription performance")]
public class MvcDiagnosticsListener : IApplicationInsightDiagnosticListener
{
/// <inheritdoc />
public string ListenerName { get; } = "Microsoft.AspNetCore";
private readonly PropertyFetcher httpContextFetcher = new PropertyFetcher("httpContext");
private readonly PropertyFetcher routeDataFetcher = new PropertyFetcher("routeData");
private readonly PropertyFetcher routeValuesFetcher = new PropertyFetcher("Values");
/// <inheritdoc />
public string ListenerName { get; } = "Microsoft.AspNetCore";
/// <summary>
/// Diagnostic event handler method for 'Microsoft.AspNetCore.Mvc.BeforeAction' event.
/// Diagnostic event handler method for 'Microsoft.AspNetCore.Mvc.BeforeAction' event
/// </summary>
public void OnBeforeAction(HttpContext httpContext, IDictionary<string, object> routeValues)
{
@ -40,49 +40,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners
}
}
/// <inheritdoc />
public void OnSubscribe()
{
}
/// <inheritdoc />
public void OnNext(KeyValuePair<string, object> value)
{
try
{
if (value.Key == "Microsoft.AspNetCore.Mvc.BeforeAction")
{
var context = this.httpContextFetcher.Fetch(value.Value) as HttpContext;
var routeData = this.routeDataFetcher.Fetch(value.Value);
var routeValues = this.routeValuesFetcher.Fetch(routeData) as IDictionary<string, object>;
if (context != null && routeValues != null)
{
this.OnBeforeAction(context, routeValues);
}
}
}
catch (Exception ex)
{
AspNetCoreEventSource.Instance.DiagnosticListenerWarning("MvcDiagnosticsListener", value.Key, ex.Message);
}
}
/// <inheritdoc />
public void OnError(Exception error)
{
}
/// <inheritdoc />
public void OnCompleted()
{
}
/// <inheritdoc />
public void Dispose()
{
}
private string GetNameFromRouteContext(IDictionary<string, object> routeValues)
{
string name = null;
@ -138,5 +95,48 @@ namespace Microsoft.ApplicationInsights.AspNetCore.DiagnosticListeners
return name;
}
/// <inheritdoc />
public void OnSubscribe()
{
}
/// <inheritdoc />
public void OnNext(KeyValuePair<string, object> value)
{
try
{
if (value.Key == "Microsoft.AspNetCore.Mvc.BeforeAction")
{
var context = this.httpContextFetcher.Fetch(value.Value) as HttpContext;
var routeData = routeDataFetcher.Fetch(value.Value);
var routeValues = routeValuesFetcher.Fetch(routeData) as IDictionary<string, object>;
if (context != null && routeValues != null)
{
this.OnBeforeAction(context, routeValues);
}
}
}
catch (Exception ex)
{
AspNetCoreEventSource.Instance.DiagnosticListenerWarning("MvcDiagnosticsListener", value.Key, ex.Message);
}
}
/// <inheritdoc />
public void OnError(Exception error)
{
}
/// <inheritdoc />
public void OnCompleted()
{
}
/// <inheritdoc />
public void Dispose()
{
}
}
}

Просмотреть файл

@ -29,14 +29,5 @@
/// Correlation-Context header.
/// </summary>
public const string CorrelationContextHeader = "Correlation-Context";
//
// Summary:
// W3C traceparent header name.
public const string TraceParentHeader = "traceparent";
//
// Summary:
// W3C tracestate header name.
public const string TraceStateHeader = "tracestate";
}
}

Просмотреть файл

@ -111,27 +111,18 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.
this.WriteEvent(9, this.ApplicationName);
}
/// <summary>
/// Logs an event when a TelemetryModule is not found to configure.
/// </summary>
[Event(11, Message = "Unable to configure module {0} as it is not found in service collection.", Level = EventLevel.Warning, Keywords = Keywords.Diagnostics)]
public void UnableToFindModuleToConfigure(string moduleType, string appDomainName = "Incorrect")
{
this.WriteEvent(11, moduleType, this.ApplicationName);
}
/// <summary>
/// Logs an event when QuickPulseTelemetryModule is not found in service collection.
/// </summary>
[Event(12, Message = "Unable to find QuickPulseTelemetryModule in service collection. LiveMetrics feature will not be available. Please add QuickPulseTelemetryModule to services collection in the ConfigureServices method of your application Startup class.", Level = EventLevel.Error, Keywords = Keywords.Diagnostics)]
public void UnableToFindQuickPulseModuleInDI(string appDomainName = "Incorrect")
{
this.WriteEvent(12, this.ApplicationName);
}
/// <summary>
/// Logs an event when telemetry is not tracked as the Listener is not active.
/// </summary>
[Event(
13,
Keywords = Keywords.Diagnostics,
@ -142,9 +133,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.
this.WriteEvent(13, evntName, activityId, this.ApplicationName);
}
/// <summary>
/// Logs an event for when generic error occur within the SDK.
/// </summary>
[Event(
14,
Keywords = Keywords.Diagnostics,
@ -155,9 +143,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.
this.WriteEvent(14, errorMessage, this.ApplicationName);
}
/// <summary>
/// Logs an event when RequestTrackingModule failed to initialize.
/// </summary>
[Event(
15,
Keywords = Keywords.Diagnostics,
@ -168,9 +153,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.
this.WriteEvent(15, errorMessage, this.ApplicationName);
}
/// <summary>
/// Logs an event when any error occurs within DiagnosticListener callback.
/// </summary>
[Event(
16,
Keywords = Keywords.Diagnostics,
@ -181,9 +163,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.
this.WriteEvent(16, callback, errorMessage, this.ApplicationName);
}
/// <summary>
/// Logs an event when TelemetryConfiguration configure has failed.
/// </summary>
[Event(
17,
Keywords = Keywords.Diagnostics,
@ -193,10 +172,7 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.
{
this.WriteEvent(17, errorMessage, this.ApplicationName);
}
/// <summary>
/// Logs an event when a telemetry item is sampled out at head.
/// </summary>
[Event(
18,
Keywords = Keywords.Diagnostics,
@ -207,42 +183,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore.Extensibility.Implementation.
this.WriteEvent(18, operationId, this.ApplicationName);
}
/// <summary>
/// Logs an informational event from Hosting listeners.
/// </summary>
[Event(
19,
Message = "Hosting Major Version: '{0}'. Informational Message: '{1}'.",
Level = EventLevel.Informational)]
public void HostingListenerInformational(string hostingVersion, string message, string appDomainName = "Incorrect")
{
this.WriteEvent(19, hostingVersion, message, this.ApplicationName);
}
/// <summary>
/// Logs a verbose event.
/// </summary>
[Event(
20,
Message = "Message: '{0}'.",
Level = EventLevel.Verbose)]
public void HostingListenerVerboe(string message, string appDomainName = "Incorrect")
{
this.WriteEvent(20, message, this.ApplicationName);
}
/// <summary>
/// Logs an event for RequestTelemetry created.
/// </summary>
[Event(
21,
Message = "RequestTelemetry created. CorrelationFormat: '{0}', RequestID: '{1}', OperationId : '{2}' ",
Level = EventLevel.Informational)]
public void RequestTelemetryCreated(string correlationFormat, string requestId, string requestOperationId, string appDomainName = "Incorrect")
{
this.WriteEvent(21, correlationFormat, requestId, requestOperationId, this.ApplicationName);
}
/// <summary>
/// Keywords for the AspNetEventSource.
/// </summary>

Просмотреть файл

@ -6,8 +6,7 @@
public class RequestCollectionOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="RequestCollectionOptions"/> class
/// and populates default values.
/// Creates new instance of <see cref="RequestCollectionOptions"/> class and fills default values.
/// </summary>
public RequestCollectionOptions()
{
@ -20,23 +19,21 @@
#else
this.TrackExceptions = true;
#endif
this.EnableW3CDistributedTracing = true;
this.EnableW3CDistributedTracing = false;
}
/// <summary>
/// Gets or sets a value indicating whether Request-Context header is injected into the response.
/// Get or sets value indicating whether Request-Context header is injected into the response.
/// </summary>
public bool InjectResponseHeaders { get; set; }
/// <summary>
/// Gets or sets a value indicating whether exceptions are be tracked by the RequestCOllectionModule.
/// Exceptions could be tracked by ApplicationInsightsLoggerProvider as well which is not affected by
/// this setting.
/// Get or sets value indicating whether exceptions are be tracked.
/// </summary>
public bool TrackExceptions { get; set; }
/// <summary>
/// Gets or sets a value indicating whether W3C distributed tracing standard is enabled.
/// Get or sets value indicating whether W3C distributed tracing standard is enabled.
/// </summary>
public bool EnableW3CDistributedTracing { get; set; }
}

Просмотреть файл

@ -93,7 +93,11 @@ namespace Microsoft.Extensions.DependencyInjection
this.AddSampling(configuration);
this.DisableHeartBeatIfConfigured();
configuration.EnableW3CCorrelation = this.applicationInsightsServiceOptions.RequestCollectionOptions.EnableW3CDistributedTracing;
if (applicationInsightsServiceOptions.RequestCollectionOptions.EnableW3CDistributedTracing)
{
this.EnableW3CHeaders(configuration);
}
configuration.DefaultTelemetrySink.TelemetryProcessorChainBuilder.Build();
configuration.TelemetryProcessorChainBuilder.Build();
@ -198,5 +202,10 @@ namespace Microsoft.Extensions.DependencyInjection
}
}
}
private void EnableW3CHeaders(TelemetryConfiguration configuration)
{
configuration.TelemetryInitializers.Add(new W3COperationCorrelationTelemetryInitializer());
}
}
}

Просмотреть файл

@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>Microsoft.ApplicationInsights.AspNetCore</AssemblyName>
<VersionPrefix>2.8.0-beta3</VersionPrefix>
<LangVersion>7.2</LangVersion>
<VersionPrefix>2.8.0-beta2</VersionPrefix>
<TargetFrameworks>net451;net46;netstandard1.6;netstandard2.0</TargetFrameworks>
<TargetFrameworks Condition=" '$(OS)' != 'Windows_NT' ">netstandard1.6;netstandard2.0</TargetFrameworks>
@ -73,14 +73,14 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.11.0-beta1-build12825" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.11.0-beta1" />
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.11.0-beta1" />
<PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.11.0-beta1" />
<PackageReference Include="Microsoft.ApplicationInsights.WindowsServer" Version="2.11.0-beta1" />
<PackageReference Include="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" Version="2.11.0-beta1-build12825" />
<PackageReference Include="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" Version="2.11.0-beta1" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="1.0.2" />
<PackageReference Include="System.Text.Encodings.Web" Version="4.3.1" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.6.0-preview7.19362.9" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.5.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'netstandard2.0' ">

Просмотреть файл

@ -31,7 +31,7 @@ namespace Microsoft.ApplicationInsights.AspNetCore
/// <summary>
/// Initializes a new instance of the <see cref="RequestTrackingTelemetryModule"/> class.
/// </summary>
public RequestTrackingTelemetryModule()
public RequestTrackingTelemetryModule()
: this(null)
{
this.CollectionOptions = new RequestCollectionOptions();
@ -89,8 +89,6 @@ namespace Microsoft.ApplicationInsights.AspNetCore
this.subscriptions?.Add(DiagnosticListener.AllListeners.Subscribe(this));
// Questionable to modify the configuration here.
configuration.EnableW3CCorrelation = this.CollectionOptions.EnableW3CDistributedTracing;
this.isInitialized = true;
}
}

Просмотреть файл

@ -14,7 +14,6 @@
/// <summary>
/// Get the Assembly Version with SDK prefix.
/// </summary>
/// <returns>assembly version prefixed with versionprefix.</returns>
internal static string GetVersion()
{
return VersionPrefix + GetAssemblyVersion();

Просмотреть файл

@ -47,8 +47,8 @@
this.ValidateBasicRequest(server, RequestPath, expectedRequestTelemetry);
}
}
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestMixedTelemetryItemsReceived()
{
InProcessServer server;

Просмотреть файл

@ -12,7 +12,7 @@
}
// The NET451 conditional check is wrapped inside the test to make the tests visible in the test explorer. We can move them to the class level once if the issue is resolved.
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestBasicDependencyPropertiesAfterRequestingBasicPage()
{
this.ValidateBasicDependency(assemblyName, "/");

Просмотреть файл

@ -63,7 +63,7 @@
}
}
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestMixedTelemetryItemsReceived()
{
using (var server = new InProcessServer(assemblyName, this.output))

Просмотреть файл

@ -14,7 +14,7 @@
// The NET451 conditional check is wrapped inside the test to make the tests visible in the test explorer. We can move them to the class level once if the issue is resolved.
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestBasicDependencyPropertiesAfterRequestingBasicPage()
{
const string RequestPath = "/";
@ -34,7 +34,9 @@
[Fact]
public void TestIfPerformanceCountersAreCollected()
{
#if NET451 || NET461
ValidatePerformanceCountersAreCollected(assemblyName);
#endif
}
}
}

Просмотреть файл

@ -85,7 +85,7 @@
Assert.NotEmpty(actual.Context.Operation.Name);
Assert.NotEmpty(actual.Context.Operation.Id);
}
public void ValidateBasicDependency(string assemblyName, string requestPath, Func<IWebHostBuilder, IWebHostBuilder> configureHost = null)
{
DependencyTelemetry expected = new DependencyTelemetry();

Просмотреть файл

@ -14,7 +14,9 @@
using Xunit;
using Xunit.Abstractions;
using Microsoft.ApplicationInsights.Extensibility;
#if NET451 || NET461
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;
#endif
public abstract class TelemetryTestsBase
{
@ -107,6 +109,7 @@
return (requestTelemetry, dependencyTelemetry);
}
#if NET451 || NET461
public void ValidatePerformanceCountersAreCollected(string assemblyName)
{
using (var server = new InProcessServer(assemblyName, this.output))
@ -123,6 +126,7 @@
Assert.True(actual.Length > 0);
}
}
#endif
protected HttpResponseMessage ExecuteRequest(string requestPath, Dictionary<string, string> headers = null)
{

Просмотреть файл

@ -68,7 +68,7 @@ namespace MVCFramework.FunctionalTests.FunctionalTest
}
}
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestMixedTelemetryItemsReceived()
{
InProcessServer server;

Просмотреть файл

@ -13,8 +13,8 @@
}
// The NET451 conditional check is wrapped inside the test to make the tests visible in the test explorer. We can move them to the class level once if the issue is resolved.
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestBasicDependencyPropertiesAfterRequestingBasicPage()
{
this.ValidateBasicDependency(assemblyName, "/Home/About/5", InProcessServer.UseApplicationInsights);

Просмотреть файл

@ -1,4 +1,4 @@
namespace MVC20.FuncTests
namespace MVCFramework20.FunctionalTests.FunctionalTest
{
using FunctionalTestUtils;
using Microsoft.ApplicationInsights.DataContracts;

Просмотреть файл

@ -1,5 +1,5 @@
namespace MVC20.FuncTests
{
namespace MVCFramework20.FunctionalTests.FunctionalTest
{
using System;
using System.Linq;
using System.Net.Http;

Просмотреть файл

@ -1,7 +1,7 @@
using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace MVC20.FuncTests
namespace MVCFramework20.FunctionalTests.FunctionalTest
{
using System;
using FunctionalTestUtils;

Просмотреть файл

@ -1,4 +1,4 @@
namespace MVC20.FuncTests
namespace MVCFramework20.FunctionalTests.FunctionalTest
{
using System.Collections.Generic;
using System.Linq;
@ -87,7 +87,7 @@
}
}
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestMixedTelemetryItemsReceived()
{
using (var server = new InProcessServer(assemblyName, this.output))

Просмотреть файл

@ -1,4 +1,4 @@
namespace MVC20.FuncTests
namespace MVCFramework20.FunctionalTests.FunctionalTest
{
using FunctionalTestUtils;
using Microsoft.ApplicationInsights.DataContracts;
@ -15,7 +15,7 @@
// The NET451 conditional check is wrapped inside the test to make the tests visible in the test explorer. We can move them to the class level once if the issue is resolved.
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestBasicDependencyPropertiesAfterRequestingBasicPage()
{
const string RequestPath = "/Home/About/5";
@ -35,7 +35,9 @@
[Fact]
public void TestIfPerformanceCountersAreCollected()
{
#if NET451 || NET461
ValidatePerformanceCountersAreCollected(assemblyName);
#endif
}
}
}

Просмотреть файл

@ -62,11 +62,8 @@
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.7.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
<PackageReference Include="xunit" Version="2.3.1" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" />
</ItemGroup>

Просмотреть файл

@ -1,8 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.ApplicationInsights.AspNetCore.Tests
{
public enum AspNetCoreMajorVersion { One, Two, Three};
}

Просмотреть файл

@ -1050,7 +1050,7 @@ namespace Microsoft.Extensions.DependencyInjection.Test
}
[Fact]
public static void W3CIsEnabledByDefault()
public static void W3CIsDisabledByDefault()
{
var services = CreateServicesAndAddApplicationinsightsTelemetry(null, "http://localhost:1234/v2/track/");
IServiceProvider serviceProvider = services.BuildServiceProvider();
@ -1066,19 +1066,21 @@ namespace Microsoft.Extensions.DependencyInjection.Test
Assert.Single(requestTracking);
Assert.Single(dependencyTracking);
Assert.True(requestTracking.Single().CollectionOptions.EnableW3CDistributedTracing);
Assert.True(dependencyTracking.Single().EnableW3CHeadersInjection);
Assert.False(requestTracking.Single().CollectionOptions.EnableW3CDistributedTracing);
Assert.False(dependencyTracking.Single().EnableW3CHeadersInjection);
}
[Fact]
public static void W3CIsDisabledWhenConfiguredInOptions()
public static void W3CIsEnabledWhenConfiguredInOptions()
{
var services = CreateServicesAndAddApplicationinsightsTelemetry(null,
"http://localhost:1234/v2/track/",
o => o.RequestCollectionOptions.EnableW3CDistributedTracing = false);
o => o.RequestCollectionOptions.EnableW3CDistributedTracing = true);
IServiceProvider serviceProvider = services.BuildServiceProvider();
var telemetryConfiguration = serviceProvider.GetTelemetryConfiguration();
Assert.Contains(telemetryConfiguration.TelemetryInitializers, t => t is W3COperationCorrelationTelemetryInitializer);
var modules = serviceProvider.GetServices<ITelemetryModule>().ToList();
var requestTracking = modules.OfType<RequestTrackingTelemetryModule>().ToList();
@ -1086,9 +1088,8 @@ namespace Microsoft.Extensions.DependencyInjection.Test
Assert.Single(requestTracking);
Assert.Single(dependencyTracking);
Assert.False(requestTracking.Single().CollectionOptions.EnableW3CDistributedTracing);
Assert.False(dependencyTracking.Single().EnableW3CHeadersInjection);
Assert.False(telemetryConfiguration.EnableW3CCorrelation);
Assert.True(requestTracking.Single().CollectionOptions.EnableW3CDistributedTracing);
Assert.True(dependencyTracking.Single().EnableW3CHeadersInjection);
}
private static int GetTelemetryProcessorsCountInConfiguration<T>(TelemetryConfiguration telemetryConfiguration)

Просмотреть файл

@ -7,15 +7,15 @@
public static class CommonMocks
{
public const string InstrumentationKey = "REQUIRED";
public const string InstrumentationKeyHash = "0KNjBVW77H/AWpjTEcI7AP0atNgpasSkEll22AtqaVk=";
public const string TestApplicationId = nameof(TestApplicationId);
public static TelemetryClient MockTelemetryClient(Action<ITelemetry> onSendCallback, bool isW3C = true)
public static TelemetryClient MockTelemetryClient(Action<ITelemetry> onSendCallback)
{
return new TelemetryClient(new TelemetryConfiguration()
{
InstrumentationKey = InstrumentationKey,
TelemetryChannel = new FakeTelemetryChannel { OnSend = onSendCallback },
EnableW3CCorrelation = isW3C
TelemetryChannel = new FakeTelemetryChannel { OnSend = onSendCallback }
});
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -3,7 +3,7 @@
<PropertyGroup>
<VersionPrefix>2.0.0</VersionPrefix>
<TargetFrameworks>netcoreapp2.0;net46;netcoreapp1.0</TargetFrameworks>
<TargetFrameworks Condition=" '$(OS)' != 'Windows_NT' ">netcoreapp2.0</TargetFrameworks>
<TargetFrameworks Condition=" '$(OS)' != 'Windows_NT' ">netcoreapp1.0</TargetFrameworks>
<DelaySign Condition=" '$(OS)' == 'Windows_NT' ">true</DelaySign>
<PreserveCompilationContext>true</PreserveCompilationContext>
<AssemblyName>Microsoft.ApplicationInsights.AspNetCore.Tests</AssemblyName>

Просмотреть файл

@ -15,8 +15,7 @@ namespace WebApi.FunctionalTests.FunctionalTest
}
// The NET451 conditional check is wrapped inside the test to make the tests visible in the test explorer. We can move them to the class level once if the issue is resolved.
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestBasicDependencyPropertiesAfterRequestingBasicPage()
{
this.ValidateBasicDependency(assemblyName, "/api/values");

Просмотреть файл

@ -0,0 +1,50 @@
using Xunit;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace WebApi20.FunctionalTests.FunctionalTest
{
using System;
using FunctionalTestUtils;
using Microsoft.ApplicationInsights.DataContracts;
using Xunit.Abstractions;
public class ExceptionTelemetryWebApiTests : TelemetryTestsBase
{
private const string assemblyName = "WebApi20.FunctionalTests20";
public ExceptionTelemetryWebApiTests(ITestOutputHelper output) : base (output)
{
}
[Fact]
public void TestBasicRequestPropertiesAfterRequestingControllerThatThrows()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/exception";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Exception/Get";
expectedRequestTelemetry.ResponseCode = "500";
expectedRequestTelemetry.Success = false;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
// the is no response header because of https://github.com/Microsoft/ApplicationInsights-aspnetcore/issues/717
this.ValidateBasicRequest(server, RequestPath, expectedRequestTelemetry, false);
}
}
[Fact]
public void TestBasicExceptionPropertiesAfterRequestingControllerThatThrows()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
var expectedExceptionTelemetry = new ExceptionTelemetry();
expectedExceptionTelemetry.Exception = new InvalidOperationException();
this.ValidateBasicException(server, "/api/exception", expectedExceptionTelemetry);
}
}
}
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace WebApi20.FuncTests
namespace FunctionalTests
{
using System;
using System.Collections.Generic;
@ -75,7 +75,7 @@
this.DebugTelemetryItems(actual);
// Expect 1 item1.
Assert.Single(actual);
Assert.Equal(1, actual.Count());
ValidateMessage(actual[0], new string[] { "error"});
}

Просмотреть файл

@ -8,7 +8,7 @@ using Microsoft.ApplicationInsights.Extensibility;
using Xunit;
using Xunit.Abstractions;
namespace WebApi20.FuncTests
namespace WebApi20.FunctionalTests20.FunctionalTest
{
public class MultipleWebHostsTests : TelemetryTestsBase
{
@ -19,7 +19,7 @@ namespace WebApi20.FuncTests
{
}
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TwoWebHostsCreatedSequentially()
{
using (var server1 = new InProcessServer(assemblyName, this.output))
@ -51,7 +51,7 @@ namespace WebApi20.FuncTests
}
}
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TwoWebHostsCreatedInParallel()
{
using (var server1 = new InProcessServer(assemblyName, this.output))

Просмотреть файл

@ -1,179 +0,0 @@
namespace WebApi20.FuncTests
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using FunctionalTestUtils;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.ApplicationInsights.DataContracts;
using Xunit;
using Xunit.Abstractions;
public class RequestCollectionTests : TelemetryTestsBase
{
private const string assemblyName = "WebApi20.FunctionalTests20";
public RequestCollectionTests(ITestOutputHelper output) : base (output)
{
}
[Fact]
public void TestIfPerformanceCountersAreCollected()
{
this.output.WriteLine("Validating perfcounters");
ValidatePerformanceCountersAreCollected(assemblyName);
}
[Fact]
public void TestBasicRequestPropertiesAfterRequestingControllerThatThrows()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/exception";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Exception/Get";
expectedRequestTelemetry.ResponseCode = "500";
expectedRequestTelemetry.Success = false;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
// the is no response header because of https://github.com/Microsoft/ApplicationInsights-aspnetcore/issues/717
this.ValidateBasicRequest(server, RequestPath, expectedRequestTelemetry, false);
}
}
[Fact]
public void TestBasicExceptionPropertiesAfterRequestingControllerThatThrows()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
var expectedExceptionTelemetry = new ExceptionTelemetry();
expectedExceptionTelemetry.Exception = new InvalidOperationException();
this.ValidateBasicException(server, "/api/exception", expectedExceptionTelemetry);
}
}
[Fact]
public void TestBasicRequestPropertiesAfterRequestingValuesController()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/values";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
Dictionary<string, string> requestHeaders = new Dictionary<string, string>()
{
{ "Request-Context", "appId=value"},
};
this.ValidateRequestWithHeaders(server, RequestPath, requestHeaders, expectedRequestTelemetry, expectRequestContextInResponse: true);
}
}
[Fact]
public void TestBasicRequestPropertiesAfterRequestingNotExistingController()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/notexistingcontroller";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET /api/notexistingcontroller";
expectedRequestTelemetry.ResponseCode = "404";
expectedRequestTelemetry.Success = false;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
Dictionary<string, string> requestHeaders = new Dictionary<string, string>()
{
{ "Request-Context", "appId=value"},
};
this.ValidateRequestWithHeaders(server, RequestPath, requestHeaders, expectedRequestTelemetry, expectRequestContextInResponse: true);
}
}
[Fact]
public void TestBasicRequestPropertiesAfterRequestingWebApiShimRoute()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/values/1";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get [id]";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
Dictionary<string, string> requestHeaders = new Dictionary<string, string>()
{
{ "Request-Context", "appId=value"},
};
this.ValidateRequestWithHeaders(server, RequestPath, requestHeaders, expectedRequestTelemetry, expectRequestContextInResponse: true);
}
}
[Fact]
public void TestNoHeadersInjectedInResponseWhenConfiguredAndNoIncomingRequestContext()
{
IWebHostBuilder Config(IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry(options => { options.RequestCollectionOptions.InjectResponseHeaders = false; });
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
{
const string RequestPath = "/api/values/1";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get [id]";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
this.ValidateRequestWithHeaders(server, RequestPath, null, expectedRequestTelemetry, false);
}
}
[Fact]
public void TestNoHeadersInjectedInResponseWhenConfiguredAndWithIncomingRequestContext()
{
IWebHostBuilder Config(IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry(options => { options.RequestCollectionOptions.InjectResponseHeaders = false; });
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
{
const string RequestPath = "/api/values/1";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get [id]";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
Dictionary<string, string> requestHeaders = new Dictionary<string, string>()
{
{ "Request-Context", "appId=value"},
};
this.ValidateRequestWithHeaders(server, RequestPath, requestHeaders, expectedRequestTelemetry, false);
}
}
}
}

Просмотреть файл

@ -1,33 +1,129 @@
namespace WebApi20.FuncTests
namespace WebApi20.FunctionalTests.FunctionalTest
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using FunctionalTestUtils;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.DependencyCollector;
using Xunit;
using Xunit.Abstractions;
using System.Linq;
using Microsoft.ApplicationInsights.DependencyCollector;
using System.Text.RegularExpressions;
public class RequestCorrelationTests : TelemetryTestsBase
public class RequestTelemetryWebApiTests : TelemetryTestsBase, IDisposable
{
private const string assemblyName = "WebApi20.FunctionalTests20";
public RequestCorrelationTests(ITestOutputHelper output) : base(output)
public RequestTelemetryWebApiTests(ITestOutputHelper output) : base (output)
{
}
[Fact]
public void TestRequestWithNoCorrelationHeaders()
public void TestBasicRequestPropertiesAfterRequestingValuesController()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/values";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
Dictionary<string, string> requestHeaders = new Dictionary<string, string>()
{
{ "Request-Id", ""},
{ "Request-Context", "appId=value"},
};
this.ValidateRequestWithHeaders(server, RequestPath, requestHeaders, expectedRequestTelemetry, expectRequestContextInResponse: true);
}
}
[Fact]
public void TestBasicRequestPropertiesAfterRequestingNotExistingController()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/notexistingcontroller";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET /api/notexistingcontroller";
expectedRequestTelemetry.ResponseCode = "404";
expectedRequestTelemetry.Success = false;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
Dictionary<string, string> requestHeaders = new Dictionary<string, string>()
{
{ "Request-Id", ""},
{ "Request-Context", "appId=value"},
};
this.ValidateRequestWithHeaders(server, RequestPath, requestHeaders, expectedRequestTelemetry, expectRequestContextInResponse: true);
}
}
[Fact]
public void TestBasicRequestPropertiesAfterRequestingWebApiShimRoute()
{
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/values/1";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get [id]";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
Dictionary<string, string> requestHeaders = new Dictionary<string, string>()
{
{ "Request-Id", ""},
{ "Request-Context", "appId=value"},
};
this.ValidateRequestWithHeaders(server, RequestPath, requestHeaders, expectedRequestTelemetry, expectRequestContextInResponse: true);
}
}
[Fact]
public void TestNoHeaderInjectionRequestTrackingOptions()
{
IWebHostBuilder Config(IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry(options => { options.RequestCollectionOptions.InjectResponseHeaders = false; });
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
{
const string RequestPath = "/api/values/1";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get [id]";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
this.ValidateBasicRequest(server, RequestPath, expectedRequestTelemetry, false);
}
}
[Fact]
public void TestW3COperationIdFormatGeneration()
{
IWebHostBuilder Config(IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry();
// disable Dependency tracking (i.e. header injection)
services.Remove(services.FirstOrDefault(sd => sd.ImplementationType == typeof(DependencyTrackingTelemetryModule)));
});
@ -43,35 +139,19 @@
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new System.Uri(server.BaseHost + RequestPath);
Dictionary<string, string> requestHeaders = new Dictionary<string, string>()
{
// No Request-ID, No TraceParent
{ "Request-Context", "appId=value"},
};
var item = this.ValidateBasicRequest(server, RequestPath, expectedRequestTelemetry);
// W3C compatible-Id ( should go away when W3C is implemented in .NET https://github.com/dotnet/corefx/issues/30331)
Assert.Equal(32, item.tags["ai.operation.id"].Length);
Assert.True(Regex.Match(item.tags["ai.operation.id"], @"[a-z][0-9]").Success);
Assert.False(item.tags.ContainsKey("ai.operation.parentId"));
// end of workaround test
}
}
[Fact]
public void TestRequestWithRequestIdHeader()
public void TestW3CHeadersAreNotEnabledByDefault()
{
IWebHostBuilder Config(IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry();
// disable Dependency tracking (i.e. header injection)
services.Remove(services.FirstOrDefault(sd => sd.ImplementationType == typeof(DependencyTrackingTelemetryModule)));
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
using (var server = new InProcessServer(assemblyName, this.output))
{
const string RequestPath = "/api/values";
@ -81,37 +161,30 @@
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new Uri(server.BaseHost + RequestPath);
var activity = new Activity("dummy").SetParentId("|abc.123.").Start();
var headers = new Dictionary<string, string>
{
// Request-ID Correlation Header
{ "Request-Id", "|8ee8641cbdd8dd280d239fa2121c7e4e.df07da90a5b27d93."},
{ "Request-Context", "appId=value"},
{ "Correlation-Context" , "k1=v1,k2=v2" }
["traceparent"] = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
["tracestate"] = "some=state"
};
var actualRequest = this.ValidateRequestWithHeaders(server, RequestPath, headers, expectedRequestTelemetry);
Assert.Equal("8ee8641cbdd8dd280d239fa2121c7e4e", actualRequest.tags["ai.operation.id"]);
Assert.Contains("|8ee8641cbdd8dd280d239fa2121c7e4e.df07da90a5b27d93.", actualRequest.tags["ai.operation.parentId"]);
Assert.Equal("v1", actualRequest.data.baseData.properties["k1"]);
Assert.Equal("v2", actualRequest.data.baseData.properties["k2"]);
Assert.Equal(activity.RootId, actualRequest.tags["ai.operation.id"]);
Assert.Contains(activity.Id, actualRequest.tags["ai.operation.parentId"]);
}
}
[Fact]
public void TestRequestWithNonW3CCompatibleRequestIdHeader()
public void TestW3CHeadersAreParsedWhenEnabledInConfig()
{
IWebHostBuilder Config(IWebHostBuilder builder)
using (var server = new InProcessServer(assemblyName, this.output, builder =>
{
return builder.ConfigureServices(services =>
return builder.ConfigureServices( services =>
{
services.AddApplicationInsightsTelemetry();
// disable Dependency tracking (i.e. header injection)
services.Remove(services.FirstOrDefault(sd => sd.ImplementationType == typeof(DependencyTrackingTelemetryModule)));
services.AddApplicationInsightsTelemetry(o => o.RequestCollectionOptions.EnableW3CDistributedTracing = true);
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
}))
{
const string RequestPath = "/api/values";
@ -121,91 +194,9 @@
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new Uri(server.BaseHost + RequestPath);
var activity = new Activity("dummy").SetParentId("|abc.123.").Start();
var headers = new Dictionary<string, string>
{
// Request-ID Correlation Header
{ "Request-Id", "|noncompatible.df07da90a5b27d93."},
{ "Request-Context", "appId=value"},
{ "Correlation-Context" , "k1=v1,k2=v2" }
};
var actualRequest = this.ValidateRequestWithHeaders(server, RequestPath, headers, expectedRequestTelemetry);
Assert.NotEqual("noncompatible", actualRequest.tags["ai.operation.id"]);
Assert.Contains("|noncompatible.df07da90a5b27d93.", actualRequest.tags["ai.operation.parentId"]);
Assert.Equal("noncompatible", actualRequest.data.baseData.properties["ai_legacyRootId"]);
Assert.Equal("v1", actualRequest.data.baseData.properties["k1"]);
Assert.Equal("v2", actualRequest.data.baseData.properties["k2"]);
}
}
[Fact]
public void TestRequestWithNonW3CCompatibleNonHierrachicalRequestIdHeader()
{
IWebHostBuilder Config(IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry();
// disable Dependency tracking (i.e. header injection)
services.Remove(services.FirstOrDefault(sd => sd.ImplementationType == typeof(DependencyTrackingTelemetryModule)));
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
{
const string RequestPath = "/api/values";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new Uri(server.BaseHost + RequestPath);
var headers = new Dictionary<string, string>
{
// Request-ID Correlation Header
{ "Request-Id", "somerandomidnotinanyformat"},
{ "Request-Context", "appId=value"},
{ "Correlation-Context" , "k1=v1,k2=v2" }
};
var actualRequest = this.ValidateRequestWithHeaders(server, RequestPath, headers, expectedRequestTelemetry);
Assert.NotEqual("noncompatible", actualRequest.tags["ai.operation.id"]);
Assert.Contains("somerandomidnotinanyformat", actualRequest.tags["ai.operation.parentId"]);
Assert.Equal("somerandomidnotinanyformat", actualRequest.data.baseData.properties["ai_legacyRootId"]);
Assert.Equal("v1", actualRequest.data.baseData.properties["k1"]);
Assert.Equal("v2", actualRequest.data.baseData.properties["k2"]);
}
}
[Fact]
public void TestRequestWithTraceParentHeader()
{
IWebHostBuilder Config(IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry();
// disable Dependency tracking (i.e. header injection)
services.Remove(services.FirstOrDefault(sd => sd.ImplementationType == typeof(DependencyTrackingTelemetryModule)));
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
{
const string RequestPath = "/api/values";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new Uri(server.BaseHost + RequestPath);
var headers = new Dictionary<string, string>
{
// TraceParent Correlation Header
["traceparent"] = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
["tracestate"] = "some=state",
["Correlation-Context"] = "k1=v1,k2=v2"
@ -214,31 +205,22 @@
var actualRequest = this.ValidateRequestWithHeaders(server, RequestPath, headers, expectedRequestTelemetry);
Assert.Equal("4bf92f3577b34da6a3ce929d0e0e4736", actualRequest.tags["ai.operation.id"]);
Assert.Contains("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", actualRequest.tags["ai.operation.parentId"]);
// Correlation-Context will be read if either Request-Id or TraceParent available.
Assert.True(actualRequest.data.baseData.properties.ContainsKey("k1"));
Assert.True(actualRequest.data.baseData.properties.ContainsKey("k2"));
// TraceState is simply set to Activity, and not added to Telemetry.
Assert.False(actualRequest.data.baseData.properties.ContainsKey("some"));
Assert.Equal("|4bf92f3577b34da6a3ce929d0e0e4736.00f067aa0ba902b7.", actualRequest.tags["ai.operation.parentId"]);
Assert.Equal("v1", actualRequest.data.baseData.properties["k1"]);
Assert.Equal("v2", actualRequest.data.baseData.properties["k2"]);
}
}
[Fact]
public void TestRequestWithRequestIdAndTraceParentHeader()
public void TestW3CEnabledW3CHeadersOnly()
{
IWebHostBuilder Config(IWebHostBuilder builder)
using (var server = new InProcessServer(assemblyName, this.output, builder =>
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry();
// disable Dependency tracking (i.e. header injection)
services.Remove(services.FirstOrDefault(sd => sd.ImplementationType == typeof(DependencyTrackingTelemetryModule)));
services.AddApplicationInsightsTelemetry(o => o.RequestCollectionOptions.EnableW3CDistributedTracing = true);
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
}))
{
const string RequestPath = "/api/values";
@ -250,43 +232,30 @@
var headers = new Dictionary<string, string>
{
// Both request id and traceparent
["Request-Id"] = "|8ee8641cbdd8dd280d239fa2121c7e4e.df07da90a5b27d93.",
["traceparent"] = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
["tracestate"] = "some=state",
["tracestate"] = "some=state,az=cid-v1:xyz",
["Correlation-Context"] = "k1=v1,k2=v2"
};
var actualRequest = this.ValidateRequestWithHeaders(server, RequestPath, headers, expectedRequestTelemetry);
Assert.Equal("4bf92f3577b34da6a3ce929d0e0e4736", actualRequest.tags["ai.operation.id"]);
Assert.NotEqual("8ee8641cbdd8dd280d239fa2121c7e4e", actualRequest.tags["ai.operation.id"]);
Assert.Contains("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", actualRequest.tags["ai.operation.parentId"]);
// Correlation-Context will be read if either Request-Id or traceparent is present.
Assert.True(actualRequest.data.baseData.properties.ContainsKey("k1"));
Assert.True(actualRequest.data.baseData.properties.ContainsKey("k2"));
// TraceState is simply set to Activity, and not added to Telemetry.
Assert.False(actualRequest.data.baseData.properties.ContainsKey("some"));
Assert.StartsWith("|4bf92f3577b34da6a3ce929d0e0e4736.00f067aa0ba902b7.", actualRequest.tags["ai.operation.parentId"]);
Assert.Equal("v1", actualRequest.data.baseData.properties["k1"]);
Assert.Equal("v2", actualRequest.data.baseData.properties["k2"]);
}
}
[Fact]
public void TestRequestWithRequestIdAndTraceParentHeaderWithW3CDisabled()
public void TestW3CEnabledRequestIdAndW3CHeaders()
{
IWebHostBuilder Config(IWebHostBuilder builder)
using (var server = new InProcessServer(assemblyName, this.output, builder =>
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry(o => o.RequestCollectionOptions.EnableW3CDistributedTracing = false);
// disable Dependency tracking (i.e. header injection)
services.Remove(services.FirstOrDefault(sd => sd.ImplementationType == typeof(DependencyTrackingTelemetryModule)));
services.AddApplicationInsightsTelemetry(o => o.RequestCollectionOptions.EnableW3CDistributedTracing = true);
});
}
using (var server = new InProcessServer(assemblyName, this.output, Config))
}))
{
const string RequestPath = "/api/values";
@ -296,25 +265,95 @@
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new Uri(server.BaseHost + RequestPath);
// this will force Request-Id header injection, it will start with |abc.123.
var activity = new Activity("dummy").SetParentId("|abc.123.").Start();
var headers = new Dictionary<string, string>
{
// Both request id and traceparent
["Request-Id"] = "|8ee8641cbdd8dd280d239fa2121c7e4e.df07da90a5b27d93.",
["traceparent"] = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
["tracestate"] = "some=state",
["tracestate"] = "some=state,az=cid-v1:xyz",
["Correlation-Context"] = "k1=v1,k2=v2"
};
var actualRequest = this.ValidateRequestWithHeaders(server, RequestPath, headers, expectedRequestTelemetry);
Assert.Equal("8ee8641cbdd8dd280d239fa2121c7e4e", actualRequest.tags["ai.operation.id"]);
Assert.NotEqual("4bf92f3577b34da6a3ce929d0e0e4736", actualRequest.tags["ai.operation.id"]);
Assert.Contains("|8ee8641cbdd8dd280d239fa2121c7e4e.df07da90a5b27d93.", actualRequest.tags["ai.operation.parentId"]);
Assert.Equal("4bf92f3577b34da6a3ce929d0e0e4736", actualRequest.tags["ai.operation.id"]);
Assert.StartsWith("|4bf92f3577b34da6a3ce929d0e0e4736.00f067aa0ba902b7.", actualRequest.tags["ai.operation.parentId"]);
Assert.Equal("v1", actualRequest.data.baseData.properties["k1"]);
Assert.Equal("v2", actualRequest.data.baseData.properties["k2"]);
Assert.Equal("abc", actualRequest.data.baseData.properties["ai_legacyRootId"]);
Assert.StartsWith("|abc.123", actualRequest.data.baseData.properties["ai_legacyRequestId"]);
}
}
// Correlation-Context should be read and populated.
Assert.True(actualRequest.data.baseData.properties.ContainsKey("k1"));
Assert.True(actualRequest.data.baseData.properties.ContainsKey("k2"));
[Fact]
public void TestW3CEnabledRequestIdAndNoW3CHeaders()
{
using (var server = new InProcessServer(assemblyName, this.output,
builder =>
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry(o => o.RequestCollectionOptions.EnableW3CDistributedTracing = true);
services.ConfigureTelemetryModule<DependencyTrackingTelemetryModule>((m, o) =>
{
// no correlation headers so we can test request
// call without auto-injected w3c headers
m.ExcludeComponentCorrelationHttpHeadersOnDomains.Add("localhost");
});
});
}))
{
const string RequestPath = "/api/values";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new Uri(server.BaseHost + RequestPath);
// this will force Request-Id header injection, it will start with |abc.123.
var activity = new Activity("dummy").SetParentId("|abc.123.").Start();
var actualRequest = this.ValidateBasicRequest(server, RequestPath, expectedRequestTelemetry);
Assert.Equal(32, actualRequest.tags["ai.operation.id"].Length);
Assert.StartsWith("|abc.123.", actualRequest.tags["ai.operation.parentId"]);
}
}
[Fact]
public void TestW3CIsUsedWithoutHeadersWhenEnabledInConfig()
{
using (var server = new InProcessServer(assemblyName, this.output,
builder =>
{
return builder.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetry(o => o.RequestCollectionOptions.EnableW3CDistributedTracing = true);
});
}))
{
const string RequestPath = "/api/values";
var expectedRequestTelemetry = new RequestTelemetry();
expectedRequestTelemetry.Name = "GET Values/Get";
expectedRequestTelemetry.ResponseCode = "200";
expectedRequestTelemetry.Success = true;
expectedRequestTelemetry.Url = new Uri(server.BaseHost + RequestPath);
var actualRequest = this.ValidateBasicRequest(server, RequestPath, expectedRequestTelemetry);
Assert.Equal(32, actualRequest.tags["ai.operation.id"].Length);
Assert.Equal(1 + 32 + 1 + 16 + 1, actualRequest.data.baseData.id.Length);
}
}
public void Dispose()
{
while (Activity.Current != null)
{
Activity.Current.Stop();
}
}
}
}

Просмотреть файл

@ -1,4 +1,4 @@
namespace WebApi20.FuncTests
namespace WebApi20.FunctionalTests.FunctionalTest
{
using FunctionalTestUtils;
using System;
@ -12,16 +12,16 @@
using Xunit;
using Xunit.Abstractions;
public class RequestDependencyCorrelationTests : TelemetryTestsBase, IDisposable
public class TelemetryModuleWorkingWebApiTests : TelemetryTestsBase, IDisposable
{
private const string assemblyName = "WebApi20.FunctionalTests20";
public RequestDependencyCorrelationTests(ITestOutputHelper output) : base (output)
public TelemetryModuleWorkingWebApiTests(ITestOutputHelper output) : base (output)
{
}
// The NET451 conditional check is wrapped inside the test to make the tests visible in the test explorer. We can move them to the class level once if the issue is resolved.
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestBasicDependencyPropertiesAfterRequestingBasicPage()
{
const string RequestPath = "/api/values";
@ -38,8 +38,7 @@
}
}
// We may need to add more tests to cover Request + Dependency Tracking
[Fact(Skip = "Re-Enable once DependencyTrackingModule is updated to latest DiagnosticSource.")]
[Fact]
public void TestDependencyAndRequestWithW3CStandard()
{
const string RequestPath = "/api/values";
@ -84,6 +83,15 @@
}
}
[Fact]
public void TestIfPerformanceCountersAreCollected()
{
#if NET451 || NET461
this.output.WriteLine("Validating perfcounters");
ValidatePerformanceCountersAreCollected(assemblyName);
#endif
}
public void Dispose()
{
while (Activity.Current != null)