Exemplo n.º 1
0
        public async Task <IActionResult> GetById(int id)
        {
            try
            {
                _telemetry.TrackPageView(new PageViewTelemetry("ModelController.GetById")
                {
                    Timestamp = DateTime.UtcNow
                });
                _telemetry.Flush();
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                Model result = await _businessContext.GetAllAsyncById(id);

                return(Ok(result));
            }
            catch (AggregateException ex)
            {
                ErrorTreatment("GetById", null, ex);

                return(NotFound());
            }
            catch (Exception ex)
            {
                ErrorTreatment("GetById", ex, null);
                return(StatusCode(500, ex));
            }
        }
Exemplo n.º 2
0
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            cancellationToken.Register(() =>
            {
                _logger.LogInformation("Worker Cancelling");
            });

            try
            {
                _logger.LogInformation("Worker Running at: {time} for correlation id: {id}", DateTimeOffset.Now, _correlationConfiguration.CorrelationId);

                await _messageListener.ReceiveAndHandleAsync(cancellationToken);
            }
            catch (OperationCanceledException)
            {
                _logger.LogInformation("Operation Canceled");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unhandled Exception");
            }
            finally
            {
                _telemetryQueue.Flush();
                _telemetryClient.Flush();

                Task.Delay(TimeSpan.FromSeconds(30)).Wait();

                _hostApplicationLifetime.StopApplication();
            }
        }
        private void ExternalToolsInstaller_AfterUninstall(object sender, InstallEventArgs e)
        {
            // Read version installed
            ExternalToolConfiguration externalToolConfiguration = ReadExternalToolConfiguration();
            string versionInstalled = GetInstallerProductVersion() ?? externalToolConfiguration?.version ?? "unknown";

            // Enable telemetry if it was enabled in configuration file or if there is no configuration
            bool telemetryEnabled = externalToolConfiguration?.arguments?.Contains(TELEMETRY_ARGUMENT) ?? true;
            var  ev = new EventTelemetry
            {
                Name = "Uninstall"
            };

            ev.Properties["Version"] = versionInstalled;

            // Initialize Telemetry
            TelemetryClient tc = GetTelemetryClient(telemetryEnabled);

            try
            {
                // Send telemetry
                tc.TrackEvent(ev);
                tc.Flush();
            }
            catch (Exception ex)
            {
                // In case of error, send exception to Telemetry
                tc.TrackException(ex);
                tc.Flush();
                throw;
            }
        }
        internal void ConfigureUserTraits()
        {
            try
            {
                var user = $"{Environment.UserName}@{Environment.MachineName}";

                _telemetry.Context.User.Id = user;
                if (string.IsNullOrEmpty(_telemetry.Context.Session.Id))
                {
                    _telemetry.Context.Session.Id = Guid.NewGuid().ToString();
                }

                _telemetry.Context.GlobalProperties["language"] = Thread.CurrentThread.CurrentCulture.Name;
                _telemetry.Context.GlobalProperties["user"]     = user;

                if (_options.UserTraits != null)
                {
                    foreach (var trait in _options.UserTraits)
                    {
                        _telemetry.Context.GlobalProperties[trait.Key] = trait.Value;
                    }
                }

                _telemetry.Flush();
                StartHeartbeat();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                Debugger.Break();
            }
        }
Exemplo n.º 5
0
        public void RecordDrill(DrillOptions drillOptions, DrillStats drillStats)
        {
            var properties = new Dictionary <string, string>
            {
                { "Url", drillOptions.Url },
                { "ConnectionCount", drillOptions.ConnectionCount.ToString() },
                { "MillisecondsToDrill", drillOptions.MillisecondsToDrill.ToString() },
                { "MillisecondsToWaitAfterRequest", drillOptions.MillisecondsToWaitAfterRequest.ToString() },
                { "QueryStringParameters", CombineQueryStringParameters(drillOptions.QueryStringParameters) }
            };

            var metrics = new Dictionary <string, double>
            {
                { "TotalRequestCount", drillStats.TotalRequestCount },
                { "ConnectionCount", drillStats.ConnectionCount },
                { "FailureCount", drillStats.FailureCount },
                { "AverageResponseTime", (double)drillStats.AverageResponseTime }
            };

            _telemetryClient.TrackEvent("Drill", properties, metrics);

            _telemetryClient.Flush();

            System.Threading.Thread.Sleep(5000);
        }
        public Task Info(string message, Type type = null)
        {
            _logger.LogInformation($"Info Message: {message}; Type: {type}");
            _telemetryClient?.Flush();

            return(Task.FromResult(0));
        }
