public override void OnException(ExceptionContext context)
        {
            base.OnException(context);

            if (context != null)
            {
                try
                {
                    if (context.HttpContext != null && context.Exception != null)
                    {
                        // If customError is Off, then AppInsights HTTP module will report the exception. If not, handle it explicitly.
                        // http://blogs.msdn.com/b/visualstudioalm/archive/2014/12/12/application-insights-exception-telemetry.aspx
                        if (context.HttpContext.IsCustomErrorEnabled)
                        {
                            var telemetryClient = new TelemetryClient();
                            telemetryClient.TrackException(context.Exception);
                        }
                    }
                }
                catch (Exception exception)
                {
                    context.Exception = new AggregateException("Failed to send exception telemetry.", exception, context.Exception);
                }
            }
        }
 public void ActorMessageFailed(
     string methodName,
     CodeEffect.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader headers,
     System.Exception ex)
 {
     WebApiServiceEventSource.Current.ActorMessageFailed(
         _context,
         methodName,
         headers,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "ActorMessageFailed" },
         { "ServiceName", _context.ServiceName.ToString() },
         { "ServiceTypeName", _context.ServiceTypeName },
         { "ReplicaOrInstanceId", _context.InstanceId.ToString() },
         { "PartitionId", _context.PartitionId.ToString() },
         { "ApplicationName", _context.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _context.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _context.NodeContext.NodeName },
         { "MethodName", methodName },
         { "User", headers?.GetHeader("name") },
         { "CorrelationId", headers?.GetHeader("correlation-id") },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
예제 #3
0
        public static bool SendMessage(ContactAttempt contactAttempt)
        {
            var telemetry = new TelemetryClient();
            bool success;
            try
            {
                var contactInfo = _contactInfoRepository.GetContactInfo(contactAttempt.ProfileId);
                MailMessage mailMessage = new MailMessage(contactAttempt.EmailAddress, contactInfo.EmailAddress, contactAttempt.Subject, contactAttempt.Message);

                var client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.UseDefaultCredentials = false;
                client.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MailUserName"], ConfigurationManager.AppSettings["MailPassword"]);
                client.Send(mailMessage);

                telemetry.TrackEvent("EmailSent", GetEmailSentTrackingProperties(contactAttempt, contactInfo));
                success = true;
            }
            catch(Exception ex)
            {
                telemetry.TrackException(ex);
                success = false;
            }
            return success;
        }
예제 #4
0
 public void RunAsyncLoopFailed(
     System.Exception ex)
 {
     PersonActorServiceEventSource.Current.RunAsyncLoopFailed(
         _actorService,
         _context,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "RunAsyncLoopFailed" },
         { "ActorType", _actorService.ActorTypeInformation.ImplementationType.ToString() },
         { "ApplicationTypeName", _actorService.Context.CodePackageActivationContext.ApplicationTypeName },
         { "ApplicationName", _actorService.Context.CodePackageActivationContext.ApplicationName },
         { "ServiceTypeName", _actorService.Context.ServiceTypeName },
         { "ServiceName", _actorService.Context.ServiceName.ToString() },
         { "PartitionId", _actorService.Context.PartitionId.ToString() },
         { "ReplicaOrInstanceId", _actorService.Context.ReplicaId.ToString() },
         { "NodeName", _actorService.Context.NodeContext.NodeName },
         { "CorrelationId", FG.ServiceFabric.Services.Remoting.FabricTransport.ServiceRequestContext.Current?["correlationId"] },
         { "UserId", FG.ServiceFabric.Services.Remoting.FabricTransport.ServiceRequestContext.Current?["userId"] },
         { "RequestUri", FG.ServiceFabric.Services.Remoting.FabricTransport.ServiceRequestContext.Current?["requestUri"] },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
예제 #5
0
        public void UnsupportedKeyError(
            System.Exception ex)
        {
            FGDiagnosticsAutoLoggerSamplesConsoleApplication1EventSource.Current.UnsupportedKeyError(
                _autogenerated,
                _machineName,
                ex
                );

            System.Diagnostics.Debug.WriteLine($"[ConsoleRunner, Error] ERR: UnsupportedKeyError");

            System.Diagnostics.Debug.WriteLine($"\t_autogenerated:\t{_autogenerated}");
            System.Diagnostics.Debug.WriteLine($"\tEnvironment.MachineName:\t{Environment.MachineName}");
            System.Diagnostics.Debug.WriteLine($"\tex.Message:\t{ex.Message}");
            System.Diagnostics.Debug.WriteLine($"\tex.Source:\t{ex.Source}");
            System.Diagnostics.Debug.WriteLine($"\tex.GetType().FullName:\t{ex.GetType().FullName}");
            System.Diagnostics.Debug.WriteLine($"\tex.AsJson():\t{ex.AsJson()}");
            _telemetryClient.TrackException(
                ex,
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "Name", "UnsupportedKeyError" },
                { "Autogenerated", _autogenerated.ToString() },
                { "MachineName", Environment.MachineName },
                { "Message", ex.Message },
                { "Source", ex.Source },
                { "ExceptionTypeName", ex.GetType().FullName },
                { "Exception", ex.AsJson() }
            });
        }
