public void Initialize(ITelemetry telemetry)
        {
            try
            {
                var context = this.httpContextAccessor.HttpContext;

                if (context == null)
                {
                    AspNetCoreEventSource.Instance.LogTelemetryInitializerBaseInitializeContextNull();
                    return;
                }

                if (context.RequestServices == null)
                {
                    AspNetCoreEventSource.Instance.LogTelemetryInitializerBaseInitializeRequestServicesNull();
                    return;
                }

                var request = context.RequestServices.GetService<RequestTelemetry>();

                if (request == null)
                {
                    AspNetCoreEventSource.Instance.LogTelemetryInitializerBaseInitializeRequestNull();
                    return;
                }

                this.OnInitializeTelemetry(context, request, telemetry);
            }
            catch (Exception exp)
            {
                AspNetCoreEventSource.Instance.LogTelemetryInitializerBaseInitializeException(exp.ToString());
                Debug.WriteLine(exp);
            }
        }
        /// <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;
                            }
                        }
                    }
                }
            }
        }
 public void Initialize(ITelemetry telemetry)
 {
     if (!string.IsNullOrEmpty(this.appVersion))
     {
         telemetry.Context.Component.Version = this.appVersion;
     }
 }
        public void Send(ITelemetry item)
        {
            var timer = TimerStrategy();

            if (timer == null || MessageBroker == null)
            {
                return;
            }

            if (item is DependencyTelemetry)
            {
                var dependency = item as DependencyTelemetry;
                var timelineMessage = new DependencyTelemetryTimelineMessage(dependency);
                timelineMessage.Offset = timer.Point().Offset.Subtract(dependency.Duration);
                MessageBroker.Publish(timelineMessage);
            }

            if (item is TraceTelemetry)
            {
                TraceTelemetry t = new TraceTelemetry();

                var model = new TraceMessage
                {
                    Category = "Application Insights",
                    Message = t.SeverityLevel == null ? t.Message : t.SeverityLevel + ": " + t.Message,
                    FromFirst = timer.Point().Offset,
                    FromLast = CalculateFromLast(timer),
                    IndentLevel = 0
                };

                MessageBroker.Publish(model);
            }

            messageBroker.Publish(item);
        }
 protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
 {
     if (string.IsNullOrEmpty(telemetry.Context.Operation.Id))
     {
         telemetry.Context.Operation.Id = requestTelemetry.Id;
     }
 }
        /// <summary>
        /// Initializes/Adds operation id to the existing telemetry item.
        /// </summary>
        /// <param name="telemetryItem">Target telemetry item to add operation id.</param>
        public void Initialize(ITelemetry telemetryItem)
        {
            var itemContext = telemetryItem.Context.Operation;

            if (string.IsNullOrEmpty(itemContext.ParentId) || string.IsNullOrEmpty(itemContext.Id) || string.IsNullOrEmpty(itemContext.Name))
            {
                var parentContext = AsyncLocalHelpers.GetCurrentOperationContext();
                if (parentContext != null)
                {
                    if (string.IsNullOrEmpty(itemContext.ParentId)
                        && !string.IsNullOrEmpty(parentContext.ParentOperationId))
                    {
                        itemContext.ParentId = parentContext.ParentOperationId;
                    }

                    if (string.IsNullOrEmpty(itemContext.Id)
                        && !string.IsNullOrEmpty(parentContext.RootOperationId))
                    {
                        itemContext.Id = parentContext.RootOperationId;
                    }

                    if (string.IsNullOrEmpty(itemContext.Name)
                        && !string.IsNullOrEmpty(parentContext.RootOperationName))
                    {
                        itemContext.Name = parentContext.RootOperationName;
                    }
                }
            }
        }
        /// <summary>
        /// Process a collected telemetry item.
        /// </summary>
        /// <param name="item">A collected Telemetry item.</param>
        public void Process(ITelemetry item)
        {
            if (this.SamplingPercentage < 100.0 - 1.0E-12)
            {
                // set sampling percentage on telemetry item, current codebase assumes it is the only one updating SamplingPercentage.
                var samplingSupportingTelemetry = item as ISupportSampling;

                if (samplingSupportingTelemetry != null)
                {
                    samplingSupportingTelemetry.SamplingPercentage = this.SamplingPercentage;
                }

                if (!this.IsSampledIn(item))
                {
                    if (TelemetryChannelEventSource.Log.IsVerboseEnabled)
                    {
                        TelemetryChannelEventSource.Log.ItemSampledOut(item.ToString());
                    }

                    return;
                }
            }

            this.Next.Process(item);
        }
 /// <summary>
 /// Populates <see cref="ITelemetry.Sequence"/> with unique ID and sequential number.
 /// </summary>
 public void Initialize(ITelemetry telemetry)
 {
     if (string.IsNullOrEmpty(telemetry.Sequence))
     {
         telemetry.Sequence = this.stablePrefix + Interlocked.Increment(ref this.currentNumber);
     }
 }
        /// <summary>
        /// Base implementation of the initialization method.
        /// </summary>
        /// <param name="telemetry">Telemetry item to initialize.</param>
        public void Initialize(ITelemetry telemetry)
        {
            try
            {
                var platformContext = this.ResolvePlatformContext();

                if (platformContext == null)
                {
                    WebEventSource.Log.WebTelemetryInitializerNotExecutedOnNullHttpContext();
                    return;
                }

                if (platformContext.GetRequest() == null)
                {
                    return;
                }

                var requestTelemetry = platformContext.ReadOrCreateRequestTelemetryPrivate();
                this.OnInitializeTelemetry(platformContext, requestTelemetry, telemetry);
            }
            catch (Exception exc)
            {
                WebEventSource.Log.WebTelemetryInitializerFailure(
                    this.GetType().FullName,
                    exc.ToInvariantString());
            }
        }
 /// <summary>
 /// Initializes the given <see cref="Microsoft.ApplicationInsights.Channel.ITelemetry"/>.
 /// </summary>
 public void Initialize(ITelemetry telemetry)
 {
     if (String.IsNullOrWhiteSpace(telemetry.Context.Component.Version))
     {
         telemetry.Context.Component.Version = _applicationVersion.Value;
     }
 }
        public void Initialize(ITelemetry telemetry)
        {
            try
            {
                var context = this.httpContextAccessor.HttpContext;

                if (context == null)
                {
                    //TODO: Diagnostics!
                    return;
                }

                if (context.RequestServices == null)
                {
                    //TODO: Diagnostics!
                    return;
                }

                var request = context.RequestServices.GetService<RequestTelemetry>();

                if (request == null)
                {
                    //TODO: Diagnostics!
                    return;
                }

                this.OnInitializeTelemetry(context, request, telemetry);
            }
            catch (Exception exp)
            {
                //TODO: Diagnostics!
                Debug.WriteLine(exp);
            }
        }
 /// <summary>
 /// Initializes the telemetry.
 /// </summary>
 public void Initialize(ITelemetry telemetry)
 {
     if (telemetry.Context.Cloud.RoleInstance == null)
     {
         telemetry.Context.Cloud.RoleInstance = _hostName.Value;
     }
 }
 /// <summary>
 /// Initializes the given <see cref="Microsoft.ApplicationInsights.Channel.ITelemetry"/>.
 /// </summary>
 /// <param name="telemetry"></param>
 public void Initialize(ITelemetry telemetry)
 {
     if (String.IsNullOrWhiteSpace(telemetry.Context.Session.Id))
     {
         telemetry.Context.Session.Id = _sessionId.Value;
     }
 }
        public void Initialize(ITelemetry telemetry)
        {
            var telemetryWithProperties = telemetry as ISupportProperties;

            if (telemetryWithProperties == null) return;

            // If already set, nothing to do.
            if (telemetryWithProperties.Properties.ContainsKey(Constants.ShellNameKey)) return;

            // Below algorithm copied from OrchardLog4netLogger.
            var ctx = HttpContext.Current;
            if (ctx == null)
                return;

            var runningShellTable = HostContainer.Resolve<IRunningShellTable>();
            if (runningShellTable == null)
                return;

            var shellSettings = runningShellTable.Match(new HttpContextWrapper(ctx));
            if (shellSettings == null)
                return;

            var orchardHost = HostContainer.Resolve<IOrchardHost>();
            if (orchardHost == null)
                return;

            var shellContext = orchardHost.GetShellContext(shellSettings);
            if (shellContext == null || shellContext.Settings == null)
                return;

            telemetryWithProperties.Properties[Constants.ShellNameKey] = shellContext.Settings.Name;
        }
        /// <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 Send(ITelemetry item)
 {
     lock ( lockobj )
     {
         items.Add(item);
     }
 }
 /// <summary>
 /// Initializes the given <see cref="Microsoft.ApplicationInsights.Channel.ITelemetry"/>.
 /// </summary>
 public void Initialize(ITelemetry telemetry)
 {
     if (String.IsNullOrWhiteSpace(telemetry.Context.Device.OperatingSystem))
     {
         telemetry.Context.Device.OperatingSystem = _osVersion.Value;
     }
 }