Exemplo n.º 7
0
        public Action <IApplicationBuilder> Configure(Action <IApplicationBuilder> next) => app =>
        {
            // Enable tracking of application start/stop to Application Insights
            if (_telemetry.IsEnabled())
            {
                _appLifetime.ApplicationStarted.Register(() =>
                {
                    var startedEvent = new EventTelemetry("Application Started");
                    _telemetry.TrackEvent(startedEvent);
                });
                _appLifetime.ApplicationStopping.Register(() =>
                {
                    var startedEvent = new EventTelemetry("Application Stopping");
                    _telemetry.TrackEvent(startedEvent);
                    _telemetry.Flush();
                });
                _appLifetime.ApplicationStopped.Register(() =>
                {
                    var stoppedEvent = new EventTelemetry("Application Stopped");
                    _telemetry.TrackEvent(stoppedEvent);
                    _telemetry.Flush();

                    // Allow some time for flushing before shutdown.
                    Thread.Sleep(1000);
                });
            }

            // Call next now so that the ILoggerFactory by Startup.Configure is configured before we go any further
            next(app);

            // Prime the cached web root file provider for static file serving
            _cachedWebRoot.PrimeCache();
        };
Exemplo n.º 8
0
        public static void LogException(Exception exception, Dictionary <string, string> traceDetails)
        {
            try
            {
                ExceptionTelemetry telemetry = new ExceptionTelemetry(exception);

                Type exceptionType = exception.GetType();
                if (exceptionType != null)
                {
                    foreach (PropertyInfo property in exceptionType.GetProperties())
                    {
                        telemetry.Properties[$"{exceptionType.Name}.{property.Name}"] = JsonConvert.SerializeObject(property.GetValue(exception), jsonSettings);
                    }

                    foreach (KeyValuePair <string, string> entry in traceDetails)
                    {
                        telemetry.Properties[entry.Key] = entry.Value;
                    }

                    telemetry.Message   = exception.Message;
                    telemetry.Exception = exception;
                    client.TrackException(telemetry);
                    client.Flush();
                }
            }
            catch (Exception)
            {
            }
        }
 public void TrackEvent(string eventName)
 {
     if (IsUserOptedIn)
     {
         _telemetryClient.TrackEvent(eventNamePrefix + eventName);
         _telemetryClient.Flush();
     }
 }
 /// <summary>
 /// Sends event telemetry for the specified event type.
 /// </summary>
 /// <param name="eventType">The type of the event.</param>
 public static void WriteEvent(TelemetryEvent eventType)
 {
     if (s_IsInitialized)
     {
         s_AppInsightsClient.TrackEvent(eventType.ToString());
         s_AppInsightsClient.Flush();
     }
 }
Exemplo n.º 11
0
 /// <summary>
 /// This is the Method executed after the Method Body
 /// Important: Name must match <see cref="OnAfterMethod"/>
 /// </summary>
 // ReSharper disable once UnusedMember.Global Justification: Reflection
 public static void OnAfterMethod(string documentationCommentId)
 {
     if (!_methodStartDateTimes.TryRemove(documentationCommentId, out var startDateTime))
     {
         return;
     }
     _telemetryClient.TrackDependency("telemetry", "-target-", documentationCommentId, "-data-", startDateTime, DateTime.UtcNow - startDateTime, "0", true);
     _telemetryClient.Flush();
 }
Exemplo n.º 12
0
 private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
 {
     if (InnerClient == null)
     {
         return;
     }
     InnerClient.TrackException(e.Exception);
     InnerClient.Flush();
 }
Exemplo n.º 13
0
        public static void TrackFrameworkUse(string prefix, CodeGenerationMode codeGenerationMode)
        {
#if !DEBUG
            if (Enabled && telemetry != null)
            {
                telemetry.TrackEvent($"{prefix}:{codeGenerationMode}");
                telemetry.Flush();
            }
#endif
        }
Exemplo n.º 14
0
 /// <summary>
 /// This method log User actions and other events. Used to track user behavior or to monitor performance.
 /// </summary>
 /// <param name="message"></param>
 public void TrackEvent(string message)
 {
     if (IsTraceEnabledForEvents)
     {
         //assign Instrumentation Key to TelemetryClient object
         client.InstrumentationKey = InstrumentationKey;
         client.TrackEvent(message);
         //flush the buffer data
         client.Flush();
     }
 }
        private void SendTelemetry(string url, string name, string responseCode, Dictionary <string, string> properties)
        {
            RequestTelemetry requestTelemetry = new RequestTelemetry();

            requestTelemetry.Url          = new Uri(url);
            requestTelemetry.ResponseCode = responseCode;
            requestTelemetry.Name         = name;
            requestTelemetry.Properties.Concat(properties);
            telemetryClient.TrackRequest(requestTelemetry);
            telemetryClient.Flush();
        }