예제 #6
0
 public void ActorHostInitializationFailed(
     System.Exception ex)
 {
     PersonActorServiceEventSource.Current.ActorHostInitializationFailed(
         _actor,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "ActorHostInitializationFailed" },
         { "ActorType", _actor.ActorType.ToString() },
         { "ActorId", _actor.ActorId.ToString() },
         { "ApplicationTypeName", _actor.ApplicationTypeName },
         { "ApplicationName", _actor.ApplicationName },
         { "ServiceTypeName", _actor.ServiceTypeName },
         { "ServiceName", _actor.ToString() },
         { "PartitionId", _actor.PartitionId.ToString() },
         { "ReplicaOrInstanceId", _actor.ReplicaOrInstanceId.ToString() },
         { "NodeName", _actor.NodeName },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
        public void Error(
            System.Exception exception)
        {
            Sample.Current.Error(
                _actorId,
                _processId,
                _machineName,
                exception
                );

            System.Diagnostics.Debug.WriteLine($"[Console, Error] ERR: Error");

            System.Diagnostics.Debug.WriteLine($"\t_actorId.ToString():\t{_actorId.ToString()}");
            System.Diagnostics.Debug.WriteLine($"\t_actorId.Kind.ToString():\t{_actorId.Kind.ToString()}");
            System.Diagnostics.Debug.WriteLine($"\t_processId:\t{_processId}");
            System.Diagnostics.Debug.WriteLine($"\tEnvironment.MachineName:\t{Environment.MachineName}");
            System.Diagnostics.Debug.WriteLine($"\texception.Message:\t{exception.Message}");
            System.Diagnostics.Debug.WriteLine($"\texception.Source:\t{exception.Source}");
            System.Diagnostics.Debug.WriteLine($"\texception.GetType().FullName:\t{exception.GetType().FullName}");
            System.Diagnostics.Debug.WriteLine($"\texception.AsJson():\t{exception.AsJson()}");
            _telemetryClient.TrackException(
                exception,
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "Name", "Error" },
                { "ActorId", _actorId.ToString() },
                { "ActorIdType", _actorId.Kind.ToString() },
                { "ProcessId", _processId.ToString() },
                { "MachineName", Environment.MachineName },
                { "Message", exception.Message },
                { "Source", exception.Source },
                { "ExceptionTypeName", exception.GetType().FullName },
                { "Exception", exception.AsJson() }
            });
        }
		public override void OnException(ExceptionContext filterContext)
		{
			if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
			{
				//If customError is Off, then AI HTTPModule will report the exception
				if (filterContext.HttpContext.IsCustomErrorEnabled)
				{
					string email;
					try
					{
						email = filterContext.HttpContext.User.Identity.Name;
					}
					catch
					{
						email = "unknown";
					}

					var properties = new Dictionary<string, string>();
					properties.Add("AzureDayUserEmail", email);

					// Note: A single instance of telemetry client is sufficient to track multiple telemetry items.
					var ai = new TelemetryClient();
					ai.TrackException(filterContext.Exception, properties);
				}
			}
			base.OnException(filterContext);
		}