Exemplo n.º 18
0
 public Car(ITelemetry telemetry, int carIdx)
 {
     this.telemetry = telemetry;
     this.carIdx = carIdx;
     this.driver = telemetry.SessionData.DriverInfo.CompetingDrivers[carIdx];
     this.Details = new CarDetails(telemetry, carIdx);
 }
 /// <summary>
 /// Sets <see cref="ITelemetry.Timestamp"/> to <see cref="DateTimeOffset.Now"/>.
 /// </summary>
 public void Initialize(ITelemetry telemetry)
 {
     if (telemetry.Timestamp == default(DateTimeOffset))
     {
         telemetry.Timestamp = Clock.Instance.Time;
     }
 }
 public void Initialize(ITelemetry telemetry)
 {
     if (HttpContext.Current == null) return;
     var requestId = HttpContext.Current.Items[Constants.RequestIdKey];
     if (requestId == null || !string.IsNullOrEmpty(telemetry.Context.Operation.Id)) return;
     telemetry.Context.Operation.Id = requestId as string;
 }
 public UnhandledExceptionTelemetryModuleTest()
 {
     this.channel.OnSend = telemetry =>
     {
         sentTelemetry = telemetry;
         telemetrySent.Set();
     };
 }
 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;
     }
 }
 /// <summary>
 /// Implements the <see cref="ITelemetryProcessor.Process"/> method by invoking the <see cref="OnProcess"/> callback.
 /// </summary>
 public void Process(ITelemetry item)
 {
     this.OnProcess(item);
     if (this.Next != null)
     {
         this.Next.Process(item);
     }
 }
 public void Initialize(ITelemetry telemetry)
 {
     var owinRequestId = OwinRequestIdContext.Get();
     if (owinRequestId != null)
     {
         telemetry.Context.Operation.Id = owinRequestId;
     }
 }
 /// <summary>
 /// Implements the <see cref="ITelemetryProcessor.Initialize"/> method by invoking the process method
 /// </summary>
 public void Process(ITelemetry telemetry)
 {
     this.OnProcess(telemetry);
     if (this.next != null)
     {
         this.next.Process(telemetry);
     }
 }
 /// <summary>
 /// Initializes <see cref="ITelemetry" /> device context.
 /// </summary>
 /// <param name="telemetry">The telemetry to initialize.</param>
 public void Initialize(ITelemetry telemetry)
 {
     if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleInstance))
     {
         var name = LazyInitializer.EnsureInitialized(ref this.roleInstanceName, this.GetMachineName);
         telemetry.Context.Cloud.RoleInstance = name;
     }
 }
 /// <summary>
 /// Adds a telemetry property for the version of SDK.
 /// </summary>
 public void Initialize(ITelemetry telemetry)
 {
     var version = LazyInitializer.EnsureInitialized(ref this.sdkVersion, this.GetAssemblyVersion);
     if (string.IsNullOrEmpty(telemetry.Context.Internal.SdkVersion))
     {
         telemetry.Context.Internal.SdkVersion = version;
     }
 }
        public async Task InvokeTracksExceptionThrownByNextMiddlewareAsHandledByPlatform()
        {
            RequestDelegate nextMiddleware = httpContext => { throw new Exception(); };
            var middleware = new ExceptionTrackingMiddleware(nextMiddleware, CommonMocks.MockTelemetryClient(telemetry => this.sentTelemetry = telemetry));

            await Assert.ThrowsAnyAsync<Exception>(() => middleware.Invoke(null));

            Assert.Equal(ExceptionHandledAt.Platform, ((ExceptionTelemetry)sentTelemetry).HandledAt);
        }
        /// <summary>
        /// Implements the <see cref="ITelemetryChannel.Send"/> method by invoking the <see cref="OnSend"/> callback.
        /// </summary>
        public void Send(ITelemetry item)
        {
            if (this.ThrowError)
            {
                throw new Exception("test error");
            }

            this.OnSend(item);
        }
 static void PopulateCarIdxPitStopCount(ITelemetry last, ITelemetry telemetry, int[] carIdxPitStopCount)
 {
     for (var i = 0; i < telemetry.CarIdxTrackSurface.Length; i++)
         if (last.CarIdxTrackSurface[i] != TrackLocation.InPitStall && telemetry.CarIdxTrackSurface[i] == TrackLocation.InPitStall)
         {
             carIdxPitStopCount[i] += 1;
             TraceInfo.WriteLine("{0} Driver {1} has pitted {2} times", telemetry.SessionTimeSpan, telemetry.Cars[i].Details.UserName, carIdxPitStopCount[i]);
         }
 }
Exemplo n.º 31
0
 public void Initialize(ITelemetry telemetry)
 {
     telemetry.Context.Operation.Id = OperationID;
 }
