Exemplo n.º 1
0
        public void DotnetNugetCommandFirstArgumentShouldBeSentToTelemetry()
        {
            const string argumentToSend = "push";

            string[] args = { "nuget", argumentToSend, "path" };

            Cli.Program.ProcessArgs(args);
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" &&
                     e.Properties.ContainsKey("argument") &&
                     e.Properties["argument"] == Sha256Hasher.Hash(argumentToSend.ToUpper()) &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("NUGET"));
        }
Exemplo n.º 2
0
        public void DotnetBuildAndPublishCommandOpinionsShouldBeSentToTelemetry()
        {
            const string optionKey         = "configuration";
            const string optionValueToSend = "Debug";

            string[] args = { "build", "--" + optionKey, optionValueToSend };
            Cli.Program.ProcessArgs(args);
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" &&
                     e.Properties.ContainsKey(optionKey) &&
                     e.Properties[optionKey] == Sha256Hasher.Hash(optionValueToSend.ToUpper()) &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("BUILD"));
        }
Exemplo n.º 3
0
        public void DotnetPublishCommandRuntimeOpinionsShouldBeSentToTelemetry()
        {
            const string optionKey         = "runtime";
            const string optionValueToSend = "win10-x64";

            string[] args = { "publish", "--" + optionKey, optionValueToSend };
            Cli.Program.ProcessArgs(args);
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" &&
                     e.Properties.ContainsKey(optionKey) &&
                     e.Properties[optionKey] == Sha256Hasher.Hash(optionValueToSend.ToUpper()) &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("PUBLISH"));
        }
Exemplo n.º 4
0
        public void AnyDotnetCommandVerbosityOpinionShouldBeSentToTelemetry()
        {
            const string optionKey         = "verbosity";
            const string optionValueToSend = "minimal";

            string[] args = { "restore", "--" + optionKey, optionValueToSend };
            Cli.Program.ProcessArgs(args);
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" &&
                     e.Properties.ContainsKey(optionKey) &&
                     e.Properties[optionKey] == Sha256Hasher.Hash(optionValueToSend.ToUpper()) &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("RESTORE"));
        }
        public void TopLevelCommandNameShouldBeSentToTelemetryWithZeroPerformanceData()
        {
            var parseResult = Parser.Instance.Parse(new List <string>()
            {
                "build"
            });

            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult, new Dictionary <string, double>()
            {
                { "Startup Time", 0 }
            }));
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "toplevelparser/command" &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("BUILD") &&
                                                       e.Measurement == null);
        }
        public void SubLevelCommandNameShouldBeSentToTelemetryWithoutPerformanceData()
        {
            var parseResult = Parser.Instance.Parse(new List <string>()
            {
                "new", "console"
            });

            TelemetryEventEntry.SendFiltered(parseResult);
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" &&
                     e.Properties.ContainsKey("argument") &&
                     e.Properties["argument"] == Sha256Hasher.Hash("CONSOLE") &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("NEW") &&
                     e.Measurement == null);
        }
Exemplo n.º 7
0
        public void DotnetNewCommandFirstArgumentShouldBeSentToTelemetryWithPerformanceData()
        {
            const string argumentToSend = "console";

            string[] args = { "new", argumentToSend };
            Cli.Program.ProcessArgs(args, new TimeSpan(23456));
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" &&
                     e.Properties.ContainsKey("argument") &&
                     e.Properties["argument"] == Sha256Hasher.Hash(argumentToSend.ToUpper()) &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("NEW") &&
                     e.Measurement.ContainsKey("Startup Time") &&
                     e.Measurement["Startup Time"] == 2.3456 &&
                     e.Measurement.ContainsKey("Parse Time") &&
                     e.Measurement["Parse Time"] > 0);
        }
Exemplo n.º 8
0
        public void DotnetRunCleanTestCommandOpinionsShouldBeSentToTelemetryWhenThereIsMultipleOption()
        {
            string[] args = { "clean", "--configuration", "Debug", "--framework", "netcoreapp1.0" };
            Cli.Program.ProcessArgs(args);
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" && e.Properties.ContainsKey("configuration") &&
                     e.Properties["configuration"] == Sha256Hasher.Hash("DEBUG") &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("CLEAN"));

            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" && e.Properties.ContainsKey("framework") &&
                     e.Properties["framework"] == Sha256Hasher.Hash("NETCOREAPP1.0") &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("CLEAN"));
        }