예제 #9
0
        public HttpResponseMessage RunJob()
        {
            var telemetry = new TelemetryClient();

            try
            {
                // トークンの削除
                var manager = TokenManager.GetInstance();
                manager.CleanExpiredToken();

                // 放送していないルームの削除
                using (var db = new ApplicationDbContext())
                {
                    var instance = RoomManager.GetInstance();
                    var liveRoom = db.Rooms.Where(c => c.IsLive);
                    foreach (var item in liveRoom)
                    {
                        if (instance.GetRoomInfo(item.Id) == null)
                        {
                            item.IsLive = true;
                        }
                    }
                    db.SaveChanges();
                }
                return Request.CreateResponse(HttpStatusCode.Accepted);
            }
            catch (Exception ex)
            {
                telemetry.TrackException(ex, new Dictionary<string, string>() { { "Method", "RunJob" } }, null);
                return Request.CreateResponse(HttpStatusCode.InternalServerError);
            }
        }
예제 #10
0
 public static void LogException(Exception ex)
 {
     if (TelemetryEnabled)
     {
         telemetry.TrackException(ex);
     }
 }
예제 #11
0
 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();
     }
 }
예제 #12
0
        protected void Application_Error()
        {
            var exception = Server.GetLastError();

            var telemetryClient = new TelemetryClient();

            telemetryClient.TrackException(exception);
        }
        bool IErrorHandler.HandleError(Exception error)
        {
            //or reuse instance (recommended!). see note above
            var ai = new TelemetryClient();

            ai.TrackException(error);
            return false;
        }
 public override void Log(ExceptionLoggerContext context)
 {
     if (context != null && context.Exception != null)
     {//or reuse instance (recommended!). see note above 
         var ai = new TelemetryClient();
         ai.TrackException(context.Exception);
     }
     base.Log(context);
 }
        /// <summary>
        /// Logs the unhandled exceptions.
        /// </summary>
        /// <param name="context">The exception logger context.</param>
        public override void Log(ExceptionLoggerContext context)
        {
            if (context?.Exception != null)
            {
                var telemetryClient = new TelemetryClient();
                telemetryClient.TrackException(context.Exception);
            }

            base.Log(context);
        }
예제 #16
0
 public override void Log(ExceptionLoggerContext context)
 {
     if (context != null && context.Exception != null)
     {
         // Note: A single instance of telemetry client is sufficient to track multiple telemetry items.
         var ai = new TelemetryClient();
         ai.TrackException(context.Exception);
     }
     base.Log(context);
 }
        private static DecisionServiceConfiguration CreateConfiguration(string settingsUrl)
        {
            var telemetry = new TelemetryClient();
            telemetry.TrackEvent($"DecisionServiceClient created: '{settingsUrl}'");

            return new DecisionServiceConfiguration(settingsUrl)
            {
                InteractionUploadConfiguration = new BatchingConfiguration
                {
                    // TODO: these are not production ready configurations. do we need to move those to C&C as well?
                    MaxBufferSizeInBytes = 1,
                    MaxDuration = TimeSpan.FromSeconds(1),
                    MaxEventCount = 1,
                    MaxUploadQueueCapacity = 1,
                    UploadRetryPolicy = BatchUploadRetryPolicy.ExponentialRetry
                },
                ModelPollFailureCallback = e => telemetry.TrackException(e, new Dictionary<string, string> { { "Pool failure", "model" } }),
                SettingsPollFailureCallback = e => telemetry.TrackException(e, new Dictionary<string, string> { { "Pool failure", "settings" } })
            };
        }
        /// <summary>
        /// Implement OnException method of IExceptionFilter which will be invoked
        /// for all unhandled exceptions
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            this._logger.LogError("MatterCenterExceptionFilter", context.Exception);
            var stackTrace = new StackTrace(context.Exception, true);
            StackFrame stackFrameInstance = null;

            if(stackTrace.GetFrames().Length>0)
            {
                for(int i=0; i< stackTrace.GetFrames().Length; i++)
                {
                    if(stackTrace.GetFrames()[i].ToString().Contains("Microsoft.Legal.Matter"))
                    {
                        stackFrameInstance = stackTrace.GetFrames()[i];
                        break;
                    }
                }
            }
            //Create custom exception response that needs to be send to client
            var response = new ErrorResponse()
            {
                Message = context.Exception.Message,
                StackTrace = context.Exception.ToString(),
                Description = "Error occured in the system. Please contact the administrator",
                //Exception = context.Exception.ToString(),
                LineNumber = stackFrameInstance?.GetFileLineNumber(),
                MethodName = stackFrameInstance?.GetMethod().Name,
                ClassName = stackFrameInstance?.GetMethod().DeclaringType.Name,
                ErrorCode = ((int)HttpStatusCode.InternalServerError).ToString()
            };

            //Create properties that need to be added to application insights
            var properties = new Dictionary<string, string>();
            properties.Add("StackTrace", response.StackTrace);
            properties.Add("LineNumber", response.LineNumber.ToString());
            properties.Add("MethodName", response.MethodName.ToString());
            properties.Add("ClassName", response.ClassName.ToString());
            properties.Add("ErrorCode", response.ErrorCode.ToString());           

            //Create Telemetry object to add exception to the application insights
            var ai = new TelemetryClient();
            ai.InstrumentationKey = instrumentationKey;
            if(ai.IsEnabled())
            {
                //add exception to the Application Insights
                ai.TrackException(context.Exception, properties);
            }           
            
            //Send the exceptin object to the client
            context.Result = new ObjectResult(response)
            {
                StatusCode = (int)HttpStatusCode.InternalServerError,
                DeclaredType = typeof(ErrorResponse)                
            };
        }
        public override void OnException(HttpActionExecutedContext context)
        {
            // Track Exceptions with Application Insights
            TelemetryClient telemetryClient = new TelemetryClient();
            telemetryClient.TrackException(context.Exception);

            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("An error occurred, please try again or contact the administrator."),
                ReasonPhrase = "Critical Exception"
            });
        }