Exemplo n.º 32
0
        public static Parser Create(
            IServiceCollection services,
            StartServer startServer = null,
            Jupyter jupyter         = null,
            StartStdIO startStdIO   = null,
            StartHttp startHttp     = null,
            Action onServerStarted  = null,
            ITelemetry telemetry    = null,
            IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null)
        {
            var operation = Log.OnEnterAndExit();

            if (services is null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            var disposeOnQuit = new CompositeDisposable();

            startServer ??= (startupOptions, invocationContext) =>
            {
                operation.Info("constructing webhost");
                var webHost = Program.ConstructWebHost(startupOptions);
                disposeOnQuit.Add(webHost);
                operation.Info("starting  kestrel server");
                webHost.Start();
                onServerStarted?.Invoke();
                webHost.WaitForShutdown();
                operation.Dispose();
            };

            jupyter ??= JupyterCommand.Do;

            startStdIO ??= StdIOCommand.Do;

            startHttp ??= HttpCommand.Do;

            // Setup first time use notice sentinel.
            firstTimeUseNoticeSentinel ??= new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion);

            var clearTextProperties = new[]
            {
                "frontend"
            };

            // Setup telemetry.
            telemetry ??= new Telemetry.Telemetry(
                VersionSensor.Version().AssemblyInformationalVersion,
                firstTimeUseNoticeSentinel,
                "dotnet/interactive/cli");

            var filter = new TelemetryFilter(
                Sha256Hasher.HashWithNormalizedCasing,
                clearTextProperties,
                (commandResult, directives, entryItems) =>
            {
                // add frontend
                var frontendTelemetryAdded = false;
                foreach (var directive in directives)
                {
                    switch (directive.Key)
                    {
                    case "vscode":
                    case "jupyter":
                    case "synapse":
                        frontendTelemetryAdded = true;
                        entryItems.Add(new KeyValuePair <string, string>("frontend", directive.Key));
                        break;
                    }
                }

                if (!frontendTelemetryAdded)
                {
                    if (commandResult.Command.Name == "jupyter")
                    {
                        entryItems.Add(new KeyValuePair <string, string>("frontend", "jupyter"));
                    }
                    else
                    {
                        entryItems.Add(new KeyValuePair <string, string>("frontend", "unknown"));
                    }
                }
            });

            var verboseOption = new Option <bool>(
                "--verbose",
                "Enable verbose logging to the console");

            var logPathOption = new Option <DirectoryInfo>(
                "--log-path",
                "Enable file logging to the specified directory");

            var pathOption = new Option <DirectoryInfo>(
                "--path",
                "Installs the kernelspecs to the specified directory")
                             .ExistingOnly();

            var defaultKernelOption = new Option <string>(
                "--default-kernel",
                description: "The default language for the kernel",
                getDefaultValue: () => "csharp").AddSuggestions("fsharp", "csharp", "pwsh");

            var rootCommand = DotnetInteractive();

            rootCommand.AddCommand(Jupyter());
            rootCommand.AddCommand(StdIO());
            rootCommand.AddCommand(HttpServer());

            return(new CommandLineBuilder(rootCommand)
                   .UseDefaults()
                   .UseMiddleware(async(context, next) =>
            {
                if (context.ParseResult.Errors.Count == 0)
                {
                    telemetry.SendFiltered(filter, context.ParseResult);
                }

                // If sentinel does not exist, print the welcome message showing the telemetry notification.
                if (!Telemetry.Telemetry.SkipFirstTimeExperience &&
                    !firstTimeUseNoticeSentinel.Exists())
                {
                    context.Console.Out.WriteLine();
                    context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage);

                    firstTimeUseNoticeSentinel.CreateIfNotExists();
                }

                await next(context);
            })
                   .Build());

            RootCommand DotnetInteractive()
            {
                var command = new RootCommand
                {
                    Name        = "dotnet-interactive",
                    Description = "Interactive programming for .NET."
                };

                command.AddGlobalOption(logPathOption);
                command.AddGlobalOption(verboseOption);

                return(command);
            }

            Command Jupyter()
            {
                var httpPortRangeOption = new Option <HttpPortRange>(
                    "--http-port-range",
                    parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result),
                    description: "Specifies the range of ports to use to enable HTTP services",
                    isDefault: true);

                var jupyterCommand = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel")
                {
                    defaultKernelOption,
                    httpPortRangeOption,
                    new Argument <FileInfo>
                    {
                        Name        = "connection-file",
                        Description = "The path to a connection file provided by Jupyter"
                    }.ExistingOnly()
                };

                jupyterCommand.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext, CancellationToken>(JupyterHandler);

                var installCommand = new Command("install", "Install the .NET kernel for Jupyter")
                {
                    httpPortRangeOption,
                    pathOption
                };

                installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext, HttpPortRange, DirectoryInfo>(InstallHandler);

                jupyterCommand.AddCommand(installCommand);

                return(jupyterCommand);

                async Task <int> JupyterHandler(StartupOptions startupOptions, JupyterOptions options, IConsole console, InvocationContext context, CancellationToken cancellationToken)
                {
                    var frontendEnvironment = new HtmlNotebookFrontendEnvironment();
                    var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions);

                    kernel.Add(
                        new JavaScriptKernel(),
                        new[] { "js" });

                    services.AddKernel(kernel);

                    await kernel.VisitSubkernelsAsync(async k =>
                    {
                        switch (k)
                        {
                        case DotNetKernel dk:
                            await dk.UseJupyterHelpersAsync();
                            break;
                        }
                    });

                    var clientSideKernelClient = new SignalRBackchannelKernelClient();

                    services.AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile))
                    .AddSingleton(clientSideKernelClient)
                    .AddSingleton(c =>
                    {
                        return(new JupyterRequestContextScheduler(delivery => c.GetRequiredService <JupyterRequestContextHandler>()
                                                                  .Handle(delivery)));
                    })
                    .AddSingleton(c => new JupyterRequestContextHandler(kernel))
                    .AddSingleton <IHostedService, Shell>()
                    .AddSingleton <IHostedService, Heartbeat>();
                    var result = await jupyter(startupOptions, console, startServer, context);

                    return(result);
                }

                Task <int> InstallHandler(IConsole console, InvocationContext context, HttpPortRange httpPortRange, DirectoryInfo path)
                {
                    var jupyterInstallCommand = new JupyterInstallCommand(console, new JupyterKernelSpecInstaller(console), httpPortRange, path);

                    return(jupyterInstallCommand.InvokeAsync());
                }
            }

            Command HttpServer()
            {
                var httpPortOption = new Option <HttpPort>(
                    "--http-port",
                    description: "Specifies the port on which to enable HTTP services",
                    parseArgument: result =>
                {
                    if (result.Tokens.Count == 0)
                    {
                        return(HttpPort.Auto);
                    }

                    var source = result.Tokens[0].Value;

                    if (source == "*")
                    {
                        return(HttpPort.Auto);
                    }

                    if (!int.TryParse(source, out var portNumber))
                    {
                        result.ErrorMessage = "Must specify a port number or *.";
                        return(null);
                    }

                    return(new HttpPort(portNumber));
                },
                    isDefault: true);

                var httpCommand = new Command("http", "Starts dotnet-interactive with kernel functionality exposed over http")
                {
                    defaultKernelOption,
                    httpPortOption
                };

                httpCommand.Handler = CommandHandler.Create <StartupOptions, KernelHttpOptions, IConsole, InvocationContext>(
                    (startupOptions, options, console, context) =>
                {
                    var frontendEnvironment = new BrowserFrontendEnvironment();
                    var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions);

                    kernel.Add(
                        new JavaScriptKernel(),
                        new[] { "js" });

                    services.AddKernel(kernel)
                    .AddSingleton(new SignalRBackchannelKernelClient());

                    onServerStarted ??= () =>
                    {
                        console.Out.WriteLine("Application started. Press Ctrl+C to shut down.");
                    };
                    return(startHttp(startupOptions, console, startServer, context));
                });

                return(httpCommand);
            }

            Command StdIO()
            {
                var httpPortRangeOption = new Option <HttpPortRange>(
                    "--http-port-range",
                    parseArgument: result => result.Tokens.Count == 0 ? HttpPortRange.Default : ParsePortRangeOption(result),
                    description: "Specifies the range of ports to use to enable HTTP services");

                var httpPortOption = new Option <HttpPort>(
                    "--http-port",
                    description: "Specifies the port on which to enable HTTP services",
                    parseArgument: result =>
                {
                    if (result.FindResultFor(httpPortRangeOption) is { } conflictingOption)
                    {
                        var parsed          = result.Parent as OptionResult;
                        result.ErrorMessage = $"Cannot specify both {conflictingOption.Token.Value} and {parsed.Token.Value} together";
                        return(null);
                    }

                    if (result.Tokens.Count == 0)
                    {
                        return(HttpPort.Auto);
                    }

                    var source = result.Tokens[0].Value;

                    if (source == "*")
                    {
                        return(HttpPort.Auto);
                    }

                    if (!int.TryParse(source, out var portNumber))
                    {
                        result.ErrorMessage = "Must specify a port number or *.";
                        return(null);
                    }

                    return(new HttpPort(portNumber));
                });

                var workingDirOption = new Option <DirectoryInfo>(
                    "--working-dir",
                    () => new DirectoryInfo(Environment.CurrentDirectory),
                    "Working directory to which to change after launching the kernel.");

                var stdIOCommand = new Command(
                    "stdio",
                    "Starts dotnet-interactive with kernel functionality exposed over standard I/O")
                {
                    defaultKernelOption,
                    httpPortRangeOption,
                    httpPortOption,
                    workingDirOption
                };

                stdIOCommand.Handler = CommandHandler.Create <StartupOptions, StdIOOptions, IConsole, InvocationContext>(
                    async(startupOptions, options, console, context) =>
                {
                    var isVsCode = context.ParseResult.Directives.Contains("vscode");
                    FrontendEnvironment frontendEnvironment = startupOptions.EnableHttpApi
                            ? new HtmlNotebookFrontendEnvironment()
                            : new BrowserFrontendEnvironment();

                    var kernel = CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions);

                    services.AddKernel(kernel);

                    kernel.UseQuitCommand();
                    var kernelServer = kernel.CreateKernelServer(startupOptions.WorkingDir);

                    if (startupOptions.EnableHttpApi)
                    {
                        var clientSideKernelClient = new SignalRBackchannelKernelClient();

                        if (isVsCode)
                        {
                            var frontEndKernel = kernelServer.GetFrontEndKernel("vscode");
                            kernel.Add(frontEndKernel);
                            await kernel.VisitSubkernelsAsync(async k =>
                            {
                                switch (k)
                                {
                                case DotNetKernel dk:
                                    await dk.UseVSCodeHelpersAsync(kernel);
                                    break;
                                }
                            });

                            services.AddSingleton(clientSideKernelClient);
                            ((HtmlNotebookFrontendEnvironment)frontendEnvironment).RequiresAutomaticBootstrapping =
                                false;
                            kernel.Add(
                                new JavaScriptKernel(clientSideKernelClient),
                                new[] { "js" });
                        }
                        else
                        {
                            services.AddSingleton(clientSideKernelClient);

                            kernel.Add(
                                new JavaScriptKernel(clientSideKernelClient),
                                new[] { "js" });
                        }

                        var _ = kernelServer.RunAsync();
                        onServerStarted ??= () =>
                        {
                            kernelServer.NotifyIsReady();
                        };
                        await startHttp(startupOptions, console, startServer, context);
                    }

                    kernel.Add(
                        new JavaScriptKernel(),
                        new[] { "js" });

                    await startStdIO(
                        startupOptions,
                        kernelServer,
                        console);
                });

                return(stdIOCommand);
            }