Exemplo n.º 9
0
        public async Task ExecuteAsync_WithUnknownHeader_SendsTelemetryWithHashedHeaderName()
        {
            ArrangeInputs(parseResultSections: "set header name value",
                          out MockedShellState shellState,
                          out HttpState httpState,
                          out ICoreParseResult parseResult);

            TelemetryCollector telemetry = new TelemetryCollector();

            SetHeaderCommand setHeaderCommand = new SetHeaderCommand(telemetry);
            await setHeaderCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

            Assert.Single(telemetry.Telemetry);
            TelemetryCollector.CollectedTelemetry collectedTelemetry = telemetry.Telemetry[0];
            Assert.Equal("SetHeader", collectedTelemetry.EventName);
            Assert.Equal(Sha256Hasher.Hash("name"), collectedTelemetry.Properties["HeaderName"]);
            Assert.Equal("False", collectedTelemetry.Properties["IsValueEmpty"]);
        }
Exemplo n.º 10
0
        public void DotnetBuildAndPublishCommandOpinionsShouldBeSentToTelemetryWhenThereIsMultipleOption()
        {
            string[] args = { "build", "--configuration", "Debug", "--runtime", "osx.10.11-x64" };
            Cli.Program.ProcessArgs(args);
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" && e.Properties.ContainsKey("configuration") &&
                     e.Properties["configuration"] == Sha256Hasher.Hash("DEBUG") &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("BUILD"));

            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" && e.Properties.ContainsKey("runtime") &&
                     e.Properties["runtime"] == Sha256Hasher.Hash("OSX.10.11-X64") &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("BUILD"));
        }
Exemplo n.º 11
0
        public void AnyDotnetCommandVerbosityOpinionShouldBeSentToTelemetryWithPerformanceData()
        {
            const string optionKey         = "verbosity";
            const string optionValueToSend = "minimal";

            string[] args = { "restore", "--" + optionKey, optionValueToSend };
            Cli.Program.ProcessArgs(args, new TimeSpan(34567));
            _fakeTelemetry
            .LogEntries.Should()
            .Contain(e => e.EventName == "sublevelparser/command" &&
                     e.Properties.ContainsKey(optionKey) &&
                     e.Properties[optionKey] == Sha256Hasher.Hash(optionValueToSend.ToUpper()) &&
                     e.Properties.ContainsKey("verb") &&
                     e.Properties["verb"] == Sha256Hasher.Hash("RESTORE") &&
                     e.Measurement.ContainsKey("Startup Time") &&
                     e.Measurement["Startup Time"] == 3.4567 &&
                     e.Measurement.ContainsKey("Parse Time") &&
                     e.Measurement["Parse Time"] > 0);
        }
Exemplo n.º 12
0
        public void SubLevelCommandNameShouldBeSentToTelemetryWithPerformanceData()
        {
            var parseResult = Parser.Instance.Parse(new List <string>()
            {
                "new", "console"
            });

            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult, new Dictionary <string, double>()
            {
                { "Startup Time", 34567 }
            }));
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "sublevelparser/command" &&
                                                       e.Properties.ContainsKey("argument") &&
                                                       e.Properties["argument"] == Sha256Hasher.Hash("CONSOLE") &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("NEW") &&
                                                       e.Measurement.ContainsKey("Startup Time") &&
                                                       e.Measurement["Startup Time"] == 34567);
        }
Exemplo n.º 13
0
        public void WhenCalledWithMissingArgumentWorkloadSubLevelCommandNameAndArgumentShouldBeSentToTelemetry()
        {
            var parseResult =
                Parser.Instance.Parse(new List <string>()
            {
                "-d", "workload", "install"
            });

            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult,
                                                          new Dictionary <string, double>()
            {
                { "Startup Time", 0 }, { "Parse Time", 23456 }
            }));
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "sublevelparser/command" &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("WORKLOAD") &&
                                                       e.Properties["subcommand"] ==
                                                       Sha256Hasher.Hash("INSTALL"));
        }