예제 #20
0
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = this.Server.GetLastError();
            if (exception == null || exception is OperationCanceledException)
            {
                return;
            }

            // Track Exceptions with Application Insights
            TelemetryClient telemetryClient = new TelemetryClient();
            telemetryClient.TrackException(exception);
        }
예제 #21
0
 public void FailedToEnumeratePartitions(
     System.Uri serviceUri,
     System.Exception ex)
 {
     WebApiServiceEventSource.Current.FailedToEnumeratePartitions(
         _context,
         serviceUri,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "FailedToEnumeratePartitions" },
         { "ServiceName", _context.ServiceName.ToString() },
         { "ServiceTypeName", _context.ServiceTypeName },
         { "ReplicaOrInstanceId", _context.InstanceId.ToString() },
         { "PartitionId", _context.PartitionId.ToString() },
         { "ApplicationName", _context.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _context.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _context.NodeContext.NodeName },
         { "ServiceUri", serviceUri.ToString() },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
            {
                if (filterContext.HttpContext.IsCustomErrorEnabled)
                {
                    var ai = new TelemetryClient();
                    ai.TrackException(filterContext.Exception);
                }
            }

            base.OnException(filterContext);
        }
예제 #23
0
 public override void OnException(ExceptionContext filterContext)
 {
     if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
     {
         //If customError is Off, then AI HTTPModule will report the exception
         if (filterContext.HttpContext.IsCustomErrorEnabled)
         {   //or reuse instance (recommended!). see note above
             var ai = new TelemetryClient();
             ai.TrackException(filterContext.Exception);
         }
     }
     base.OnException(filterContext);
 }
예제 #24
0
        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;
            }
        }
 public override void OnException(ExceptionContext filterContext)
 {
     if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
     {
         //If customError is Off, then AI HTTPModule will report the exception
         //If it is On, or RemoteOnly (default) - then we need to explicitly track the exception
         if (filterContext.HttpContext.IsCustomErrorEnabled)
         {
             var ai = new TelemetryClient();
             ai.TrackException(filterContext.Exception);
         }
     }
     base.OnException(filterContext);
 }