Exemplo n.º 33
0
 /// <summary>
 /// Sends Telemetry for the end of an XUnit Test work item.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='xHelixJobToken'>
 /// </param>
 /// <param name='id'>
 /// The id returned from the
 /// {M:Helix.LifeTime.Web.Controllers.Api_2018_03_14.TelemetryApiController.StartXUnitWorkItem(System.String,System.String)}
 /// call.
 /// </param>
 /// <param name='exitCode'>
 /// The exitCode of this work item.
 /// </param>
 /// <param name='resultsXmlUri'>
 /// The Uri where XUnit v2 format test results can be accessed.
 /// </param>
 /// <param name='logUri'>
 /// The Uri where logs for this test run may be accessed.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task FinishXUnitWorkItemAsync(this ITelemetry operations, string xHelixJobToken, string id, int exitCode, string resultsXmlUri, string logUri = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     (await operations.FinishXUnitWorkItemWithHttpMessagesAsync(xHelixJobToken, id, exitCode, resultsXmlUri, logUri, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
Exemplo n.º 34
0
        public static Parser Create(
            IServiceCollection services,
            StartServer startServer             = null,
            Jupyter jupyter                     = null,
            StartKernelServer startKernelServer = null,
            ITelemetry telemetry                = null,
            IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            startServer ??= (startupOptions, invocationContext) =>
            Program.ConstructWebHost(startupOptions).Run();

            jupyter ??= JupyterCommand.Do;

            startKernelServer ??= async(startupOptions, kernel, console) =>
            {
                var disposable = Program.StartToolLogging(startupOptions);

                if (kernel is KernelBase kernelBase)
                {
                    kernelBase.RegisterForDisposal(disposable);
                }

                var server = new StandardIOKernelServer(
                    kernel,
                    Console.In,
                    Console.Out);

                await server.Input.LastAsync();
            };

            // Setup first time use notice sentinel.
            firstTimeUseNoticeSentinel ??= new FirstTimeUseNoticeSentinel(VersionSensor.Version().AssemblyInformationalVersion);

            // Setup telemetry.
            telemetry ??= new Telemetry.Telemetry(
                VersionSensor.Version().AssemblyInformationalVersion,
                firstTimeUseNoticeSentinel);
            var filter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);

            var verboseOption = new Option <bool>(
                "--verbose",
                "Enable verbose logging to the console");

            var httpPortOption = new Option <int>(
                "--http-port",
                "Specifies the port on which to enable HTTP services");

            var httpPortRangeOption = new Option <PortRange>(
                "--http-port-range",
                parseArgument: result =>
            {
                if (result.Parent.Parent.Children.FirstOrDefault(c => c.Symbol == httpPortOption) is OptionResult conflictingOption)
                {
                    var parsed          = result.Parent as OptionResult;
                    result.ErrorMessage = $"Cannot specify both {conflictingOption.Token.Value} and {parsed.Token.Value} together";
                    return(null);
                }

                var source = result.Tokens[0].Value;

                if (string.IsNullOrWhiteSpace(source))
                {
                    result.ErrorMessage = "Must specify a port range";
                    return(null);
                }

                var parts = source.Split(new[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

                if (parts.Length != 2)
                {
                    result.ErrorMessage = "Must specify a port range";
                    return(null);
                }

                if (!int.TryParse(parts[0], out var start) || !int.TryParse(parts[1], out var end))
                {
                    result.ErrorMessage = "Must specify a port range as StartPort-EndPort";

                    return(null);
                }

                if (start > end)
                {
                    result.ErrorMessage = "Start port must be lower then end port";
                    return(null);
                }

                var pr = new PortRange(start, end);

                return(pr);
            },
                description: "Specifies the range of port to use to enable HTTP services");

            var logPathOption = new Option <DirectoryInfo>(
                "--log-path",
                "Enable file logging to the specified directory");

            var defaultKernelOption = new Option <string>(
                "--default-kernel",
                description: "The default language for the kernel",
                getDefaultValue: () => "csharp");

            var rootCommand = DotnetInteractive();

            rootCommand.AddCommand(Jupyter());
            rootCommand.AddCommand(KernelServer());
            rootCommand.AddCommand(HttpServer());

            return(new CommandLineBuilder(rootCommand)
                   .UseDefaults()
                   .UseMiddleware(async(context, next) =>
            {
                if (context.ParseResult.Errors.Count == 0)
                {
                    telemetry.SendFiltered(filter, context.ParseResult);
                }

                // If sentinel does not exist, print the welcome message showing the telemetry notification.
                if (!firstTimeUseNoticeSentinel.Exists() && !Telemetry.Telemetry.SkipFirstTimeExperience)
                {
                    context.Console.Out.WriteLine();
                    context.Console.Out.WriteLine(Telemetry.Telemetry.WelcomeMessage);

                    firstTimeUseNoticeSentinel.CreateIfNotExists();
                }

                await next(context);
            })
                   .Build());

            RootCommand DotnetInteractive()
            {
                var command = new RootCommand
                {
                    Name        = "dotnet-interactive",
                    Description = "Interactive programming for .NET."
                };

                command.AddOption(logPathOption);
                command.AddOption(verboseOption);
                command.AddOption(httpPortOption);

                return(command);
            }

            Command Jupyter()
            {
                var jupyterCommand = new Command("jupyter", "Starts dotnet-interactive as a Jupyter kernel")
                {
                    defaultKernelOption,
                    logPathOption,
                    verboseOption,
                    httpPortOption,
                    httpPortRangeOption,
                    new Argument <FileInfo>
                    {
                        Name = "connection-file"
                    }.ExistingOnly()
                };

                jupyterCommand.Handler = CommandHandler.Create <StartupOptions, JupyterOptions, IConsole, InvocationContext>(JupyterHandler);

                var installCommand = new Command("install", "Install the .NET kernel for Jupyter")
                {
                    logPathOption,
                    verboseOption,
                    httpPortRangeOption
                };

                installCommand.Handler = CommandHandler.Create <IConsole, InvocationContext, PortRange>(InstallHandler);

                jupyterCommand.AddCommand(installCommand);

                return(jupyterCommand);

                Task <int> JupyterHandler(StartupOptions startupOptions, JupyterOptions options, IConsole console, InvocationContext context)
                {
                    services.AddSingleton(c => ConnectionInformation.Load(options.ConnectionFile))
                    .AddSingleton(_ =>
                    {
                        var frontendEnvironment = new BrowserFrontendEnvironment
                        {
                            ApiUri = new Uri($"http://localhost:{startupOptions.HttpPort}")
                        };
                        return(frontendEnvironment);
                    })
                    .AddSingleton <FrontendEnvironment>(c => c.GetService <BrowserFrontendEnvironment>())
                    .AddSingleton(c =>
                    {
                        return(CommandScheduler.Create <JupyterRequestContext>(delivery => c.GetRequiredService <ICommandHandler <JupyterRequestContext> >()
                                                                               .Trace()
                                                                               .Handle(delivery)));
                    })
                    .AddSingleton(c =>
                    {
                        var frontendEnvironment = c.GetRequiredService <BrowserFrontendEnvironment>();

                        var kernel = CreateKernel(options.DefaultKernel,
                                                  frontendEnvironment,
                                                  startupOptions,
                                                  c.GetRequiredService <HttpProbingSettings>());
                        return(kernel);
                    })
                    .AddSingleton(c => new JupyterRequestContextHandler(
                                      c.GetRequiredService <IKernel>())
                                  .Trace())
                    .AddSingleton <IHostedService, Shell>()
                    .AddSingleton <IHostedService, Heartbeat>()
                    ;

                    return(jupyter(startupOptions, console, startServer, context));
                }

                Task <int> InstallHandler(IConsole console, InvocationContext context, PortRange httpPortRange) =>
                new JupyterInstallCommand(console, new JupyterKernelSpec(), httpPortRange).InvokeAsync();
            }

            Command HttpServer()
            {
                var startKernelHttpCommand = new Command("http", "Starts dotnet-interactive with kernel functionality exposed over http")
                {
                    defaultKernelOption,
                    httpPortOption,
                    logPathOption,
                    httpPortRangeOption
                };

                startKernelHttpCommand.Handler = CommandHandler.Create <StartupOptions, KernelHttpOptions, IConsole, InvocationContext>(
                    (startupOptions, options, console, context) =>
                {
                    var frontendEnvironment = new BrowserFrontendEnvironment();
                    services
                    .AddSingleton(_ => frontendEnvironment)
                    .AddSingleton(c => CreateKernel(options.DefaultKernel, frontendEnvironment, startupOptions, null));

                    return(jupyter(startupOptions, console, startServer, context));
                });

                return(startKernelHttpCommand);
            }

            Command KernelServer()
            {
                var startKernelServerCommand = new Command(
                    "stdio",
                    "Starts dotnet-interactive with kernel functionality exposed over standard I/O")
                {
                    defaultKernelOption,
                    logPathOption,
                };

                startKernelServerCommand.Handler = CommandHandler.Create <StartupOptions, KernelServerOptions, IConsole, InvocationContext>(
                    (startupOptions, options, console, context) => startKernelServer(
                        startupOptions,
                        CreateKernel(options.DefaultKernel,
                                     new BrowserFrontendEnvironment(), startupOptions, null), console));

                return(startKernelServerCommand);
            }
        }
Exemplo n.º 35
0
        protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
        {
            if (!string.IsNullOrEmpty(telemetry.Context.Location.Ip))
            {
                //already populated
                return;
            }

            if (string.IsNullOrEmpty(requestTelemetry.Context.Location.Ip))
            {
                string resultIp = null;
                foreach (var name in this.HeaderNames)
                {
                    var headerValue = platformContext.Request.Headers[name];
                    if (!string.IsNullOrEmpty(headerValue))
                    {
                        var ip = GetIpFromHeader(headerValue);
                        ip = CutPort(ip);
                        if (IsCorrectIpAddress(ip))
                        {
                            resultIp = ip;
                            break;
                        }
                    }
                }

                if (string.IsNullOrEmpty(resultIp))
                {
                    var connectionFeature = platformContext.Features.Get <IHttpConnectionFeature>();

                    if (connectionFeature != null)
                    {
                        resultIp = connectionFeature.RemoteIpAddress.ToString();
                    }
                }

                requestTelemetry.Context.Location.Ip = resultIp;
            }
            telemetry.Context.Location.Ip = requestTelemetry.Context.Location.Ip;
        }
Exemplo n.º 36
0
 public void Initialize(ITelemetry telemetry)
 {
     telemetry.Properties["customuserid"] = "your_id";
 }
Exemplo n.º 37
0
 public static void AddEmployerAccountId(this ITelemetry telemetry, long employerAccountId)
 {
     telemetry.AddProperty("Employer Account Id", employerAccountId.ToString());
 }
Exemplo n.º 38
0
 public static void TrackDependency(this ITelemetry telemetry, DependencyType dependencyType, string dependencyName, DateTimeOffset startTime,
                                    TimeSpan duration, bool success,
                                    Dictionary <string, string> properties = null)
 {
     telemetry.TrackDependency(dependencyType.ToString("G"), dependencyName, startTime, duration, success, properties);
 }
        public void Initialize(ITelemetry telemetry)
        {
            if (telemetry == null)
            {
                return;
            }

            var httpContext = _httpContextAccessor.HttpContext;
            var items       = httpContext?.Items;

            if (items != null)
            {
                if ((telemetry is RequestTelemetry || telemetry is EventTelemetry || telemetry is TraceTelemetry) &&
                    items.ContainsKey(BotActivityKey))
                {
                    if (items[BotActivityKey] is JObject body)
                    {
                        var userId = string.Empty;
                        var from   = body["from"];
                        if (!string.IsNullOrWhiteSpace(from.ToString()))
                        {
                            userId = (string)from["id"];
                        }

                        var channelId = (string)body["channelId"];

                        var conversationId = string.Empty;
                        var conversation   = body["conversation"];
                        if (!string.IsNullOrWhiteSpace(conversation.ToString()))
                        {
                            conversationId = (string)conversation["id"];
                        }

                        // Set the user id on the Application Insights telemetry item.
                        telemetry.Context.User.Id = channelId + userId;

                        // Set the session id on the Application Insights telemetry item.
                        telemetry.Context.Session.Id = conversationId;

                        var telemetryProperties = ((ISupportProperties)telemetry).Properties;

                        // Set the activity id https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#id
                        if (!telemetryProperties.ContainsKey("activityId"))
                        {
                            telemetryProperties.Add("activityId", (string)body["id"]);
                        }

                        // Set the channel id https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#channel-id
                        if (!telemetryProperties.ContainsKey("channelId"))
                        {
                            telemetryProperties.Add("channelId", (string)channelId);
                        }

                        // Set the activity type https://github.com/Microsoft/botframework-obi/blob/master/botframework-activity/botframework-activity.md#type
                        if (!telemetryProperties.ContainsKey("activityType"))
                        {
                            telemetryProperties.Add("activityType", (string)body["type"]);
                        }
                    }
                }
            }
        }
 public JobsService(IPaymentLogger logger, ILifetimeScope lifetimeScope, ActorService actorService, ActorId actorId, ITelemetry telemetry)
     : base(actorService, actorId)
 {
     this.logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     this.lifetimeScope = lifetimeScope ?? throw new ArgumentNullException(nameof(lifetimeScope));
     this.telemetry     = telemetry ?? throw new ArgumentNullException(nameof(telemetry));
 }
        private static void SetCommonTelemetryDocumentData(ITelemetryDocument telemetryDocument, ITelemetry telemetry)
        {
            if (telemetry.Context == null)
            {
                return;
            }

            telemetryDocument.OperationName     = TruncateValue(telemetry.Context.Operation?.Name);
            telemetryDocument.InternalNodeName  = TruncateValue(telemetry.Context.GetInternalContext()?.NodeName);
            telemetryDocument.CloudRoleName     = TruncateValue(telemetry.Context.Cloud?.RoleName);
            telemetryDocument.CloudRoleInstance = TruncateValue(telemetry.Context.Cloud?.RoleInstance);
        }
Exemplo n.º 42
0
        internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null)
        {
            // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA.

            var success = true;
            var command = string.Empty;
            var lastArg = 0;
            TopLevelCommandParserResult topLevelCommandParserResult = TopLevelCommandParserResult.Empty;

            using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
                       new FirstTimeUseNoticeSentinel())
            {
                IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
                IAspNetCertificateSentinel  aspNetCertificateSentinel  = new AspNetCertificateSentinel();
                IFileSentinel toolPathSentinel = new FileSentinel(
                    new FilePath(
                        Path.Combine(
                            CliFolderPathCalculator.DotnetUserProfileFolderPath,
                            ToolPathSentinelFileName)));

                for (; lastArg < args.Length; lastArg++)
                {
                    if (IsArg(args[lastArg], "d", "diagnostics"))
                    {
                        Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString);
                        CommandContext.SetVerbose(true);
                    }
                    else if (IsArg(args[lastArg], "version"))
                    {
                        PrintVersion();
                        return(0);
                    }
                    else if (IsArg(args[lastArg], "info"))
                    {
                        PrintInfo();
                        return(0);
                    }
                    else if (IsArg(args[lastArg], "h", "help") ||
                             args[lastArg] == "-?" ||
                             args[lastArg] == "/?")
                    {
                        HelpCommand.PrintHelp();
                        return(0);
                    }
                    else if (args[lastArg].StartsWith("-", StringComparison.OrdinalIgnoreCase))
                    {
                        Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}");
                        success = false;
                    }
                    else
                    {
                        // It's the command, and we're done!
                        command = args[lastArg];
                        if (string.IsNullOrEmpty(command))
                        {
                            command = "help";
                        }

                        var environmentProvider = new EnvironmentProvider();

                        bool generateAspNetCertificate =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_GENERATE_ASPNET_CERTIFICATE", true);
                        bool skipFirstRunExperience =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", false);
                        bool telemetryOptout =
                            environmentProvider.GetEnvironmentVariableAsBool("DOTNET_CLI_TELEMETRY_OPTOUT", false);

                        ReportDotnetHomeUsage(environmentProvider);

                        topLevelCommandParserResult = new TopLevelCommandParserResult(command);
                        var hasSuperUserAccess = false;
                        if (IsDotnetBeingInvokedFromNativeInstaller(topLevelCommandParserResult))
                        {
                            aspNetCertificateSentinel  = new NoOpAspNetCertificateSentinel();
                            firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel();
                            toolPathSentinel           = new NoOpFileSentinel(exists: false);
                            hasSuperUserAccess         = true;

                            // When running through a native installer, we want the cache expansion to happen, so
                            // we need to override this.
                            skipFirstRunExperience = false;
                        }

                        var dotnetFirstRunConfiguration = new DotnetFirstRunConfiguration(
                            generateAspNetCertificate: generateAspNetCertificate,
                            skipFirstRunExperience: skipFirstRunExperience,
                            telemetryOptout: telemetryOptout);

                        ConfigureDotNetForFirstTimeUse(
                            firstTimeUseNoticeSentinel,
                            aspNetCertificateSentinel,
                            toolPathSentinel,
                            hasSuperUserAccess,
                            dotnetFirstRunConfiguration,
                            environmentProvider);

                        break;
                    }
                }
                if (!success)
                {
                    HelpCommand.PrintHelp();
                    return(1);
                }

                if (telemetryClient == null)
                {
                    telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel);
                }
                TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent);
                TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing);
            }

            IEnumerable <string> appArgs =
                (lastArg + 1) >= args.Length
                ? Enumerable.Empty <string>()
                : args.Skip(lastArg + 1).ToArray();

            if (CommandContext.IsVerbose())
            {
                Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}");
            }

            TelemetryEventEntry.SendFiltered(topLevelCommandParserResult);

            int exitCode;

            if (BuiltInCommandsCatalog.Commands.TryGetValue(topLevelCommandParserResult.Command, out var builtIn))
            {
                var parseResult = Parser.Instance.ParseFrom($"dotnet {topLevelCommandParserResult.Command}", appArgs.ToArray());
                if (!parseResult.Errors.Any())
                {
                    TelemetryEventEntry.SendFiltered(parseResult);
                }

                exitCode = builtIn.Command(appArgs.ToArray());
            }
            else
            {
                CommandResult result = CommandFactoryUsingResolver.Create(
                    "dotnet-" + topLevelCommandParserResult.Command,
                    appArgs,
                    FrameworkConstants.CommonFrameworks.NetStandardApp15)
                                       .Execute();
                exitCode = result.ExitCode;
            }

            telemetryClient.Flush();
            return(exitCode);
        }