Exemplo n.º 16
0
 public async Task TrackErrorAsync(Exception ex, Dictionary <string, string> properties = null)
 {
     try
     {
         client.TrackException(ex, properties);
         client.Flush();
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 17
0
        public async Task FlushAsync()
        {
            await SafeExecuteAsync(async() => {
                if (_client != null)
                {
                    _client.Flush();
                    _client = null;
                }

                await Task.Delay(1000);
            });
        }
Exemplo n.º 18
0
        public void TrackReportProcessed(string reportName, string packageId = null)
        {
            var telemetry = new MetricTelemetry(reportName, 1);

            if (!string.IsNullOrWhiteSpace(packageId))
            {
                telemetry.Properties.Add("Package Id", packageId);
            }

            _telemetryClient.TrackMetric(telemetry);
            _telemetryClient.Flush();
        }
Exemplo n.º 19
0
        public void Write(IEnumerable <LogEvent> events)
        {
            foreach (LogEvent e in events)
            {
                _context.Apply(e);
            }

            if (_options.FlushOnWrite)
            {
                _telemetryClient.Flush();
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// This method is called whenever an actor is activated.
        /// An actor is activated the first time any of its methods are invoked.
        /// </summary>
        protected override Task OnActivateAsync()
        {
            ActorEventSource.Current.ActorMessage(this, "Actor activated.");

            // The StateManager is this actor's private state store.
            // Data stored in the StateManager will be replicated for high-availability for actors that use volatile or persisted state storage.
            // Any serializable object can be saved in the StateManager.
            // For more information, see http://aka.ms/servicefabricactorsstateserialization

            m_tc.TrackEvent($"OnActivateAsync - {this.GetActorId().ToString()}");
            m_tc.Flush();
            return(this.StateManager.TryAddStateAsync("count", 0));
        }
Exemplo n.º 21
0
 public void LogError(Exception exception)
 {
     try
     {
         if (IsLogError)
         {
             Dictionary <string, string> exceptionDictionary = new Dictionary <string, string>();
             exceptionDictionary.Add("PreciseTimeStamp", DateTime.Now.Ticks.ToString());
             exceptionDictionary.Add("Error Message", exception.Message);
             foreach (DictionaryEntry exceptionData in exception.Data)
             {
                 exceptionDictionary.Add(exceptionData.Key.ToString(), exceptionData.Value.ToString());
             }
             exceptionDictionary.Add("LogFileName", logFileName);
             TelemetryClient.Context.Operation.Id = CorrelationId.ToString();
             TelemetryClient.TrackException(exception, exceptionDictionary);
             TelemetryClient.Flush();
         }
     }
     catch (LogMangerException)
     {
         throw;
     }
     catch (Exception)
     {
         // Empty catch, as it is used by global execption handler to log error. If some
         // exception is thrown from this method it will result in endless loop.
     }
 }
Exemplo n.º 22
0
        public void LabStarted(byte[] labData, string version, string osVersion, string psVersion)
        {
            if (!GetEnvironmentVariableAsBool(_telemetryOptInVar, false))
            {
                return;
            }
            var lab = Lab.Import(labData);

            lab.Machines.ForEach(m => SendUsedRole(m.Roles.Select(r => r.Name.ToString()).ToList()));
            lab.Machines.ForEach(m => SendUsedRole(m.PostInstallationActivity.Where(p => p.IsCustomRole).Select(c => System.IO.Path.GetFileNameWithoutExtension(c.ScriptFileName)).ToList(), true));

            var properties = new Dictionary <string, string>
            {
                { "version", version },
                { "hypervisor", lab.DefaultVirtualizationEngine },
                { "osversion", osVersion },
                { "psversion", psVersion }
            };

            var metrics = new Dictionary <string, double>
            {
                {
                    "machineCount", lab.Machines.Count
                }
            };

            labStarted = DateTime.Now;

            var eventMessage = "Lab started - Transmitting the following:" +
                               $"\r\nversion = {version}" +
                               $"\r\nhypervisor = {lab.DefaultVirtualizationEngine}" +
                               $"\r\nosversion = {osVersion}" +
                               $"\r\npsversion = {psVersion}" +
                               $"\r\nmachineCount = {lab.Machines.Count}";

            try
            {
                EventLog.WriteEntry("AutomatedLab", eventMessage, EventLogEntryType.Information, 101);
            }
            catch { }
            try
            {
                telemetryClient.TrackEvent("LabStarted", properties, metrics);
                telemetryClient.Flush();
            }
            catch
            {
                ; //nothing to catch. If it doesn't work, it doesn't work.
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Shuts down the Application Insights Logging functionality
        /// and flushes any pending requests.
        ///
        /// This handles start and stop times and the application lifetime
        /// log entry that logs duration of operation.
        /// </summary>
        public static void ShutdownLogging()
        {
            if (Configuration.System.SendTelemetry &&
                Telemetry.UseApplicationInsights &&
                AppInsights != null)
            {
                var t = AppRunTelemetry.Telemetry;

                // multi-instance shutdown - ignore
                if (t.Properties.ContainsKey("usage"))
                {
                    return;
                }

                t.Properties.Add("usage", Configuration.ApplicationUpdates.AccessCount.ToString());
                t.Properties.Add("registered", UnlockKey.IsAppRegistered().ToString());
                t.Properties.Add("version", GetVersion());
                t.Properties.Add("dotnetversion", MarkdownMonster.Utilities.mmWindowsUtils.GetDotnetVersion());
                t.Properties.Add("culture", CultureInfo.CurrentUICulture.IetfLanguageTag);
                t.Stop();

                try
                {
                    AppInsights.StopOperation(AppRunTelemetry);
                }
                catch (Exception ex)
                {
                    LogLocal("Failed to Stop Telemetry Client: " + ex.GetBaseException().Message);
                }

                AppInsights.Flush();
                AppInsights = null;
                AppRunTelemetry.Dispose();
            }
        }
Exemplo n.º 24
0
 public void Flush()
 {
     if (_telemetry != null)
     {
         _telemetry.Flush();
     }
 }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            //if (args.Length != 2)
            //{
            //    Console.WriteLine("AiPing.exe number aikey");
            //    Console.ReadLine();
            //    return;
            //}

            //int.TryParse(args[0], out int num);
            //string aikey = args[1];
            var num   = 5;
            var aikey = "d9781523-e0ba-4496-adb1-d080807ecc07";

            // set develop mode
            //TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;
            TelemetryConfiguration.Active.InstrumentationKey = aikey;
            var client = new TelemetryClient();

            client.Context.User.Id   = "AiPing";
            client.Context.Device.Id = System.Net.Dns.GetHostName();

            try
            {
                Console.WriteLine(DateTime.Now.ToUniversalTime());
                for (int i = 0; i < num; i++)
                {
                    var id = i + 1;
                    Console.WriteLine($"AiPing {id} Start:");

                    Trace.TraceInformation($"TraceInformation {id}.");
                    Trace.TraceWarning($"TraceWarning {id}.");
                    Trace.TraceError($"TraceError {id}.");
                    Console.WriteLine("\t Trace ping end.");

                    client.TrackTrace($"HelloWorld {id}!");
                    client.TrackEvent($"HelloWorld {id}!");
                    var properties = new Dictionary <string, string>
                    {
                        { "AiException", "AiException Text" }
                    };
                    var measurements = new Dictionary <string, double>
                    {
                        { "AiMeasure", 100.0 }
                    };
                    client.TrackException(new Exception($"AiException {id}"), properties, measurements);
                    Console.WriteLine("\t AI Ping end");
                    Thread.Sleep(1000);
                }
                Console.WriteLine("AiPing End.");
            }
            catch (Exception ex)
            {
                client.TrackException(ex);
                Console.WriteLine(ex.Message);
            }
            client.Flush();
            Task.Delay(5000);
            Console.ReadLine();
        }
Exemplo n.º 26
0
 public static void Flush()
 {
     if (tc != null)
     {
         tc.Flush();
     }
 }
Exemplo n.º 27
0
 private static void Application_Exit(object sender, System.Windows.ExitEventArgs e)
 {
     TrackEvent("AppExit");
     _client.Flush();
     // Allow time for flushing:
     System.Threading.Thread.Sleep(1000);
 }
 private void Flush()
 {
     lock (SyncTelemetryWrite)
     {
         telemetryClient.Flush();
     }
 }
Exemplo n.º 29
0
        public static void LogException(Exception ex)
        {
            if (ex is AggregateException)
            {
                var e = ex as AggregateException;
                foreach (var curE in e.Flatten().InnerExceptions)
                {
                    LogException(curE);
                }
            }
            else
            {
                // Log inner exceptions first
                if (ex.InnerException != null)
                {
                    LogException(ex.InnerException);
                }

                Log($"{ErrorLevel.Error} - {ex.Message}\r\n{ex.StackTrace}");

                if (Settings.Default.Telemetry == 1)
                {
                    var telex = new Microsoft.ApplicationInsights.DataContracts.ExceptionTelemetry(ex);
                    _telemetry?.TrackException(telex);
                    _telemetry?.Flush();
                }
            }
        }
Exemplo n.º 30
0
 private void OnBeginShutdown()
 {
     if (Enabled)
     {
         _client.Flush();
     }
 }