예제 #26
0
        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 override void OnException(ExceptionContext filterContext)
 {
     if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
     {
         //If customError is Off, then AI HTTPModule will report the exception
         if (filterContext.HttpContext.IsCustomErrorEnabled)
         {
             // Note: A single instance of telemetry client is sufficient to track multiple telemetry items.
             var ai = new TelemetryClient();
             ai.TrackException(filterContext.Exception);
         }
     }
     base.OnException(filterContext);
 }
        public static DecisionServiceClient<string> AddOrGetExisting(Action<byte[]> modelSuccessNotifier)
        {
            return DecisionServiceStaticClient.AddOrGetExisting("single", _ =>
            {
                var telemetry = new TelemetryClient();
                string azureStorageConnectionString = ConfigurationManager.AppSettings[ApplicationMetadataStore.AKConnectionString];

                var storageAccount = CloudStorageAccount.Parse(azureStorageConnectionString);
                var blobClient = storageAccount.CreateCloudBlobClient();
                var settingsBlobContainer = blobClient.GetContainerReference(ApplicationBlobConstants.SettingsContainerName);
                var clientSettingsBlob = settingsBlobContainer.GetBlockBlobReference(ApplicationBlobConstants.LatestClientSettingsBlobName);

                //var settingsUrl = clientSettingsBlob.StorageUri.PrimaryUri.ToString();
                var settingsUrl = APIUtil.GetSettingsUrl();

                telemetry.TrackEvent($"DecisionServiceClient created: '{settingsUrl}'");

                var config = new DecisionServiceConfiguration(settingsUrl)
                {
                    InteractionUploadConfiguration = new BatchingConfiguration
                    {
                        // TODO: these are not production ready configurations. do we need to move those to C&C as well?
                        MaxBufferSizeInBytes = 1,
                        MaxDuration = TimeSpan.FromSeconds(1),
                        MaxEventCount = 1,
                        MaxUploadQueueCapacity = 1,
                        UploadRetryPolicy = BatchUploadRetryPolicy.ExponentialRetry
                    },
                    ModelPollSuccessCallback = modelSuccessNotifier,
                    ModelPollFailureCallback = e => telemetry.TrackException(e, new Dictionary<string, string> { { "Pool failure", "model" } }),
                    SettingsPollFailureCallback = e => telemetry.TrackException(e, new Dictionary<string, string> { { "Pool failure", "settings" } }),
                    AzureStorageConnectionString = ConfigurationManager.AppSettings[ApplicationMetadataStore.AKConnectionString]
                };

                return DecisionService.CreateJson(config);
            });
        }
 public override void Log(ExceptionLoggerContext context)
 {
     if (context != null && context.Exception != null)
     {
         /*
          * Please note: You do not need to construct a new TelemetryClient every time. 
          * Indeed, we recommend that you reuse a client instance.
          * You only need to create separate instances, when you need to initialize with different configuration
          * The default constructor without parameters, uses TelemetryConfiguration.Active
          */
         var ai = new TelemetryClient();
         ai.TrackException(context.Exception);
     }
     base.Log(context);
 }
        //透過HttpClient 去取得紫外線Open Data 
        public async Task<List<TaiwanCityUV>> GetTaiwanUVData()
        {

                List<TaiwanCityUV> taiwanUVData = new List<TaiwanCityUV>();

                string content = "";

                HttpClient httpClient = new HttpClient();
                try
                {
                    content = await httpClient.GetStringAsync(new Uri(TaiwanUVOpenDataUrl));

                    RawContent = content;
                    JsonArray jArray = JsonArray.Parse(content);
                    IJsonValue outValue;

                    string testContent = "";
                    foreach (var item in jArray)
                    {
                        JsonObject obj = item.GetObject();
                        // Assume there is a “backgroundImage” column coming back
                        if (obj.TryGetValue("SiteName", out outValue))
                        {
                            testContent += outValue.GetString() + " ";
                        }


                    }
                    RawContent = testContent;
                    RawContent = "There are " + taiwanUVData.Count + " " + RawContent;

                    taiwanUVData=DeserializeTaiwanUVJason(content);                  
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message+ " "+ ex.StackTrace);

                    var telemetry = new TelemetryClient();
                    telemetry.TrackException(ex);
                            
            }

            // Once your app is done using the HttpClient object call dispose to 

            httpClient.Dispose();
            return taiwanUVData;

        }
        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 IHttpActionResult GetProduct(int id)
        {
            // pretend there was a failure if input id is a certain value
            if (id == 5)
            {
                var c = new TelemetryClient();
                c.TrackException(new ApplicationException("Something went wrong"));
                throw new ApplicationException("Something went wrong");
            }

            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
예제 #33
0
 public override void Log(ExceptionLoggerContext context)
 {
     if (context != null && context.Exception != null)
     {
         var ai = new TelemetryClient();
         ai.InstrumentationKey = RoleEnvironment.GetConfigurationSettingValue("APPINSIGHTS_INSTRUMENTATIONKEY");
         ai.TrackException(context.Exception);
         //ai.TrackEvent("custom event name");
         //Dictionary<string,string> customMetricDictionary=new Dictionary<string,string>();
         //customMetricDictionary.Add("custom metric key","custom metric value");
         //ai.TrackMetric("custom metric", 25, customMetricDictionary);
         //ai.TrackRequest("custom request", DateTimeOffset.Now, new TimeSpan(0, 0, 5), "500", false);
         //ai.TrackPageView("custom page view");
         //ai.TrackDependency("custom dependency name", "custom command name", DateTimeOffset.UtcNow, new TimeSpan(0, 0, 5), false);
     }
     base.Log(context);
 }
예제 #34
0
        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 override void OnException(ExceptionContext filterContext)
 {
     if (filterContext != null && filterContext.HttpContext != null && filterContext.Exception != null)
     {
         //If customError is Off, then AI HTTPModule will report the exception
         if (filterContext.HttpContext.IsCustomErrorEnabled)
         {   
             /*
             * Please note: You do not need to construct a new TelemetryClient every time. 
             * Indeed, we recommend that you reuse a client instance.
             * You only need to create separate instances, when you need to initialize with different configuration
             * The default constructor without parameters, uses TelemetryConfiguration.Active
             */
             var ai = new TelemetryClient();
             ai.TrackException(filterContext.Exception);
         } 
     }
     base.OnException(filterContext);
 }
예제 #36
0
        // GET api/values/5
        public Object Get(int id)
        {
            Invocations++;
            Trace.TraceInformation("Otro cliente al que atender.");
            if (id < 10)
            {   var ex = new ArgumentException("Requerida una precisión superior a 10.");

                // Telemetría para App Insights
                var telemetry = new TelemetryClient();
                var telemetryInfo = new Dictionary<string, string>
                { { "invocaciones", Convert.ToString(Invocations) } };
                var telemetryMeasurements = new Dictionary<string, double>
                { { "digitos", id } };
                telemetry.TrackException(ex, telemetryInfo, telemetryMeasurements);

                // Mensaje para Applications Logs
                Trace.TraceError("El cliente anda despistado.");

                throw ex;
            }
            BigNumber x = new BigNumber(id);
            BigNumber y = new BigNumber(id);
            x.ArcTan(16, 5);
            y.ArcTan(4, 239);
            x.Subtract(y);

            string pi = x.AsPrintableString();

            if (pi.Length > 1000)
            {
                Trace.TraceWarning("Resultado de " + pi.Length + " caracteres!");
            }

            var resultado = new
            {
                pi = pi,
                invocations = Invocations
            };

            return resultado;
        }
    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");
    }
