/// <summary> /// Initializes the telemetry client. /// </summary> public static void Initialize(IServiceProvider serviceProvider, string version, string telemetryKey) { if (_telemetry != null) throw new NotSupportedException("The telemetry client is already initialized"); var dte = (DTE2)serviceProvider.GetService(typeof(DTE)); _telemetry = new TelemetryClient(); _telemetry.Context.Session.Id = Guid.NewGuid().ToString(); _telemetry.Context.Device.Model = dte.Edition; _telemetry.InstrumentationKey = telemetryKey; _telemetry.Context.Component.Version = version; byte[] enc = Encoding.UTF8.GetBytes(Environment.UserName + Environment.MachineName); using (var crypto = new MD5CryptoServiceProvider()) { byte[] hash = crypto.ComputeHash(enc); _telemetry.Context.User.Id = Convert.ToBase64String(hash); } _events = dte.Events.DTEEvents; _events.OnBeginShutdown += delegate { _telemetry.Flush(); }; Enabled = true; }
public static void Main(string[] args) { var config = new Configuration(); var telemetry = new TelemetryClient(); telemetry.InstrumentationKey = config.InstrumentationKey; telemetry.Context.Device.Id = Environment.MachineName; telemetry.Context.Session.Id = Guid.NewGuid().ToString(); telemetry.Context.Location.Ip = Dns.GetHostEntryAsync(Dns.GetHostName()) .Result .AddressList .FirstOrDefault(addr => addr.AddressFamily == AddressFamily.InterNetwork) .ToString(); using (var amz = new AmazonSynchronizer(config, telemetry)) { amz.WithInterval(TimeSpan.FromSeconds(1)) .StopWhen((obj) => false) .Start(CancellationToken.None) .Wait(); } if (telemetry != null) telemetry.Flush(); Console.WriteLine("Sync Server Stopped.Press any key to exit ..."); Console.ReadKey(); }
public static void LogException(Exception ex, Dictionary <string, string> properties = null, Dictionary <string, double> metrics = null) { if (TelemetryEnabled) { telemetry.TrackException(ex, properties, metrics); telemetry.Flush(); } }
protected void Application_Start() { // Read instrumentation key from azure web app settings string ikeyValue = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY"); if (!string.IsNullOrEmpty(ikeyValue)) { TelemetryConfiguration.Active.InstrumentationKey = ikeyValue; } try { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); BindingConfig.RegisterGlobalBindings(ModelBinders.Binders, GlobalConfiguration.Configuration); FormatterConfig.RegisterFormatters(GlobalConfiguration.Configuration); ReleaseSettings.Settings.Options.PackageListingPath = Server.MapPath("~/Content/packages.json"); ReleaseSettings.Settings.Initialize(); PackageSettings.Settings.NugetListingPath = Server.MapPath("~/Content/nuget.json"); PackageSettings.Settings.Initialize(); TwitterSettings.Settings.Initialize(); BuildSettings.Settings.Initialize(); BlogSettings.Settings.Initialize(); ContributorSettings.Settings.Options.ContributorListingPath = Server.MapPath("~/Content/committers.json"); ContributorSettings.Settings.Initialize(); } catch (Exception ex) { TelemetryClient client = new TelemetryClient(); ExceptionTelemetry excTelemetry = new ExceptionTelemetry(ex); excTelemetry.HandledAt = ExceptionHandledAt.Unhandled; client.TrackException(excTelemetry); // this exception will terminate the process. Let's wait till telemetry will be delivered client.Flush(); Thread.Sleep(1000); throw; } }
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (ChatterBox.Client.Common.Settings.SignalingSettings.AppInsightsEnabled) { ExceptionTelemetry excTelemetry = new ExceptionTelemetry((Exception)e.Exception); excTelemetry.SeverityLevel = SeverityLevel.Critical; excTelemetry.HandledAt = ExceptionHandledAt.Unhandled; excTelemetry.Timestamp = System.DateTimeOffset.UtcNow; var telemetry = new TelemetryClient(); telemetry.TrackException(excTelemetry); telemetry.Flush(); } }
public async void SaveArea() { var json = await Request.Content.ReadAsStringAsync(); var telemetry = new Microsoft.ApplicationInsights.TelemetryClient(); telemetry.TrackEvent("STH", new Dictionary <string, string> { { "body", json.Replace(@"\", "").TrimStart('"').TrimEnd('"') } }); telemetry.Flush(); var dbGeo = JsonConvert.DeserializeObject <Polygon>(json.Replace(@"\", "").TrimStart('"').TrimEnd('"')).ToDbGeography(); var sqlGeography = MakePolygonValid(dbGeo); sqlGeography = sqlGeography.Reduce(1); var newPolygon = DbGeography.FromBinary(sqlGeography.STAsBinary().Value); using (var context = new PttContext()) { var intersectingAreas = context.CoveredAreas.Where(x => x.Geo.Intersects(newPolygon)).ToList(); var user = UserHelper.GetUser(context, RequestContext); if (newPolygon.Length != null) { user.Statistic.DistanceWalked += (double)newPolygon.Length; } foreach (var intersectingArea in intersectingAreas) { if (intersectingArea.User == user) { intersectingArea.Geo = intersectingArea.Geo.Difference(newPolygon); } } context.CoveredAreas.Add(new CoveredArea() { User = user, Geo = newPolygon }); context.SaveChanges(); } }
public static void Start() { if (CoreApp.DoNotTrack()) { return; } Log.Debug("Insights - starting"); try { var configuration = TelemetryConfiguration.Active; Assert.IsNotNull(configuration, "configuration"); configuration.TelemetryChannel = new PersistenceChannel("Sitecore Instance Manager"); configuration.InstrumentationKey = "1447f72f-2d39-401b-91ac-4d5c502e3359"; var client = new TelemetryClient(configuration) { InstrumentationKey = "1447f72f-2d39-401b-91ac-4d5c502e3359" }; Analytics.telemetryClient = client; try { // ReSharper disable PossibleNullReferenceException client.Context.Component.Version = string.IsNullOrEmpty(ApplicationManager.AppVersion) ? "0.0.0.0" : ApplicationManager.AppVersion; client.Context.Session.Id = Guid.NewGuid().ToString(); client.Context.User.Id = Environment.MachineName + "\\" + Environment.UserName; client.Context.User.AccountId = CoreApp.GetCookie(); client.Context.Device.OperatingSystem = Environment.OSVersion.ToString(); // ReSharper restore PossibleNullReferenceException client.TrackEvent("Start"); client.Flush(); } catch (Exception ex) { client.TrackException(ex); Log.Error(ex, "Error in app insights"); } } catch (Exception ex) { Log.Error(ex, "Error in app insights"); } Log.Debug("Insights - started"); }
public static void TrackPackageNotFound(string id, string version, string logFileName) { if (!_initialized) { return; } var telemetryClient = new TelemetryClient(); var telemetry = new EventTelemetry("PackageNotFound"); telemetry.Properties.Add("PackageId", id); telemetry.Properties.Add("PackageVersion", version); telemetry.Properties.Add("LogFile", logFileName); telemetryClient.TrackEvent(telemetry); telemetryClient.Flush(); }
private static void GenerateUnobservedException(TelemetryClient client) { Task.Factory.StartNew(() => { throw new Exception(); }); HardWork(TimeSpan.FromSeconds(5)); // This forces exception to become unobserved GC.Collect(2, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); HardWork(TimeSpan.FromSeconds(5)); client.Flush(); HardWork(TimeSpan.FromSeconds(5)); }
/// <summary> /// Initializes the telemetry client. /// </summary> public static void Initialize(DTE2 dte, string version, string telemetryKey) { if (_telemetry != null) throw new NotSupportedException("The telemetry client is already initialized"); _telemetry = new TelemetryClient(); _telemetry.Context.Session.Id = Guid.NewGuid().ToString(); _telemetry.Context.User.Id = (Environment.UserName + Environment.MachineName).GetHashCode().ToString(); _telemetry.Context.Device.Model = dte.Edition; _telemetry.InstrumentationKey = telemetryKey; _telemetry.Context.Component.Version = version; _events = dte.Events.DTEEvents; _events.OnBeginShutdown += delegate { _telemetry.Flush(); }; Enabled = true; }
public static void TrackMetric(string metricName, double value, string logFileName) { if (!_initialized) { return; } var telemetryClient = new TelemetryClient(); var telemetry = new MetricTelemetry(metricName, value); if (!string.IsNullOrWhiteSpace(logFileName)) { telemetry.Properties.Add("LogFile", logFileName); } telemetryClient.TrackMetric(telemetry); telemetryClient.Flush(); }
public static void TrackException(Exception exception, string logFileName = null) { if (!_initialized) { return; } var telemetryClient = new TelemetryClient(); var telemetry = new ExceptionTelemetry(exception); if (!string.IsNullOrWhiteSpace(logFileName)) { telemetry.Properties.Add("LogFile", logFileName); } telemetryClient.TrackException(telemetry); telemetryClient.Flush(); }
public async Task <FeatureCollection> GetPolysInArea() { string json = await Request.Content.ReadAsStringAsync(); var telemetry = new Microsoft.ApplicationInsights.TelemetryClient(); telemetry.TrackEvent("STH", new Dictionary <string, string> { { "body", json.Replace(@"\", "").TrimStart('"').TrimEnd('"') } }); telemetry.Flush(); var currentPostion = JsonConvert.DeserializeObject <GeoJSON.Net.Geometry.Point>(json.Replace(@"\", "").TrimStart('"').TrimEnd('"')); var currentPositionDbGeography = currentPostion.ToDbGeography(); var result = new FeatureCollection(); using (var context = new PttContext()) { foreach (var nearArea in context.CoveredAreas.Where( x => x.Geo.Distance(currentPositionDbGeography) < 10000)) { result.Features.Add(new Feature(nearArea.Geo.ToGeoJSONGeometry())); } var firstGeo = context.CoveredAreas.First(x => x.Id == 3).Geo; var y = context.CoveredAreas.Where(x => x.Geo.Intersects(firstGeo)).ToList(); foreach (var intersectingArea in y) { intersectingArea.Geo = intersectingArea.Geo.Difference(firstGeo); } telemetry.TrackEvent("ResultCount", new Dictionary <string, string> { { "xxxxx", result.Features.Count.ToString() } }); return(result); } }
public static void Start() { if (string.IsNullOrEmpty(ApplicationManager.AppVersion) || EnvironmentHelper.DoNotTrack()) { return; } Log.Debug("Insights - starting"); try { var tc = new TelemetryClient(new TelemetryConfiguration { InstrumentationKey = "1447f72f-2d39-401b-91ac-4d5c502e3359", TelemetryChannel = new PersistenceChannel() }); client = tc; try { tc.Context.Session.Id = Guid.NewGuid().ToString(); tc.Context.User.Id = Environment.MachineName + "\\" + Environment.UserName; tc.Context.User.AccountId = EnvironmentHelper.GetCookie(); tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString(); tc.TrackEvent("Start"); tc.Flush(); } catch (Exception ex) { tc.TrackException(ex); Log.Error(ex, "Error in app insights"); } } catch (Exception ex) { Log.Error(ex, "Error in app insights"); } Log.Debug("Insights - started"); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { TelemetryClient = new TelemetryClient(); } catch (Exception) { // ignored } try { // Create default garbage collection settings for all the actor types var actorGarbageCollectionSettings = new ActorGarbageCollectionSettings(300, 60); // This line registers your actor class with the Fabric Runtime. // The contents of your ServiceManifest.xml and ApplicationManifest.xml files // are automatically populated when you build this project. // For more information, see http://aka.ms/servicefabricactorsplatform ActorRuntime.RegisterActorAsync<DeviceActor>( (context, actorType) => new DeviceActorService(context, actorType, () => new DeviceActor(), null, new ActorServiceSettings { ActorGarbageCollectionSettings = actorGarbageCollectionSettings })).GetAwaiter().GetResult(); Thread.Sleep(Timeout.Infinite); } catch (Exception e) { TelemetryClient.TrackException(e); ActorEventSource.Current.ActorHostInitializationFailed(e); throw; } finally { TelemetryClient.Flush(); } }
static void Main() { Console.WriteLine("Hello, this is a trace"); try { var eventHubString = ConfigurationManager.ConnectionStrings["EventHubConnection"]; var eventHubName = ConfigurationManager.ConnectionStrings["EventHubName"]; var appInsightsKey = ConfigurationManager.ConnectionStrings["AppInsightsKey"]; var nsm = NamespaceManager.CreateFromConnectionString(eventHubString.ConnectionString); var hub = nsm.GetEventHub(eventHubName.ConnectionString); TelemetryClient appInsights = new TelemetryClient(); appInsights.InstrumentationKey = appInsightsKey.ConnectionString; var telemetryData = new EventTelemetry() { Name = "Event Hub Heartbeat", }; telemetryData.Properties.Add("Status", hub.Status.ToString()); appInsights.TrackEvent(telemetryData); appInsights.Flush(); Console.Write($"Service status is at {hub.Status}"); } catch { Console.WriteLine("Catch handler"); } Console.WriteLine("We're done"); }
private static void TrackTelemetryOnIndexReopened(object sender, SegmentInfoEventArgs e) { var telemetryClient = new TelemetryClient(); // track the index reopened event var eventTelemetry = new EventTelemetry("Index Reopened"); eventTelemetry.Metrics.Add("Segment Count", e.Segments.Count()); eventTelemetry.Metrics.Add("Segment Size (Sum)", e.Segments.Sum(s => s.NumDocs)); telemetryClient.TrackEvent(eventTelemetry); foreach (var segment in e.Segments) { var metricTelemetry = new MetricTelemetry("Segment Size", segment.NumDocs); metricTelemetry.Properties.Add("Segment Name", segment.Name); telemetryClient.TrackMetric(metricTelemetry); } telemetryClient.Flush(); }
// Create a CSV file and save to Blob storage with the Headers required for our Azure Function processing // A new request telemetry is created // The request is part of the parent request (since) public void CreateBlob(string fileName) { /////////////////////////////////////////////////// // Grab existing /////////////////////////////////////////////////// Microsoft.ApplicationInsights.TelemetryClient telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient(); telemetryClient.Context.User.AuthenticatedUserId = "*****@*****.**"; string traceoperation = null; string traceparent = null; System.Console.WriteLine("telemetryClient.Context.Operation.Id: " + telemetryClient.Context.Operation.Id); System.Console.WriteLine("telemetryClient.Context.Session.Id: " + telemetryClient.Context.Session.Id); System.Console.WriteLine("telemetryClient.Context.Operation.ParentId: " + telemetryClient.Context.Operation.ParentId); Microsoft.ApplicationInsights.DataContracts.RequestTelemetry requestTelemetry = new Microsoft.ApplicationInsights.DataContracts.RequestTelemetry(); requestTelemetry.Name = "Create Blob: " + fileName; //requestTelemetry.Source = requestContext.Replace("appId=",string.Empty); requestTelemetry.Timestamp = System.DateTimeOffset.Now; requestTelemetry.Context.Operation.Id = traceoperation; requestTelemetry.Context.Operation.ParentId = traceparent; requestTelemetry.Context.User.AuthenticatedUserId = "*****@*****.**"; using (var requestBlock = telemetryClient.StartOperation<Microsoft.ApplicationInsights.DataContracts.RequestTelemetry>(requestTelemetry)) { /////////////////////////////////////////////////// // Request Telemetry /////////////////////////////////////////////////// requestBlock.Telemetry.Context.User.AuthenticatedUserId = "*****@*****.**"; if (!string.IsNullOrWhiteSpace(traceoperation)) { // Use the existing common operation id requestBlock.Telemetry.Context.Operation.Id = traceoperation; System.Console.WriteLine("[Use existing] traceoperation: " + traceoperation); } else { // Set the traceoperation (we did not know it until now) traceoperation = requestBlock.Telemetry.Context.Operation.Id; System.Console.WriteLine("[Set the] traceoperation = requestBlock.Telemetry.Context.Operation.Id: " + traceoperation); } if (!string.IsNullOrWhiteSpace(traceparent)) { // Use the existing traceparent requestBlock.Telemetry.Context.Operation.ParentId = traceparent; System.Console.WriteLine("[Use existing] traceparent: " + traceparent); } else { traceparent = requestBlock.Telemetry.Id; System.Console.WriteLine("[Set the] traceparent = requestBlock.Telemetry.Id: " + traceparent); } // Store future parent id traceparent = requestBlock.Telemetry.Id; System.Console.WriteLine("traceparent = requestBlock.Telemetry.Id: " + traceparent); /////////////////////////////////////////////////// // Create Dependency for future Azure Function processing // NOTE: I trick it by giving a Start Time Offset of Now.AddSeconds(1), so it sorts correctly in the Azure Portal UI /////////////////////////////////////////////////// string operationName = "Dependency: Blob Event"; // Set the target so it points to the "dependent" app insights account app id // string target = "03-disttrace-func-blob | cid-v1:676560d0-81fb-4e5b-bfdd-7da1ad11c866" string target = "03-disttrace-func-blob | cid-v1:" + System.Environment.GetEnvironmentVariable("ai_03_disttrace_web_app_appkey"); string dependencyName = "Dependency Name: Azure Function Blob Trigger"; Microsoft.ApplicationInsights.DataContracts.DependencyTelemetry dependencyTelemetry = new Microsoft.ApplicationInsights.DataContracts.DependencyTelemetry( operationName, target, dependencyName, "02-disttrace-web-app", System.DateTimeOffset.Now.AddSeconds(1), System.TimeSpan.FromSeconds(2), "200", true); dependencyTelemetry.Context.Operation.Id = traceoperation; dependencyTelemetry.Context.Operation.ParentId = requestBlock.Telemetry.Id; // Store future parent id traceparent = dependencyTelemetry.Id; System.Console.WriteLine("traceparent = dependencyTelemetry.Id: " + traceparent); telemetryClient.TrackDependency(dependencyTelemetry); /////////////////////////////////////////////////// // Blob code /////////////////////////////////////////////////// string containerName = "appinsightstest"; string storageConnectionString = System.Environment.GetEnvironmentVariable("ai_storage_key"); CloudStorageAccount storageAccount = null; System.Console.WriteLine("storageConnectionString: " + storageConnectionString); CloudStorageAccount.TryParse(storageConnectionString, out storageAccount); System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>(); list.Add("id,date"); for (int i = 1; i <= 50000; i++) { list.Add(i.ToString() + "," + string.Format("{0:MM/dd/yyyy}", System.DateTime.Now)); } var text = string.Join("\n", list.ToArray()); Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient(); blobStorage.DefaultRequestOptions.RetryPolicy = new Microsoft.WindowsAzure.Storage.RetryPolicies.LinearRetry(System.TimeSpan.FromSeconds(1), 10); Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer container = blobStorage.GetContainerReference(containerName); container.CreateIfNotExistsAsync().Wait(); Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob blob = container.GetBlockBlobReference(fileName); /////////////////////////////////////////////////// // Set the blob's meta data // We need the values from the dependency /////////////////////////////////////////////////// // Request-Context: appId=cid-v1:{The App Id of the current App Insights Account} string requestContext = "appId=cid-v1:" + System.Environment.GetEnvironmentVariable("ai_02_disttrace_web_app_appkey"); System.Console.WriteLine("Blob Metadata -> requestContext: " + requestContext); blob.Metadata.Add("RequestContext", requestContext); // Request-Id / traceparent: {parent request/operation id} (e.g. the Track Dependency) System.Console.WriteLine("Blob Metadata -> RequestId: " + traceparent); blob.Metadata.Add("RequestId", traceparent); System.Console.WriteLine("Blob Metadata -> traceparent: " + traceparent); blob.Metadata.Add("traceparent", traceparent); // Traceoperation {common operation id} (e.g. same operation id for all requests in this telemetry pipeline) System.Console.WriteLine("Blob Metadata -> traceoperation: " + traceoperation); blob.Metadata.Add("traceoperation", traceoperation); using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(text))) { blob.UploadFromStreamAsync(memoryStream).Wait(); } requestTelemetry.ResponseCode = "200"; requestTelemetry.Success = true; telemetryClient.StopOperation(requestBlock); } // using /////////////////////////////////////////////////// // For Debugging /////////////////////////////////////////////////// telemetryClient.Flush(); } // Create Blob
public static void TrackReportProcessed(string reportName, string packageId = null) { if (!_initialized) { return; } var telemetryClient = new TelemetryClient(); var telemetry = new MetricTelemetry(reportName, 1); if (!string.IsNullOrWhiteSpace(packageId)) { telemetry.Properties.Add("Package Id", packageId); } telemetryClient.TrackMetric(telemetry); telemetryClient.Flush(); }
public static void TrackSqlException(string eventName, SqlException sqlException, string logFileName, string dimension) { if (!_initialized) { return; } var telemetryClient = new TelemetryClient(); var telemetry = new EventTelemetry(eventName); telemetry.Properties.Add("Dimension", dimension); if (!string.IsNullOrWhiteSpace(logFileName)) { telemetry.Properties.Add("LogFile", logFileName); } telemetryClient.TrackEvent(telemetry); telemetryClient.Flush(); TrackException(sqlException, logFileName); }
public static void TrackRetrieveDimensionDuration(string dimension, long value, string logFileName) { if (!_initialized) { return; } var telemetryClient = new TelemetryClient(); var telemetry = new MetricTelemetry("Retrieve Dimension duration (ms)", value); telemetry.Properties.Add("Dimension", dimension); if (!string.IsNullOrWhiteSpace(logFileName)) { telemetry.Properties.Add("LogFile", logFileName); } telemetryClient.TrackMetric(telemetry); telemetryClient.Flush(); }
private static void ConfigureApplication(string instrumentationKey, TelemetryClient client, TelemetryConfiguration config, TelemetryInitializer initializer) { config.InstrumentationKey = instrumentationKey; config.TelemetryInitializers.Add(initializer); Application.ThreadException += (s, e) => { client.TrackException(new ExceptionTelemetry(e.Exception) { HandledAt = ExceptionHandledAt.Unhandled, SeverityLevel = SeverityLevel.Critical, }); throw e.Exception; }; Application.ApplicationExit += (s, e) => { client.Flush(); }; }
public async Task Initialize() { try { telemetryClient = new TelemetryClient(); telemetryClient.InstrumentationKey = "23694f6c-53c2-42e2-9427-b7e02cda9c6f"; telemetryClient.Context.Component.Version = Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion; telemetryClient.Context.Session.Id = Guid.NewGuid().ToString(); telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString(); telemetryClient.TrackPageView("Home"); telemetryClient.Flush(); } catch (Exception ex) { Trace.TraceError("Couldn't initialize telemetry: " + ex); } // Check for updates await CheckForUpdates(); SelectedMirrorProvider = MirrorProviders.First(); apps = (await applicationEnumerator.GetInstalledApplications()).ToList(); if (!apps.Any()) { Trace.TraceWarning("No BitTorrent applications found."); return; } foreach (var result in apps) { Trace.TraceInformation("Found app {0} version {1} at {2}", result.Description, result.Version, result.InstallLocation); } }