Exemplo n.º 14
0
        internal static void FormatAndSend(ITelemetry telemetry, TelemetryEventArgs args)
        {
            if (args.EventName == TargetFrameworkTelemetryEventName)
            {
                var newEventName = $"msbuild/{TargetFrameworkTelemetryEventName}";
                Dictionary <string, string> maskedProperties = new Dictionary <string, string>();
                if (args.Properties.TryGetValue(TargetFrameworkVersionTelemetryPropertyKey, out string targetFrameworkVersionValue))
                {
                    maskedProperties.Add(TargetFrameworkVersionTelemetryPropertyKey, Sha256Hasher.HashWithNormalizedCasing(targetFrameworkVersionValue));
                }

                telemetry.TrackEvent(newEventName, maskedProperties, measurements: null);
            }

            if (args.EventName == SdkTaskBaseCatchExceptionTelemetryEventName)
            {
                telemetry.TrackEvent(args.EventName, args.Properties, measurements: null);
            }
        }
Exemplo n.º 15
0
        public async Task ExecuteAsync_WithGetAndUnknownName_SendsTelemetryWithHashedName()
        {
            Arrange("pref set preferenceName value",
                    out HttpState httpState,
                    out MockedShellState shellState,
                    out ICoreParseResult parseResult,
                    out UserFolderPreferences preferences);

            TelemetryCollector telemetry = new TelemetryCollector();

            PrefCommand command = new PrefCommand(preferences, telemetry);

            await command.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

            Assert.Single(telemetry.Telemetry);
            TelemetryCollector.CollectedTelemetry collectedTelemetry = telemetry.Telemetry[0];
            Assert.Equal("Preference", collectedTelemetry.EventName);
            Assert.Equal("Set", collectedTelemetry.Properties["GetOrSet"]);
            Assert.Equal(Sha256Hasher.Hash("preferenceName"), collectedTelemetry.Properties["PreferenceName"]);
        }
Exemplo n.º 16
0
        public void ItMasksTargetFrameworkEventname()
        {
            var fakeTelemetry      = new FakeTelemetry();
            var telemetryEventArgs = new TelemetryEventArgs
            {
                EventName  = "targetframeworkeval",
                Properties = new Dictionary <string, string>
                {
                    { "TargetFrameworkVersion", ".NETStandard,Version=v2.0" },
                }
            };

            MSBuildLogger.FormatAndSend(fakeTelemetry, telemetryEventArgs);

            fakeTelemetry.LogEntry.EventName.Should().Be("msbuild/targetframeworkeval");
            fakeTelemetry.LogEntry.Properties.Keys.Count.Should().Be(1);
            var expectedKey = "TargetFrameworkVersion";

            fakeTelemetry.LogEntry.Properties.Should().ContainKey(expectedKey);
            fakeTelemetry.LogEntry.Properties[expectedKey].Should().Be(Sha256Hasher.Hash(".NETSTANDARD,VERSION=V2.0"));
        }
Exemplo n.º 17
0
        public void ToolsSubLevelCommandNameAndArgumentShouldBeSentToTelemetry()
        {
            var parseResult =
                Parser.Instance.Parse(new List <string>()
            {
                "tool", "install", "dotnet-format"
            });

            TelemetryEventEntry.SendFiltered(Tuple.Create(parseResult,
                                                          new Dictionary <string, double>()
            {
                { "Startup Time", 0 }, { "Parse Time", 23456 }
            }));
            _fakeTelemetry.LogEntries.Should().Contain(e => e.EventName == "sublevelparser/command" &&
                                                       e.Properties.ContainsKey("verb") &&
                                                       e.Properties["verb"] == Sha256Hasher.Hash("TOOL") &&
                                                       e.Properties["subcommand"] ==
                                                       Sha256Hasher.Hash("INSTALL") &&
                                                       e.Properties["argument"] ==
                                                       Sha256Hasher.Hash("DOTNET-FORMAT"));
        }
Exemplo n.º 18
0
        public async Task InvokeAsync(HttpContext context, IAnalyticsService analyticsService, IExtremeIpLookup ipLookup, ICookieStorage cookies, ILogger <AnalyticsMiddleware> logger)
        {
            var ip = context.Connection.RemoteIpAddress;

            try
            {
                var deats = await ipLookup.GetIpDetailsAsync(ip);

                await deats.Match(o =>
                {
                    var thumb = GetThumbPrint(cookies, context.Request, context.Response);
                    return(analyticsService.Add(
                               new Domain.AnalyticsReport(Guid.NewGuid(), DateTime.UtcNow, o.City,
                                                          Sha256Hasher.Hash(thumb.ToString())), CancellationToken.None));
                }, _ => Task.CompletedTask);
            }
            catch (Exception e)
            {
                logger.LogError(e, "Error running analytics");
            }

            await this.next(context);
        }