예제 #38
0
 public void UnsupportedKeyError(
     System.Exception ex)
 {
     DefaultEventSource.Current.UnsupportedKeyError(
         _processId,
         _machineName,
         _actorId,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "UnsupportedKeyError" },
         { "ProcessId", _processId.ToString() },
         { "MachineName", Environment.MachineName },
         { "Actor", _actorId.ToString() },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
        public override void WriteLine(string message)
        {
            //// Note: A single instance of telemetry client is sufficient to track multiple telemetry items.
            //var ai = new TelemetryClient();
            //ai.TrackException(filterContext.Exception);
            //var ai = new TelemetryClient();
            //var trace = new TraceTelemetry("test2 " + message);
            //trace.SeverityLevel = SeverityLevel.Critical;
            //ai.Track(trace);

            try
            {
                throw new Exception("error2" + message);
            }
            catch (Exception exc)
            {
                var telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
                telemetry.TrackTrace("anders test", SeverityLevel.Error);

                telemetry.TrackTrace("Slow database response",
                                     SeverityLevel.Warning,
                                     new System.Collections.Generic.Dictionary <string, string> {
                    { "database", "1111" }
                });
                telemetry.TrackException(exc);
            }


            //var storageAccount = CloudStorageAccount.Parse(Startup.Configuration.GetConnectionString("AzureWebJobsStorage"));
            //var blobClient = storageAccount.CreateCloudBlobClient();
            //var logBlobContainer = blobClient.GetContainerReference("websitelog");
            //logBlobContainer.CreateIfNotExists();

            //var now = DateTime.Now;
            //var logBlob = logBlobContainer.GetBlockBlobReference($"{now.Year.ToString("D4")}/{now.Month.ToString("D2")}/{now.Day.ToString("D2")} {now.Hour.ToString("D2")}:{now.Minute.ToString("D2")}:{now.Second.ToString("D2")};{now.Millisecond} ERROR");
            //logBlob.UploadText(message);
        }
예제 #40
0
 public void RecieveWebApiRequestFailed(
     System.Uri requestUri,
     string payload,
     string correlationId,
     string userId,
     System.Exception exception)
 {
     WebApiServiceEventSource.Current.RecieveWebApiRequestFailed(
         _context,
         requestUri,
         payload,
         correlationId,
         userId,
         exception
         );
     _telemetryClient.TrackException(
         exception,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "RecieveWebApiRequestFailed" },
         { "ServiceName", _context.ServiceName.ToString() },
         { "ServiceTypeName", _context.ServiceTypeName },
         { "ReplicaOrInstanceId", _context.InstanceId.ToString() },
         { "PartitionId", _context.PartitionId.ToString() },
         { "ApplicationName", _context.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _context.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _context.NodeContext.NodeName },
         { "RequestUri", requestUri.ToString() },
         { "Payload", payload },
         { "CorrelationId", correlationId },
         { "UserId", userId },
         { "Message", exception.Message },
         { "Source", exception.Source },
         { "ExceptionTypeName", exception.GetType().FullName },
         { "Exception", exception.AsJson() }
     });
 }