Exemplo n.º 43
0
 /// <summary>
 /// Processes telemetry item.
 /// </summary>
 /// <param name="item">Telemetry item to process.</param>
 public void Process(ITelemetry item)
 {
     this.samplingProcessor.Process(item);
 }
Exemplo n.º 44
0
 /// <summary>
 /// Method that subclasses can override to augment
 /// a telemetry item
 /// </summary>
 /// <param name="telemetry">The telemetry item</param>
 /// <param name="operation">The operation context</param>
 protected abstract void OnInitialize(ITelemetry telemetry, IOperationContext operation);
Exemplo n.º 45
0
 public MeditationTimer(string persistentObjectId, IWurmApi wurmApi, ILogger logger, ISoundManager soundManager,
                        ITrayPopups trayPopups, ITelemetry telemetry)
     : base(persistentObjectId, trayPopups, logger, wurmApi, soundManager, telemetry)
 {
     cooldownUpdateOperation = new TriggerableAsyncOperation(UpdateMeditationCooldown);
 }
 public void Send(ITelemetry item)
 {
     this.OnSend(item);
 }
        /// <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 (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
                var request = platformContext.GetRequest();

                var runIdHeader    = request.UnvalidatedGetHeader(TestRunHeader);
                var locationHeader = request.UnvalidatedGetHeader(TestLocationHeader);

                if (!string.IsNullOrEmpty(runIdHeader) &&
                    !string.IsNullOrEmpty(locationHeader))
                {
                    telemetry.Context.Operation.SyntheticSource = GsmSource;

                    // User id will be Pop location name and RunId (We cannot use just location because of sampling)
                    telemetry.Context.User.Id    = locationHeader + "_" + runIdHeader;
                    telemetry.Context.Session.Id = runIdHeader;
                }
            }
        }