Exemplo n.º 19
0
        public async Task Jupyter_ignore_connection_file_sends_telemetry()
        {
            var tmp = Path.GetTempFileName();

            try
            {
                // Do not capture connection file
                await _parser.InvokeAsync(String.Format("jupyter {0}", tmp), _console);

                _fakeTelemetry.LogEntries.Should().Contain(
                    x => x.EventName == "command" &&
                    x.Properties.Count == 2 &&
                    x.Properties["verb"] == Sha256Hasher.Hash("JUPYTER") &&
                    x.Properties["default-kernel"] == Sha256Hasher.Hash("CSHARP"));
            }
            finally
            {
                try
                {
                    File.Delete(tmp);
                }
                catch { }
            }
        }
Exemplo n.º 20
0
        internal static void FormatAndSend(ITelemetry telemetry, TelemetryEventArgs args)
        {
            if (args.EventName == TargetFrameworkTelemetryEventName)
            {
                var newEventName = $"msbuild/{TargetFrameworkTelemetryEventName}";
                Dictionary <string, string> maskedProperties = new Dictionary <string, string>();
                if (args.Properties.TryGetValue(TargetFrameworkVersionTelemetryPropertyKey, out string targetFrameworkVersionValue))
                {
                    maskedProperties.Add(TargetFrameworkVersionTelemetryPropertyKey, Sha256Hasher.HashWithNormalizedCasing(targetFrameworkVersionValue));
                }

                if (args.Properties.TryGetValue(UseWindowsFormsTelemetryPropertyKey, out string useWindowsFormsValue))
                {
                    maskedProperties.Add(UseWindowsFormsTelemetryPropertyKey, SanitizeToOnlyTrueFalseEmpty(useWindowsFormsValue));
                }

                if (args.Properties.TryGetValue(UseWPFTelemetryPropertyKey, out string useWPFValue))
                {
                    maskedProperties.Add(UseWPFTelemetryPropertyKey, SanitizeToOnlyTrueFalseEmpty(useWPFValue));
                }

                telemetry.TrackEvent(newEventName, maskedProperties, measurements: null);
            }
        }
Exemplo n.º 21
0
 public void HmacHash_ReturnsCorrectHash()
 {
     String actual = new Sha256Hasher().HmacHash("secretKey", "hello world");
     Assert.AreEqual("a31288ecf77d266463fc7e2a63799cb1ce6dcff156610373f722fa298e932340", actual);
 }
Exemplo n.º 22
0
        public void ItMasksEventNameWithTargetframeworkevalOnTargetFrameworkVersionUseWindowsFormsOrWPF()
        {
            var fakeTelemetry      = new FakeTelemetry();
            var telemetryEventArgs = new TelemetryEventArgs
            {
                EventName  = MSBuildLogger.TargetFrameworkTelemetryEventName,
                Properties = new Dictionary <string, string>
                {
                    { MSBuildLogger.TargetFrameworkVersionTelemetryPropertyKey, ".NETStandard,Version=v2.0" },
                    { MSBuildLogger.UseWindowsFormsTelemetryPropertyKey, "true" },
                    { MSBuildLogger.UseWPFTelemetryPropertyKey, "AnyNonTrueValue" },
                }
            };

            MSBuildLogger.FormatAndSend(fakeTelemetry, telemetryEventArgs);

            fakeTelemetry.LogEntry.EventName.Should().Be($"msbuild/{MSBuildLogger.TargetFrameworkTelemetryEventName}");
            fakeTelemetry.LogEntry.Properties.Keys.Count.Should().Be(3);
            fakeTelemetry.LogEntry.Properties[MSBuildLogger.TargetFrameworkVersionTelemetryPropertyKey].Should().Be(Sha256Hasher.Hash(".NETSTANDARD,VERSION=V2.0"));
            fakeTelemetry.LogEntry.Properties[MSBuildLogger.UseWindowsFormsTelemetryPropertyKey].Should().Be("True");
            fakeTelemetry.LogEntry.Properties[MSBuildLogger.UseWPFTelemetryPropertyKey]
            .Should().Be(
                "False",
                "sanitize to avoid user input, and since in SDK prop and target non 'true' is effectively false");
        }