예제 #41
0
 public void RecieveServiceMessageFailed(
     System.Uri requestUri,
     string serviceMethodName,
     Microsoft.ServiceFabric.Services.Remoting.ServiceRemotingMessageHeaders serviceMessageHeaders,
     FG.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader customServiceRequestHeader,
     System.Exception ex)
 {
     TitleActorServiceEventSource.Current.RecieveServiceMessageFailed(
         _context,
         requestUri,
         serviceMethodName,
         serviceMessageHeaders,
         customServiceRequestHeader,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "RecieveServiceMessageFailed" },
         { "ServiceName", _context.ServiceName.ToString() },
         { "ServiceTypeName", _context.ServiceTypeName },
         { "ReplicaOrInstanceId", _context.ReplicaOrInstanceId.ToString() },
         { "PartitionId", _context.PartitionId.ToString() },
         { "ApplicationName", _context.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _context.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _context.NodeContext.NodeName },
         { "RequestUri", requestUri.ToString() },
         { "ServiceMethodName", serviceMethodName },
         { "InterfaceId", (serviceMessageHeaders?.InterfaceId ?? 0).ToString() },
         { "MethodId", (serviceMessageHeaders?.MethodId ?? 0).ToString() },
         { "UserId", customServiceRequestHeader?.GetHeader("userId") },
         { "CorrelationId", customServiceRequestHeader?.GetHeader("correlationId") },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
예제 #42
0
        public void Error(
            System.Exception exception)
        {
            Sample.Current.Error(
                exception
                );

            System.Diagnostics.Debug.WriteLine($"[Console, Error] ERR: Error");

            System.Diagnostics.Debug.WriteLine($"\texception.Message:\t{exception.Message}");
            System.Diagnostics.Debug.WriteLine($"\texception.Source:\t{exception.Source}");
            System.Diagnostics.Debug.WriteLine($"\texception.GetType().FullName:\t{exception.GetType().FullName}");
            System.Diagnostics.Debug.WriteLine($"\texception.AsJson():\t{exception.AsJson()}");
            _telemetryClient.TrackException(
                exception,
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "Name", "Error" },
                { "Message", exception.Message },
                { "Source", exception.Source },
                { "ExceptionTypeName", exception.GetType().FullName },
                { "Exception", exception.AsJson() }
            });
        }
예제 #43
0
 /// <summary>
 /// Log and track custom app insights exception event with global common properities
 /// See https://azure.microsoft.com/en-us/documentation/articles/app-insights-api-custom-events-metrics/#api-summary
 /// </summary>
 /// <param name="exception"></param>
 /// <param name="properties"></param>
 internal static void TrackException(Exception exception, IDictionary <string, string> properties)
 {
     // add common properties
     AddCommonProperties(ref properties);
     _TelemetryClient.TrackException(exception, properties);
 }