Exemplo n.º 48
0
 public void Initialize(ITelemetry telemetry)
 {
     telemetry.Context.Component.Version = Program.AssemblyInformationalVersion;
 }
Exemplo n.º 49
0
 protected void InitializeTelemetry(ITelemetry telemetry)
 {
     this.Telemetry = telemetry;
 }
Exemplo n.º 50
0
        public void Initialize(ITelemetry telemetry)
        {
            ISupportProperties propTelemetry = (ISupportProperties)telemetry;

            propTelemetry.Properties.TryAdd("Test", "TestValue");
        }
Exemplo n.º 51
0
 protected override void OnInitializeTelemetry(HttpContext platformContext, RequestTelemetry requestTelemetry, ITelemetry telemetry)
 {
     if (string.IsNullOrEmpty(telemetry.Context.Operation.Id))
     {
         telemetry.Context.Operation.Id = requestTelemetry.Id;
     }
 }
        private void ProcessTelemetry(ITelemetry telemetry)
        {
            // only process items that are going to the instrumentation key that our module is initialized with
            if (string.IsNullOrWhiteSpace(this.config?.InstrumentationKey) ||
                !string.Equals(telemetry?.Context?.InstrumentationKey, this.config.InstrumentationKey, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var telemetryAsRequest    = telemetry as RequestTelemetry;
            var telemetryAsDependency = telemetry as DependencyTelemetry;
            var telemetryAsException  = telemetry as ExceptionTelemetry;
            var telemetryAsEvent      = telemetry as EventTelemetry;
            var telemetryAsTrace      = telemetry as TraceTelemetry;

            // update aggregates
            bool?originalRequestTelemetrySuccessValue = null;

            if (telemetryAsRequest != null)
            {
                // special treatment for RequestTelemetry.Success
                originalRequestTelemetrySuccessValue = telemetryAsRequest.Success;
                telemetryAsRequest.Success           = IsRequestSuccessful(telemetryAsRequest);

                this.UpdateRequestAggregates(telemetryAsRequest);
            }
            else if (telemetryAsDependency != null)
            {
                this.UpdateDependencyAggregates(telemetryAsDependency);
            }
            else if (telemetryAsException != null)
            {
                this.UpdateExceptionAggregates();
            }

            // get a local reference, the accumulator might get swapped out at any time
            // in case we continue to process this configuration once the accumulator is out, increase the reference count so that this accumulator is not sent out before we're done
            CollectionConfigurationAccumulator configurationAccumulatorLocal =
                this.dataAccumulatorManager.CurrentDataAccumulator.CollectionConfigurationAccumulator;

            // if the accumulator is swapped out and a sample is created and sent out - all while between these two lines, this telemetry item gets lost
            // however, that is not likely to happen
            configurationAccumulatorLocal.AddRef();

            try
            {
                // collect full telemetry items
                if (!this.disableFullTelemetryItems)
                {
                    ITelemetryDocument           telemetryDocument = null;
                    IEnumerable <DocumentStream> documentStreams   = configurationAccumulatorLocal.CollectionConfiguration.DocumentStreams;

                    // !!! report runtime errors for filter groups?
                    CollectionConfigurationError[] groupErrors;

                    if (telemetryAsRequest != null)
                    {
                        telemetryDocument = this.CreateTelemetryDocument(
                            telemetryAsRequest,
                            documentStreams,
                            documentStream => documentStream.RequestQuotaTracker,
                            documentStream => documentStream.CheckFilters(telemetryAsRequest, out groupErrors),
                            this.ConvertRequestToTelemetryDocument);
                    }
                    else if (telemetryAsDependency != null)
                    {
                        telemetryDocument = this.CreateTelemetryDocument(
                            telemetryAsDependency,
                            documentStreams,
                            documentStream => documentStream.DependencyQuotaTracker,
                            documentStream => documentStream.CheckFilters(telemetryAsDependency, out groupErrors),
                            ConvertDependencyToTelemetryDocument);
                    }
                    else if (telemetryAsException != null)
                    {
                        telemetryDocument = this.CreateTelemetryDocument(
                            telemetryAsException,
                            documentStreams,
                            documentStream => documentStream.ExceptionQuotaTracker,
                            documentStream => documentStream.CheckFilters(telemetryAsException, out groupErrors),
                            ConvertExceptionToTelemetryDocument);
                    }
                    else if (telemetryAsEvent != null)
                    {
                        telemetryDocument = this.CreateTelemetryDocument(
                            telemetryAsEvent,
                            documentStreams,
                            documentStream => documentStream.EventQuotaTracker,
                            documentStream => documentStream.CheckFilters(telemetryAsEvent, out groupErrors),
                            ConvertEventToTelemetryDocument);
                    }
                    else if (telemetryAsTrace != null)
                    {
                        telemetryDocument = this.CreateTelemetryDocument(
                            telemetryAsTrace,
                            documentStreams,
                            documentStream => documentStream.TraceQuotaTracker,
                            documentStream => documentStream.CheckFilters(telemetryAsTrace, out groupErrors),
                            ConvertTraceToTelemetryDocument);
                    }

                    if (telemetryDocument != null)
                    {
                        this.dataAccumulatorManager.CurrentDataAccumulator.TelemetryDocuments.Push(telemetryDocument);
                    }

                    this.dataAccumulatorManager.CurrentDataAccumulator.GlobalDocumentQuotaReached = this.globalQuotaTracker.QuotaExhausted;
                }

                // collect calculated metrics
                CollectionConfigurationError[] filteringErrors;
                string projectionError = null;

                if (telemetryAsRequest != null)
                {
                    QuickPulseTelemetryProcessor.ProcessMetrics(
                        configurationAccumulatorLocal,
                        configurationAccumulatorLocal.CollectionConfiguration.RequestMetrics,
                        telemetryAsRequest,
                        out filteringErrors,
                        ref projectionError);
                }
                else if (telemetryAsDependency != null)
                {
                    QuickPulseTelemetryProcessor.ProcessMetrics(
                        configurationAccumulatorLocal,
                        configurationAccumulatorLocal.CollectionConfiguration.DependencyMetrics,
                        telemetryAsDependency,
                        out filteringErrors,
                        ref projectionError);
                }
                else if (telemetryAsException != null)
                {
                    QuickPulseTelemetryProcessor.ProcessMetrics(
                        configurationAccumulatorLocal,
                        configurationAccumulatorLocal.CollectionConfiguration.ExceptionMetrics,
                        telemetryAsException,
                        out filteringErrors,
                        ref projectionError);
                }
                else if (telemetryAsEvent != null)
                {
                    QuickPulseTelemetryProcessor.ProcessMetrics(
                        configurationAccumulatorLocal,
                        configurationAccumulatorLocal.CollectionConfiguration.EventMetrics,
                        telemetryAsEvent,
                        out filteringErrors,
                        ref projectionError);
                }
                else if (telemetryAsTrace != null)
                {
                    QuickPulseTelemetryProcessor.ProcessMetrics(
                        configurationAccumulatorLocal,
                        configurationAccumulatorLocal.CollectionConfiguration.TraceMetrics,
                        telemetryAsTrace,
                        out filteringErrors,
                        ref projectionError);
                }

                // !!! report errors from string[] errors; and string projectionError;
            }
            finally
            {
                // special treatment for RequestTelemetry.Success - restore the value
                if (telemetryAsRequest != null)
                {
                    telemetryAsRequest.Success = originalRequestTelemetrySuccessValue;
                }

                configurationAccumulatorLocal.Release();
            }
        }
Exemplo n.º 53
0
 /// <summary>
 /// Initializes the telemetry context for a telemetry item
 /// </summary>
 /// <param name="telemetry">The telemetry item to augment</param>
 /// <param name="context">The operation context</param>
 /// <remarks>
 /// This variant is used to support easier testability by providing
 /// the operation context explicitly
 /// </remarks>
 public void Initialize(ITelemetry telemetry, IOperationContext context)
 {
     OnInitialize(telemetry, context);
 }
Exemplo n.º 54
0
 public ConnectCommand(IPreferences preferences, ITelemetry telemetry)
 {
     _preferences = preferences;
     _telemetry   = telemetry;
 }
Exemplo n.º 55
0
 /// <summary>
 /// Sends Telemetry for the end of a build work item.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='xHelixJobToken'>
 /// </param>
 /// <param name='id'>
 /// The id returned from the
 /// {M:Helix.LifeTime.Web.Controllers.Api_2018_03_14.TelemetryApiController.StartBuildWorkItem(System.String,System.Uri)}
 /// call.
 /// </param>
 /// <param name='errorCount'>
 /// The number of errors reported for this build.
 /// </param>
 /// <param name='warningCount'>
 /// The number of warnings reported for this build.
 /// </param>
 /// <param name='logUri'>
 /// The Uri where logs for this build may be accessed.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task FinishBuildWorkItemAsync(this ITelemetry operations, string xHelixJobToken, string id, int errorCount, int warningCount, string logUri = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     (await operations.FinishBuildWorkItemWithHttpMessagesAsync(xHelixJobToken, id, errorCount, warningCount, logUri, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
Exemplo n.º 56
0
 /// <summary>
 /// Sends Telemetry for work item logs.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='xHelixJobToken'>
 /// </param>
 /// <param name='id'>
 /// The id returned from the
 /// {M:Helix.LifeTime.Web.Controllers.Api_2018_03_14.TelemetryApiController.StartBuildWorkItem(System.String,System.Uri)}
 /// or
 /// {M:Helix.LifeTime.Web.Controllers.Api_2018_03_14.TelemetryApiController.StartXUnitWorkItem(System.String,System.String)}
 /// call.
 /// </param>
 /// <param name='logUri'>
 /// The Uri where logs may be accessed.
 /// </param>
 /// <param name='format'>
 /// The format that this log is in.
 /// </param>
 /// <param name='module'>
 /// The module/dll where these logs came from.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task LogAsync(this ITelemetry operations, string xHelixJobToken, string id, string logUri, string format = default(string), string module = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     (await operations.LogWithHttpMessagesAsync(xHelixJobToken, id, logUri, format, module, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
Exemplo n.º 57
0
 public void Initialize(ITelemetry telemetry)
 {
     telemetry.Context.Cloud.RoleName     = _roleName;
     telemetry.Context.Cloud.RoleInstance = Environment.MachineName;
     // @see: TelemetryConfigurationHelper
 }
Exemplo n.º 58
0
 /// <summary>
 /// Sends Telemetry for an error from a work item.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='xHelixJobToken'>
 /// </param>
 /// <param name='id'>
 /// The id returned from the
 /// {M:Helix.LifeTime.Web.Controllers.Api_2018_03_14.TelemetryApiController.StartBuildWorkItem(System.String,System.Uri)}
 /// or
 /// {M:Helix.LifeTime.Web.Controllers.Api_2018_03_14.TelemetryApiController.StartXUnitWorkItem(System.String,System.String)}
 /// call.
 /// </param>
 /// <param name='eid'>
 /// The id of the error.
 /// </param>
 /// <param name='message'>
 /// The error message.
 /// </param>
 /// <param name='logUri'>
 /// The Uri where error logs may be accessed.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task ErrorAsync(this ITelemetry operations, string xHelixJobToken, string id, string eid, string message = default(string), string logUri = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     (await operations.ErrorWithHttpMessagesAsync(xHelixJobToken, id, eid, message, logUri, null, cancellationToken).ConfigureAwait(false)).Dispose();
 }
Exemplo n.º 59
0
 public void Initialize(ITelemetry telemetry)
 {
     telemetry.Context.GlobalProperties["WPF version"] = _wpfVersion;
     telemetry.Context.Component.Version = _appVersion;
 }
 public SupplierService(IRepository repository, ILogger logger, ICache cache, ITelemetry telemetry) : base(repository, logger, cache, telemetry)
 {
 }