Exemplo n.º 23
0
 /// <summary>
 /// Generate a pseudo-random pipe name using the specified process ID, hashed MAC address and process path.
 /// </summary>
 /// <param name="processId">The process ID to use for generating the pipe name.</param>
 /// <param name="values">Additional values to incorporate into the generated name.</param>
 /// <returns>A string containing the pipe name.</returns>
 public static string CreatePipeName(int processId, params string[] values)
 {
     // Reinvoking the host can cause differences between the original path, e.g.,
     // "C:\Program Files" and "c:\Program Files". This will generate different UUID values and cause
     // deadlock when the client and server are trying to connect, so always use the lower invariant of the process.
     return(Uuid.Create($"{processId};{Environment.ProcessPath.ToLowerInvariant()};{Sha256Hasher.Hash(MacAddressGetter.GetMacAddress())};{string.Join(";", values)}")
            .ToString("B"));
 }
Exemplo n.º 24
0
        public void HmacHash_ReturnsCorrectHash()
        {
            String actual = new Sha256Hasher().HmacHash("secretKey", "hello world");

            Assert.AreEqual("a31288ecf77d266463fc7e2a63799cb1ce6dcff156610373f722fa298e932340", actual);
        }
Exemplo n.º 25
0
            public virtual void CalcHashes(Hashes hashFlags, Validations validationFlags)
            {
                if (IssueModel.Data.HasFatal)
                {
                    return;
                }

                bool hitCache = Data.fBuf != null && Data.FileSize < Int32.MaxValue;

                if ((hashFlags & Hashes.FileMD5) != 0 && Data.fileMD5 == null)
                {
                    var hasher = new Md5Hasher();
                    if (hitCache)
                    {
                        hasher.Append(Data.fBuf, 0, Data.fBuf.Length);
                    }
                    else
                    {
                        hasher.Append(Data.fbs);
                    }
                    Data.fileMD5 = hasher.GetHashAndReset();
                }

                if ((hashFlags & Hashes.FileSHA1) != 0 && Data.fileSHA1 == null)
                {
                    var hasher = new Sha1Hasher();
                    if (hitCache)
                    {
                        hasher.Append(Data.fBuf, 0, Data.fBuf.Length);
                    }
                    else
                    {
                        hasher.Append(Data.fbs);
                    }
                    Data.fileSHA1 = hasher.GetHashAndReset();
                }

                if ((hashFlags & Hashes.FileSHA256) != 0 && Data.fileSHA256 == null)
                {
                    var hasher = new Sha256Hasher();
                    if (hitCache)
                    {
                        hasher.Append(Data.fBuf, 0, Data.fBuf.Length);
                    }
                    else
                    {
                        hasher.Append(Data.fbs);
                    }
                    Data.fileSHA256 = hasher.GetHashAndReset();
                }

                if ((hashFlags & Hashes.MediaSHA1) != 0 && Data.mediaSHA1 == null)
                {
                    if (Data.MediaCount == Data.FileSize && Data.fileSHA1 != null)
                    {
                        System.Diagnostics.Debug.Assert(Data.mediaPosition == 0);
                        Data.mediaSHA1 = Data.fileSHA1;
                    }
                    else
                    {
                        var hasher = new Sha1Hasher();
                        if (hitCache)
                        {
                            hasher.Append(Data.fBuf, (int)Data.mediaPosition, (int)Data.MediaCount);
                        }
                        else
                        {
                            hasher.Append(Data.fbs, Data.mediaPosition, Data.MediaCount);
                        }
                        Data.mediaSHA1 = hasher.GetHashAndReset();
                    }
                }

                if ((hashFlags & Hashes.MetaSHA1) != 0 && Data.metaSHA1 == null)
                {
                    var hasher    = new Sha1Hasher();
                    var suffixPos = Data.mediaPosition + Data.MediaCount;

                    if (hitCache)
                    {
                        hasher.Append(Data.fBuf, 0, (int)Data.mediaPosition, (int)suffixPos, (int)(Data.FileSize - suffixPos));
                    }
                    else
                    {
                        hasher.Append(Data.fbs, 0, Data.mediaPosition, suffixPos, Data.FileSize - suffixPos);
                    }

                    Data.metaSHA1 = hasher.GetHashAndReset();
                }
            }