예제 #44
0
 public void RecieveActorMessageFailed(
     System.Uri requestUri,
     string actorMethodName,
     FG.ServiceFabric.Actors.Remoting.Runtime.ActorMessageHeaders actorMessageHeaders,
     FG.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader customServiceRequestHeader,
     System.Exception ex)
 {
     PersonActorServiceEventSource.Current.RecieveActorMessageFailed(
         _actor,
         requestUri,
         actorMethodName,
         actorMessageHeaders,
         customServiceRequestHeader,
         ex
         );
     _telemetryClient.TrackException(
         ex,
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "Name", "RecieveActorMessageFailed" },
         { "ActorType", _actor.ActorType.ToString() },
         { "ApplicationTypeName", _actor.ApplicationTypeName },
         { "ApplicationName", _actor.ApplicationName },
         { "ServiceTypeName", _actor.ServiceTypeName },
         { "ServiceName", _actor.ToString() },
         { "PartitionId", _actor.PartitionId.ToString() },
         { "ReplicaOrInstanceId", _actor.ReplicaOrInstanceId.ToString() },
         { "NodeName", _actor.NodeName },
         { "RequestUri", requestUri.ToString() },
         { "ActorMethodName", actorMethodName },
         { "InterfaceId", (actorMessageHeaders?.InterfaceId ?? 0).ToString() },
         { "MethodId", (actorMessageHeaders?.MethodId ?? 0).ToString() },
         { "ActorId", actorMessageHeaders?.ActorId.ToString() },
         { "UserId", customServiceRequestHeader?.GetHeader("userId") },
         { "CorrelationId", customServiceRequestHeader?.GetHeader("correlationId") },
         { "Message", ex.Message },
         { "Source", ex.Source },
         { "ExceptionTypeName", ex.GetType().FullName },
         { "Exception", ex.AsJson() }
     });
 }
예제 #45
-1
        public async Task<HttpResponseMessage> Post(string eventId)
        {
            var userToken = Request.Headers.SingleOrDefault(x => x.Key == "Authorization").Value.First();
            if (string.IsNullOrWhiteSpace(userToken))
                return Request.CreateResponse(HttpStatusCode.Forbidden);
            if (userToken != ConfigurationManager.AppSettings["UserToken"])
                return Request.CreateResponse(HttpStatusCode.Unauthorized);

            var telemetry = new TelemetryClient();
            var stopwatch = Stopwatch.StartNew();

            try
            {
                telemetry.Context.Operation.Name = "Reward";
                telemetry.Context.Operation.Id = eventId;

                // support simply float and complex JSON outcomes
                var rewardStr = await Request.Content.ReadAsStringAsync();
                var rewardObj = JToken.Parse(rewardStr);

                // parse input
                var guid = Guid.ParseExact(eventId, "N");

                var url = ConfigurationManager.AppSettings["DecisionServiceSettingsUrl"];
                var eventUploader = DecisionServiceStaticClient.AddOrGetExisting("uploader" + url,
                    _ =>
                    {
                        telemetry.TrackEvent("EventUploader creation");
                                               
                        var metaData = ApplicationMetadataUtil.DownloadMetadata<ApplicationClientMetadata>(url);
                        return new EventUploaderASA(
                            metaData.EventHubObservationConnectionString,
                            new BatchingConfiguration
                            {
                            // TODO: these are not production ready configurations. do we need to move those to C&C as well?
                            MaxBufferSizeInBytes = 1,
                                MaxDuration = TimeSpan.FromSeconds(1),
                                MaxEventCount = 1,
                                MaxUploadQueueCapacity = 1,
                                UploadRetryPolicy = BatchUploadRetryPolicy.ExponentialRetry
                            });
                    });

                eventUploader.Upload(new Observation
                {
                    Key = guid.ToString("N", CultureInfo.InvariantCulture),
                    Value = rewardObj
                });

                stopwatch.Stop();
                telemetry.TrackRequest("ReportReward", DateTime.Now, stopwatch.Elapsed, "200", true);

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch(Exception e)
            {
                telemetry.TrackException(e);
                return Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
            }
        }