public static void DispatchRequest(RequestTelemetry request, TimeSpan duration, bool success) { request.Duration = duration; request.Success = success; request.ResponseCode = (success) ? SUCCESS_CODE : FAILURE_CODE; AI_CLIENT.TrackRequest(request); }
public void RichPayloadEventSourceRequestSentTest() { var client = new TelemetryClient(); client.InstrumentationKey = Guid.NewGuid().ToString(); using (var listener = new Microsoft.ApplicationInsights.TestFramework.TestEventListener()) { listener.EnableEvents(RichPayloadEventSource.Log.EventSourceInternal, EventLevel.Verbose, RichPayloadEventSource.Keywords.Requests); var item = new RequestTelemetry("TestRequest", DateTimeOffset.Now, TimeSpan.FromMilliseconds(10), "200", true); item.Context.Properties.Add("property1", "value1"); item.Context.User.Id = "testUserId"; item.Context.Operation.Id = Guid.NewGuid().ToString(); client.TrackRequest(item); var actualEvent = listener.Messages.FirstOrDefault(); Assert.IsNotNull(actualEvent); Assert.AreEqual(client.InstrumentationKey, actualEvent.Payload[0]); object[] tags = actualEvent.Payload[1] as object[]; Assert.AreEqual("ai.user.id", ((Dictionary<string, object>)(tags[0]))["Key"]); Assert.AreEqual("testUserId", ((Dictionary<string, object>)(tags[0]))["Value"]); Assert.AreEqual("ai.operation.id", ((Dictionary<string, object>)(tags[1]))["Key"]); Assert.AreEqual(item.Context.Operation.Id, ((Dictionary<string, object>)(tags[1]))["Value"]); Assert.IsNotNull(actualEvent.Payload[2]); } }
public static RequestTelemetry StartNewRequest(string name, DateTimeOffset startTime) { var request = new RequestTelemetry(); request.Name = name; request.Timestamp = startTime; return request; }
public static HttpContextAccessor CreateHttpContextAccessor(RequestTelemetry requestTelemetry = null, ActionContext actionContext = null) { var services = new ServiceCollection(); var request = new DefaultHttpContext().Request; request.Method = "GET"; request.Path = new PathString("/Test"); var contextAccessor = new HttpContextAccessor() { HttpContext = request.HttpContext }; services.AddInstance<IHttpContextAccessor>(contextAccessor); if (actionContext != null) { var si = new ActionContextAccessor(); si.ActionContext = actionContext; services.AddInstance<IActionContextAccessor>(si); } if (requestTelemetry != null) { services.AddInstance<RequestTelemetry>(requestTelemetry); } IServiceProvider serviceProvider = services.BuildServiceProvider(); contextAccessor.HttpContext.RequestServices = serviceProvider; return contextAccessor; }
internal void GetAuthUserContextFromUserCookie(HttpCookie authUserCookie, RequestTelemetry requestTelemetry) { if (authUserCookie == null) { // Request does not have authenticated user WebEventSource.Log.AuthIdTrackingCookieNotAvailable(); return; } if (string.IsNullOrEmpty(authUserCookie.Value)) { // Request does not have authenticated user WebEventSource.Log.AuthIdTrackingCookieIsEmpty(); return; } var authUserCookieString = HttpUtility.UrlDecode(authUserCookie.Value); var cookieParts = authUserCookieString.Split('|'); if (cookieParts.Length > 0) { requestTelemetry.Context.User.AuthenticatedUserId = cookieParts[0]; } }
/// <summary> /// Implements initialization logic. /// </summary> /// <param name="platformContext">Http context.</param> /// <param name="requestTelemetry">Request telemetry object associated with the current request.</param> /// <param name="telemetry">Telemetry item to initialize.</param> protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { if (string.IsNullOrEmpty(telemetry.Context.Operation.SyntheticSource)) { if (platformContext != null) { var request = platformContext.GetRequest(); if (request != null && !string.IsNullOrEmpty(request.UserAgent)) { // We expect customers to configure telemetry initializer before they add it to active configuration // So we will not protect fiterPatterns array with locks (to improve perf) foreach (string pattern in this.filterPatterns) { if (!string.IsNullOrWhiteSpace(pattern) && request.UserAgent.IndexOf(pattern, StringComparison.OrdinalIgnoreCase) != -1) { telemetry.Context.Operation.SyntheticSource = "Bot"; return; } } } } } }
protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { if (string.IsNullOrEmpty(telemetry.Context.Operation.Id)) { telemetry.Context.Operation.Id = requestTelemetry.Id; } }
public void InitializeAssignsVersionToTelemetry() { var initializer = new ComponentVersionTelemetryInitializer(this.BuildConfigurationWithVersion()); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry); Assert.NotNull(telemetry.Context.Component.Version); }
/// <summary> /// Implements initialization logic. /// </summary> /// <param name="platformContext">Http context.</param> /// <param name="requestTelemetry">Request telemetry object associated with the current request.</param> /// <param name="telemetry">Telemetry item to initialize.</param> protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { if (platformContext != null) { var request = platformContext.GetRequest(); if (request != null) { foreach (var pattern in this.filterPatterns) { if (pattern.RegularExpression != null && request.UserAgent != null) { var match = pattern.RegularExpression.Match(request.UserAgent); if (match.Success) { if (string.IsNullOrEmpty(telemetry.Context.Operation.SyntheticSource)) { telemetry.Context.Operation.SyntheticSource = !string.IsNullOrWhiteSpace(pattern.SourceName) ? pattern.SourceName : match.Value; return; } } } } } } }
public void ParameterlessConstructorInitializesRequiredFields() { var request = new RequestTelemetry(); Assert.False(string.IsNullOrEmpty(request.Id)); Assert.Equal("200", request.ResponseCode); Assert.Equal(true, request.Success); }
public async Task Invoke(HttpContext httpContext, RequestTelemetry telemetry) { telemetry.Timestamp = DateTimeOffset.UtcNow; var sw = new Stopwatch(); sw.Start(); bool requestFailed = false; try { await this.next.Invoke(httpContext); } catch (Exception) { requestFailed = true; throw; } finally { sw.Stop(); telemetry.Duration = sw.Elapsed; telemetry.ResponseCode = httpContext.Response.StatusCode.ToString(); telemetry.Success = (!requestFailed) && (httpContext.Response.StatusCode < 400); telemetry.HttpMethod = httpContext.Request.Method; telemetry.Url = httpContext.Request.GetUri(); telemetry.Context.GetInternalContext().SdkVersion = this.sdkVersion; this.telemetryClient.TrackRequest(telemetry); } }
protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleInstance)) { var name = LazyInitializer.EnsureInitialized(ref this.roleInstanceName, this.GetMachineName); telemetry.Context.Cloud.RoleInstance = name; } }
public void InitializeSetsNullVersionIfBuildRootInfoNull() { var source = new BuildInfoConfigComponentVersionTelemetryInitializer(); var requestTelemetry = new RequestTelemetry(); source.Initialize(requestTelemetry); Assert.IsNull(requestTelemetry.Context.Component.Version); }
public void InitializeDoesNotThrowIfVersionDoesNotExist() { var config = new ConfigurationBuilder() .Build(); var initializer = new ComponentVersionTelemetryInitializer(config); var telemetry = new RequestTelemetry(); initializer.Initialize(telemetry); }
public void InitializeSetsSdkVersionPropertyOfGivenTelemetry() { var initializer = new SdkVersionPropertyTelemetryInitializer(); var item = new RequestTelemetry(); initializer.Initialize(item); Assert.NotNull(item.Context.Internal.SdkVersion); }
public void InitializeDoesNotOverrideExistingVersion() { var initializer = new ComponentVersionTelemetryInitializer(this.BuildConfigurationWithVersion()); var telemetry = new RequestTelemetry(); telemetry.Context.Component.Version = "TestVersion"; initializer.Initialize(telemetry); Assert.Equal("TestVersion", telemetry.Context.Component.Version); }
private static void LogUsageEvent(AzurePSQoSEvent qos) { var tcEvent = new RequestTelemetry(qos.CmdletType, qos.StartTime, qos.Duration, string.Empty, qos.IsSuccess); tcEvent.Context.User.Id = qos.Uid; tcEvent.Context.User.UserAgent = AzurePowerShell.UserAgentValue.ToString(); tcEvent.Context.Device.OperatingSystem = Environment.OSVersion.VersionString; TelemetryClient.TrackRequest(tcEvent); }
public void GetVersionReturnsCorrectVersion() { var doc = XDocument.Load(new StringReader("<DeploymentEvent><Build><MSBuild><BuildLabel>123</BuildLabel></MSBuild></Build></DeploymentEvent>")).Root; var source = new BuildInfoConfigComponentVersionTelemetryInitializerMock(doc); var requestTelemetry = new RequestTelemetry(); source.Initialize(requestTelemetry); Assert.AreEqual("123", requestTelemetry.Context.Component.Version); }
public void InitializeDoesNotThrowWhenHttpContextIsNull() { var requestTelemetry = new RequestTelemetry(); var source = new OperationNameTelemetryInitializer(); source.Initialize(requestTelemetry); Assert.AreEqual(string.Empty, requestTelemetry.Name); }
public RequestTelemetryMessage(RequestTelemetry telemetry) { this.Time = telemetry.Timestamp.DateTime; this.Name = telemetry.Name; this.Details = "Response Code: " + telemetry.ResponseCode + "\n\r Succesful Request: " + telemetry.Success + "\n\r Request URL: " + telemetry.Url; this.Properties = telemetry.Properties.Count > 0 ? telemetry.Properties : null; this.Type = "Request"; this.Context = telemetry.Context; }
public void DeviceContextReaderAssignedNetwork() { var requestTelemetry = new RequestTelemetry(); new DeviceTelemetryInitializer().Initialize(requestTelemetry); string networkType = requestTelemetry.Context.Device.NetworkType; Assert.True(Enum.IsDefined(typeof(NetworkInterfaceType), networkType)); }
public void GetVersionReturnsNullVersionIfXmlDoesNotHaveLabel() { var doc = XDocument.Load(new StringReader("<DeploymentEvent></DeploymentEvent>")).Root; var source = new BuildInfoConfigComponentVersionTelemetryInitializerMock(doc); var requestTelemetry = new RequestTelemetry(); source.Initialize(requestTelemetry); Assert.IsNull(requestTelemetry.Context.Component.Version); }
public void RequestTelemetryHasCorrectValueOfSamplingPercentageAfterSerialization() { var telemetry = new RequestTelemetry { Id = null }; ((ISupportSampling)telemetry).SamplingPercentage = 10; ((ITelemetry)telemetry).Sanitize(); var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<RequestTelemetry, DataPlatformModel.RequestData>(telemetry); Assert.Equal(10, item.SampleRate); }
public void ParameterizedConstructorInitializesNewInstanceWithGivenNameTimestampDurationStatusCodeAndSuccess() { var start = DateTimeOffset.Now; var request = new RequestTelemetry("name", start, TimeSpan.FromSeconds(42), "404", true); Assert.Equal("name", request.Name); Assert.Equal("404", request.ResponseCode); Assert.Equal(TimeSpan.FromSeconds(42), request.Duration); Assert.Equal(true, request.Success); Assert.Equal(start, request.Timestamp); }
internal static RequestTelemetry WithAuthCookie(this HttpContext context, string cookieString) { var requestTelemetry = new RequestTelemetry(); context.AddRequestCookie( new HttpCookie( RequestTrackingConstants.WebAuthenticatedUserCookieName, HttpUtility.UrlEncode(cookieString))) .AddRequestTelemetry(requestTelemetry); return requestTelemetry; }
public void FilterstToGlimpseHandler() { // // TODO: Agregar aquí la lógica de las pruebas // GlimpseTelemetryChannel TestTelemetryChanel = new GlimpseTelemetryChannel(); ITelemetry RTitem = new RequestTelemetry(); ITelemetry DTitem = new DependencyTelemetry(); TestTelemetryChanel.Send(RTitem); TestTelemetryChanel.Send(DTitem); }
protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry) { // TODO: conside using // var connectionFeature = platformContext.GetFeature<HttpRequestFeature>(); // connectionFeature.Headers if (string.IsNullOrEmpty(telemetry.Context.User.UserAgent)) { telemetry.Context.User.UserAgent = platformContext.Request.Headers[HeaderNames.UserAgent]; } }
public void InitializeSetsUserFromCookie() { var requestTelemetry = new RequestTelemetry(); var contextAccessor = HttpContextAccessorHelper.CreateHttpContextAccessor(requestTelemetry); contextAccessor.HttpContext.Request.Headers["Cookie"] = "ai_user=test"; var initializer = new WebUserTelemetryInitializer(contextAccessor); initializer.Initialize(requestTelemetry); Assert.Equal("test", requestTelemetry.Context.User.Id); }
public void InitializeDoesNotNotThrowOnMalformedAcquisitionDate() { var requestTelemetry = new RequestTelemetry(); var contextAccessor = HttpContextAccessorHelper.CreateHttpContextAccessor(requestTelemetry); contextAccessor.HttpContext.Request.Headers["Cookie"] = "ai_user=test|malformeddate"; var initializer = new WebUserTelemetryInitializer(contextAccessor); initializer.Initialize(requestTelemetry); Assert.Equal(null, requestTelemetry.Context.User.Id); Assert.Equal(false, requestTelemetry.Context.User.AcquisitionDate.HasValue); }
/// <summary> /// Initializes a new instance of the <see cref="RequestTelemetry"/> class by cloning an existing instance. /// </summary> /// <param name="source">Source instance of <see cref="RequestTelemetry"/> to clone from.</param> private RequestTelemetry(RequestTelemetry source) { this.Duration = source.Duration; this.Id = source.Id; if (source.measurementsValue != null) { Utils.CopyDictionary(source.Metrics, this.Metrics); } this.Name = source.Name; this.context = source.context.DeepClone(); this.ResponseCode = source.ResponseCode; this.Source = source.Source; this.Success = source.Success; this.Url = source.Url; this.Sequence = source.Sequence; this.Timestamp = source.Timestamp; this.successFieldSet = source.successFieldSet; this.extension = source.extension?.DeepClone(); this.samplingPercentage = source.samplingPercentage; this.ProactiveSamplingDecision = source.ProactiveSamplingDecision; }
public void RequestTelemetrySerializesToJson() { var expected = new RequestTelemetry(); expected.Timestamp = DateTimeOffset.Now; expected.Id = "a1b2c3d4e5f6h7h8i9j10"; expected.Name = "GET /WebForm.aspx"; expected.Duration = TimeSpan.FromSeconds(4); expected.ResponseCode = "200"; expected.Success = true; expected.Url = new Uri("http://localhost/myapp/MyPage.aspx"); expected.HttpMethod = "GET"; expected.Metrics.Add("Metric1", 30); expected.Properties.Add("userHostAddress", "::1"); ((ITelemetry)expected).Sanitize(); var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem <RequestTelemetry, DataPlatformModel.RequestData>(expected); // NOTE: It's correct that we use the v1 name here, and therefore we test against it. Assert.Equal(item.Name, Microsoft.Developer.Analytics.DataCollection.Model.v1.ItemType.Request); Assert.Equal(typeof(DataPlatformModel.RequestData).Name, item.Data.BaseType); Assert.Equal(2, item.Data.BaseData.Ver); Assert.Equal(expected.Id, item.Data.BaseData.Id); Assert.Equal(expected.Name, item.Data.BaseData.Name); Assert.Equal(expected.Timestamp, item.Data.BaseData.StartTime); Assert.Equal(expected.Duration, item.Data.BaseData.Duration); Assert.Equal(expected.Success, item.Data.BaseData.Success); Assert.Equal(expected.ResponseCode, item.Data.BaseData.ResponseCode); Assert.Equal(expected.Url.ToString(), item.Data.BaseData.Url.ToString(), StringComparer.OrdinalIgnoreCase); Assert.Equal(expected.HttpMethod, item.Data.BaseData.HttpMethod); Assert.Equal(1, item.Data.BaseData.Measurements.Count); Assert.Equal(expected.Metrics, item.Data.BaseData.Measurements); Assert.Equal(expected.Properties.ToArray(), item.Data.BaseData.Properties.ToArray()); }
public static void TraceRequest(string operationName, DateTimeOffset startTime, TimeSpan duration, string responseCode, bool success) { var telemetryOperation = new Microsoft.ApplicationInsights.DataContracts.RequestTelemetry(operationName, startTime, duration, responseCode, success); TelemetryClient.TrackRequest(telemetryOperation); }
public void RequestTelemetryReturnsDefaultTimeStampAsDateTimeOffsetMinValue() { RequestTelemetry item = new RequestTelemetry(); Assert.AreEqual(DateTimeOffset.MinValue, item.Timestamp); }
public void RequestTelemetryReturnsDefaultDurationAsTimespanZero() { RequestTelemetry item = new RequestTelemetry(); Assert.AreEqual(TimeSpan.Zero, item.Duration); }
public void RequestTelemetryImplementsISupportAdvancedSamplingContract() { var telemetry = new RequestTelemetry(); Assert.IsNotNull(telemetry as ISupportAdvancedSampling); }
public void ParameterlessConstructorInitializesRequiredFields() { var request = new RequestTelemetry(); Assert.IsFalse(string.IsNullOrEmpty(request.Id)); }
/// <summary> /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. /// </summary> /// <param name="request">The HTTP request message to send to the server.</param> /// <param name="cancellationToken">A cancellation token to cancel operation.</param> protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Guard.NotNull(request, nameof(request)); AppInsights.GenerateAsyncAwareOperationId(); var startTime = DateTimeOffset.UtcNow; var watch = Stopwatch.StartNew(); bool success = true; try { return await base.SendAsync(request, cancellationToken); } catch (Exception exception) when (exception is LogbookException == false) { success = false; throw; } finally { watch.Stop(); var telemetry = new RequestTelemetry { HttpMethod = request.Method.Method, Duration = watch.Elapsed, Success = success, StartTime = startTime, Url = request.RequestUri }; AppInsights.Client.TrackRequest(telemetry); } }