Exemplo n.º 26
0
 /// <summary>
 /// Generate a pseudo-random pipe name using the specified process ID, hashed MAC address and process path.
 /// </summary>
 /// <param name="processId">The process ID to use for generating the pipe name.</param>
 /// <param name="values">Additional values to incorporate into the generated name.</param>
 /// <returns>A string containing the pipe name.</returns>
 public static string CreatePipeName(int processId, params string[] values)
 {
     return(Uuid.Create($"{processId};{Environment.ProcessPath};{Sha256Hasher.Hash(MacAddressGetter.GetMacAddress())};{string.Join(";", values)}")
            .ToString("B"));
 }
Exemplo n.º 27
0
        public Client(Guid sessionid, ClientAppHostEnvironment host, UpdaterService updater)
        {
            if (Interactive.Client.CommandLineTool.TestDriver.ShouldRun)
            {
                return;
            }

            PreferenceStore.Default.Subscribe(ObservePreferenceChange);

            try {
                if (!Prefs.Telemetry.Enabled.GetValue())
                {
                    Log.Info(TAG, "Telemetry is disabled");
                    return;
                }

                // InMemoryChannel is the default channel, but we set it up manually here so we can tweak several
                // default settings that are undesirable for desktop apps.
                channel = new InMemoryChannel {
                    // Defaults to 30s, but since we are changing buffer.Capacity to 1, we can make this infinite and
                    // avoid pointlessly waking up InMemoryTransmitter's Runner.
                    SendingInterval = Timeout.InfiniteTimeSpan,
                };

                // There is no reasonable public API for changing the buffer capacity at this time.
                // You can achieve it by turning on DeveloperMode, but that has other consequences.
                // So we reflect.
                //
                // The default Capacity is 500, which is far too large for us (and perhaps most non-server apps).
                // We want to avoid having to perform a blocking Flush call on the UI thread, and since our events
                // are currently few and far between, we set Capacity to 1 to essentially get auto-flush.
                var channelBuffer = typeof(InMemoryChannel)
                                    .GetField("buffer", BindingFlags.NonPublic | BindingFlags.Instance)
                                    .GetValue(channel);
                channelBuffer
                .GetType()
                .GetProperty("Capacity", BindingFlags.Public | BindingFlags.Instance)
                .SetValue(channelBuffer, 1);

                var config = new TelemetryConfiguration("@TELEMETRY_INSTRUMENTATION_KEY@", channel);

                appInsightsClient = new TelemetryClient(config);

                appInsightsClient.Context.Session.Id             = sessionid.ToString();
                appInsightsClient.Context.Device.OperatingSystem = host.OSName.ToString();

                // TODO: Make these GlobalProperties when we bump to 2.7.0-beta3 or later
                var globalProperties = appInsightsClient.Context.Properties;
                globalProperties.Add(
                    "Product Version",
                    BuildInfo.VersionString);
                globalProperties.Add(
                    "Build Hash",
                    BuildInfo.Hash);
                globalProperties.Add(
                    "OS Platform",
                    Runtime.CurrentProcessRuntime.OSPlatform.ToString());
                globalProperties.Add(
                    "OS Architecture",
                    RuntimeInformation.OSArchitecture.ToString());
                globalProperties.Add(
                    "Process Architecture",
                    Runtime.CurrentProcessRuntime.Architecture.ToString());
                globalProperties.Add(
                    "Runtime Identifier",
                    Runtime.CurrentProcessRuntime.RuntimeIdentifier);
                globalProperties.Add(
                    "OS Version",
                    host.OSVersion.ToString());
                globalProperties.Add(
                    "Release Candidate Level",
                    ((byte)BuildInfo.Version.CandidateLevel).ToString());
                globalProperties.Add(
                    "Release Candidate Level Name",
                    BuildInfo.Version.CandidateLevel.ToString().ToLowerInvariant());
                globalProperties.Add(
                    "Machine ID",
                    Sha256Hasher.Hash(MacAddressGetter.GetMacAddress()));
                globalProperties.Add(
                    "Update Channel", updater.UpdateChannel);

                enabled = true;
            } catch (Exception e) {
                LogErrorWithoutTelemetry(e, "Unable to create AppInsights client for telemetry");
            }
        }