public void SayHello(
            string message)
        {
            Sample.Current.SayHello(
                _actorId,
                _processId,
                _machineName,
                message
                );

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

            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($"\tmessage:\t{message}");
            _telemetryClient.TrackEvent(
                nameof(SayHello),
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "ActorId", _actorId.ToString() },
                { "ActorIdType", _actorId.Kind.ToString() },
                { "ProcessId", _processId.ToString() },
                { "MachineName", Environment.MachineName },
                { "Message", message }
            });
        }
        public void RunnerCreated(
            )
        {
            Sample.Current.RunnerCreated(
                _processId,
                _machineName,
                _actorId
                );

            System.Diagnostics.Debug.WriteLine($"[ConsoleRunner] ERR: RunnerCreated");

            System.Diagnostics.Debug.WriteLine($"\t_processId:\t{_processId}");
            System.Diagnostics.Debug.WriteLine($"\tEnvironment.MachineName:\t{Environment.MachineName}");
            System.Diagnostics.Debug.WriteLine($"\t_actorId.ToString():\t{_actorId.ToString()}");
            System.Diagnostics.Debug.WriteLine($"\t_actorId.Kind.ToString():\t{_actorId.Kind.ToString()}");
            _telemetryClient.TrackEvent(
                nameof(RunnerCreated),
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "ProcessId", _processId.ToString() },
                { "MachineName", Environment.MachineName },
                { "ActorId", _actorId.ToString() },
                { "ActorIdType", _actorId.Kind.ToString() }
            });
        }
Пример #3
0
 public void PersonActivated(
     string name,
     string title)
 {
     PersonActorServiceEventSource.Current.PersonActivated(
         _actor,
         _context,
         name,
         title
         );
     _telemetryClient.TrackEvent(
         nameof(PersonActivated),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "ActorType", _actor.GetType().ToString() },
         { "ActorId", _actor.Id.ToString() },
         { "ApplicationTypeName", _actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName },
         { "ApplicationName", _actor.ActorService.Context.CodePackageActivationContext.ApplicationName },
         { "ServiceTypeName", _actor.ActorService.Context.ServiceTypeName },
         { "ServiceName", _actor.ActorService.Context.ServiceName.ToString() },
         { "PartitionId", _actor.ActorService.Context.PartitionId.ToString() },
         { "ReplicaOrInstanceId", _actor.ActorService.Context.ReplicaId.ToString() },
         { "NodeName", _actor.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"] },
         { "Name", name },
         { "Title", title }
     });
 }
Пример #4
0
 public void PersonActivated(
     string name,
     string title)
 {
     PersonActorServiceEventSource.Current.PersonActivated(
         _actor,
         _correlationId,
         _message,
         name,
         title
         );
     _telemetryClient.TrackEvent(
         nameof(PersonActivated),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "ActorType", _actor.GetType().ToString() },
         { "ActorId", _actor.Id.ToString() },
         { "ApplicationTypeName", _actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName },
         { "ApplicationName", _actor.ActorService.Context.CodePackageActivationContext.ApplicationName },
         { "ServiceTypeName", _actor.ActorService.Context.ServiceTypeName },
         { "ServiceName", _actor.ActorService.Context.ServiceName.ToString() },
         { "PartitionId", _actor.ActorService.Context.PartitionId.ToString() },
         { "ReplicaOrInstanceId", _actor.ActorService.Context.ReplicaId.ToString() },
         { "NodeName", _actor.ActorService.Context.NodeContext.NodeName },
         { "CorrelationId", _correlationId.ToString() },
         { "Message", _message },
         { "Name", name },
         { "Title", title }
     });
 }
Пример #5
0
        public void RunnerCreated(
            )
        {
            Sample.Current.RunnerCreated(

                );

            System.Diagnostics.Debug.WriteLine($"[ConsoleRunner] ERR: RunnerCreated");

            _telemetryClient.TrackEvent(
                nameof(RunnerCreated),
                new System.Collections.Generic.Dictionary <string, string>()
            {
            });
        }
Пример #6
0
 public void UpdateTitle(
     string person,
     string title)
 {
     TitleActorServiceEventSource.Current.UpdateTitle(
         _serviceContext,
         _requestContext,
         person,
         title
         );
     _telemetryClient.TrackEvent(
         nameof(UpdateTitle),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "ServiceName", _serviceContext.ServiceName.ToString() },
         { "ServiceTypeName", _serviceContext.ServiceTypeName },
         { "ReplicaOrInstanceId", _serviceContext.ReplicaOrInstanceId.ToString() },
         { "PartitionId", _serviceContext.PartitionId.ToString() },
         { "ApplicationName", _serviceContext.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _serviceContext.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _serviceContext.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"] },
         { "Person", person },
         { "Title", title }
     });
 }
Пример #7
0
        private async void kameraBtn_Click(object sender, RoutedEventArgs e)
        {
            ApplicationView.GetForCurrentView().TitleBar.BackgroundColor = Colors.Red; // Uygulamanın title barı kırmızı olur
            ApplicationView.GetForCurrentView().IsScreenCaptureEnabled = false; // Ekran screen shoot alınamaz.


            var client = new TelemetryClient();

            client.TrackEvent("ResimCekButonunaTiklandi");

            var camera = new CameraCaptureUI();

            camera.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
            camera.PhotoSettings.AllowCropping = true;

            var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);

            // resmi azure'a upload etmek için önce WindowsAzure.Storage 'ı nugetten ekle
            // var acount= CloudStorageAccount.Parse("");
            // var blobClient = account.CreateCloudBlobClient();
            // var folder = blobClient.GetBlockBlobReference("images");
            // burada azure'da blob'un içinde images klasorunde profile.jpg adında bir alan oluşturup çekilen fotoğraf buraya upload edilir.
            // var blobFile = folder.GetBlockBlobReference("profile.jpg");
            // blobFile.UploadFromFileAsync(file);
        }
Пример #8
0
        public ActionResult Redirect(string id)
        {
            string subdomain = (string)Request.RequestContext.RouteData.Values["subdomain"];

            if (subdomain == null ||
                subdomain == "vso")
            {
                throw new HttpException(400, "Bad Request");
            }

            int number = 0;
            if (int.TryParse(id, out number) == false)
            {
                throw new HttpException(400, "Bad Request");
            }

            TelemetryClient telemetry = new TelemetryClient();
            telemetry.TrackEvent("Redirect", new Dictionary<string, string> {
                { "Account", subdomain },
                { "Work Item", id }
            });

            Response.StatusCode = 302;
            Response.RedirectLocation = String.Format("https://{0}.visualstudio.com/DefaultCollection/_workitems/edit/{1}", subdomain, number);

            return new ContentResult();
        }
Пример #9
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;
        }
Пример #10
0
 public void RunnerCreated(
     )
 {
     DefaultEventSource.Current.RunnerCreated(
         _processId,
         _machineName,
         _actorId
         );
     _telemetryClient.TrackEvent(
         nameof(RunnerCreated),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "ProcessId", _processId.ToString() },
         { "MachineName", Environment.MachineName },
         { "Actor", _actorId.ToString() }
     });
 }
Пример #11
0
        public void SayHello(
            string message)
        {
            Sample.Current.SayHello(
                message
                );

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

            System.Diagnostics.Debug.WriteLine($"\tmessage:\t{message}");
            _telemetryClient.TrackEvent(
                nameof(SayHello),
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "Message", message }
            });
        }
Пример #12
0
 /// <summary>
 /// Reports an event with a string data to the telemetry system.
 /// </summary>
 /// <param name="eventName"></param>
 public void ReportEvent(object component, string eventName, string data)
 {
     TelemetryClient client = new TelemetryClient();
     EventTelemetry eventT = new EventTelemetry();
     eventT.Name = component.GetType().Name + ":" + eventName;
     eventT.Properties.Add("data", data);
     client.TrackEvent(eventName);
 }
 public void ActorMessageDispatched(
     string methodName,
     CodeEffect.ServiceFabric.Services.Remoting.FabricTransport.CustomServiceRequestHeader headers)
 {
     WebApiServiceEventSource.Current.ActorMessageDispatched(
         _context,
         methodName,
         headers
         );
     _telemetryClient.TrackEvent(
         nameof(ActorMessageDispatched),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "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") }
     });
 }
Пример #14
0
        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);
            }
        }
Пример #15
0
        public static async Task<string> FindSidAsync(IPrincipal claimsPrincipal, HttpRequestMessage request)
        {
            var aiTelemetry = new TelemetryClient();
            var principal = claimsPrincipal as ClaimsPrincipal;
            if (principal == null)
            {
                aiTelemetry.TrackEvent("FindSidAsync: ClaimsPrincipal is null!");
                return string.Empty;
            }

            var match = principal.FindFirst("http://schemas.microsoft.com/identity/claims/identityprovider");
            string provider;
            if (match != null)
                provider = match.Value;
            else
            {
                aiTelemetry.TrackEvent("FindSidAsync: Can't find identity provider");
                return string.Empty;
            }

            ProviderCredentials creds = null;
            if (string.Equals(provider, "facebook", StringComparison.OrdinalIgnoreCase))
            {
                creds = await claimsPrincipal.GetAppServiceIdentityAsync<FacebookCredentials>(request);
            }
            else if (string.Equals(provider, "microsoftaccount", StringComparison.OrdinalIgnoreCase))
            {
                creds = await claimsPrincipal.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(request);
            }
            else if (string.Equals(provider, "twitter", StringComparison.OrdinalIgnoreCase))
            {
                creds = await claimsPrincipal.GetAppServiceIdentityAsync<TwitterCredentials>(request);
            }

            if (creds == null)
            {
                aiTelemetry.TrackEvent("FindSidAsync: Credentials not found");
                return string.Empty;
            }

            return creds.UserId;
        }
Пример #16
0
        public void RunnerCreated(
            )
        {
            FGDiagnosticsAutoLoggerSamplesConsoleApplication1EventSource.Current.RunnerCreated(
                _autogenerated,
                _machineName
                );

            System.Diagnostics.Debug.WriteLine($"[ConsoleRunner] ERR: RunnerCreated");

            System.Diagnostics.Debug.WriteLine($"\t_autogenerated:\t{_autogenerated}");
            System.Diagnostics.Debug.WriteLine($"\tEnvironment.MachineName:\t{Environment.MachineName}");
            _telemetryClient.TrackEvent(
                nameof(RunnerCreated),
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "Autogenerated", _autogenerated.ToString() },
                { "MachineName", Environment.MachineName }
            });
        }
        public SynchronizerBase(Configuration config, TelemetryClient telemetryClient)
        {
            if(telemetryClient == null)
                throw new ArgumentNullException("Telemetry client cannot be null.");

            _telemetryClient = telemetryClient;
            _config = config;
            _amazonClient = new AmazonUtilities(_config.AmazonAccessKey, _config.AmazonSecretKey, _config.AmazonAssociateTag);
            _watch = new Stopwatch();
            _telemetryClient.TrackEvent("Synchronization System Initialized ...");
        }
 public static void LogEvent(string eventName, Dictionary<string, string> events)
 {
     try
     {
         var tc = new TelemetryClient();
         tc.TrackEvent(eventName, events);
     }
     catch (Exception)
     {
         // Ignore errors? From logs? :\
     }
 }
 public void RunAsyncWorkCompleted(
     int iteration)
 {
     DefaultEventSource.Current.RunAsyncWorkCompleted(
         _context,
         iteration
         );
     _telemetryClient.TrackEvent(
         nameof(RunAsyncWorkCompleted),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "ServiceName", _context.ServiceName.ToString() },
         { "ServiceTypeName", _context.ServiceTypeName },
         { "ReplicaOrInstanceId", _context.GetReplicaOrInstanceId().ToString() },
         { "PartitionId", _context.PartitionId.ToString() },
         { "ApplicationName", _context.CodePackageActivationContext.ApplicationName },
         { "ApplicationTypeName", _context.CodePackageActivationContext.ApplicationTypeName },
         { "NodeName", _context.NodeContext.NodeName },
         { "Iteration", iteration.ToString() }
     });
 }
Пример #20
0
 /// <summary>
 /// Reports an event that might need to be looked at, an unexpected event.
 /// </summary>
 /// <param name="eventName"></param>
 public void ReportUnExpectedEvent(object component, string eventName, Exception excpetion = null)
 {
     TelemetryClient client = new TelemetryClient();
     EventTelemetry eventT = new EventTelemetry();
     eventT.Name = component.GetType().Name + ":" + eventName;
     eventT.Properties.Add("error", "unexpected");
     if(excpetion != null)
     {
         eventT.Properties.Add("exception", excpetion.Message);
     }
     client.TrackEvent(eventName);
 }
Пример #21
0
 public void EnumeratingPartitions(
     System.Uri serviceUri)
 {
     WebApiServiceEventSource.Current.EnumeratingPartitions(
         _context,
         serviceUri
         );
     _telemetryClient.TrackEvent(
         nameof(EnumeratingPartitions),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "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() }
     });
 }
 public void LogIncreaseHealth(Uri endpoint, int health)
 {
     var telemetryClient = new TelemetryClient();
     telemetryClient.TrackEvent("Endpoint Health Changed",
         new Dictionary<string, string>()
         {
             {"Endpoint", endpoint.ToString()},
             {"Event", "Increase"}
         }, new Dictionary<string, double>()
         {
             {"Endpoint Health", health}
         });
 }
Пример #23
0
 public MainPage()
 {
     //test for network connectivity
     this.InitializeComponent();
     methodLibrary mlibrary = new methodLibrary();
     //Debug.WriteLine("ConnectionProfile Info : " + networkInfo);
     try
     {
         Package pack = Package.Current;
         PackageId packId = pack.Id;
         PackageVersion packVer = packId.Version;
         string appver = String.Format("{0}.{1}.{2}.{3}", packVer.Major, packVer.Minor, packVer.Build, packVer.Revision);
         if (ApplicationData.Current.LocalSettings.Values["AppVersion"] == null)
         {
             ApplicationData.Current.LocalSettings.Values["POSTCallMade"] = true;
             ApplicationData.Current.LocalSettings.Values["RefreshClicked"] = "true";
             ApplicationData.Current.LocalSettings.Values["AppVersion"] = appver;
         }
         else if ((string)ApplicationData.Current.LocalSettings.Values["AppVersion"] != appver)
         {
             ApplicationData.Current.LocalSettings.Values["POSTCallMade"] = true;
             ApplicationData.Current.LocalSettings.Values["RefreshClicked"] = "true";
             ApplicationData.Current.LocalSettings.Values["AppVersion"] = appver;
         }
         Debug.WriteLine("File.Exists" + File.Exists("fileUserClass.txt"));
         Debug.WriteLine("isNullOrEmpty :" + String.IsNullOrEmpty((string)ApplicationData.Current.LocalSettings.Values["Tokens"]));
         if (methodLibrary.checkNetworkConnectivity())
         {
             if (String.IsNullOrEmpty((string)ApplicationData.Current.LocalSettings.Values["Tokens"]))
             {
                 //mlibrary.writeToLogFile((DateTime.UtcNow).ToString() + ": Token doesn't exist. Navigating to SignIn page");
                 RootPage.Navigate(typeof(signin));
             }
             else
             {
                 Debug.WriteLine("in mainpage : " + ApplicationData.Current.LocalSettings.Values["Tokens"]);
                 //mlibrary.writeToLogFile((DateTime.UtcNow).ToString() + ": Token exists. Navigating to Dashboard page");
                 RootPage.Navigate(typeof(Dashboard));
             }
         }
         else
             networkProblems.Visibility = Visibility.Visible;
     }
     catch (Exception ex)
     {
         //mlibrary.writeToLogFile((DateTime.UtcNow).ToString() + ": Exception in MainPage.xaml.cs");
         var tc = new TelemetryClient();
         tc.TrackEvent("MainPage Exception : " + ex);
     }
 }
Пример #24
0
 public void EnumeratingPartitions(
     System.Uri serviceUri)
 {
     PersonActorServiceEventSource.Current.EnumeratingPartitions(
         _actor,
         serviceUri
         );
     _telemetryClient.TrackEvent(
         nameof(EnumeratingPartitions),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "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 },
         { "ServiceUri", serviceUri.ToString() }
     });
 }
Пример #25
0
        public void SayHello(
            string message)
        {
            FGDiagnosticsAutoLoggerSamplesConsoleApplication1EventSource.Current.SayHello(
                _autogenerated,
                _machineName,
                message
                );

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

            System.Diagnostics.Debug.WriteLine($"\t_autogenerated:\t{_autogenerated}");
            System.Diagnostics.Debug.WriteLine($"\tEnvironment.MachineName:\t{Environment.MachineName}");
            System.Diagnostics.Debug.WriteLine($"\tmessage:\t{message}");
            _telemetryClient.TrackEvent(
                nameof(SayHello),
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "Autogenerated", _autogenerated.ToString() },
                { "MachineName", Environment.MachineName },
                { "Message", message }
            });
        }
        public void LogDecreaseHealth(Uri endpoint, int health, Exception exception)
        {
            var telemetryClient = new TelemetryClient();
            telemetryClient.TrackEvent("Endpoint Health Changed",
                new Dictionary<string, string>()
                {
                    {"Endpoint", endpoint.ToString()},
                    {"Event", "Decrease"}
                }, new Dictionary<string, double>()
                {
                    {"Endpoint Health", health}
                });

            QuietLog.LogHandledException(exception);
        }
Пример #27
0
        public App()
        {
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            _kernel = new StandardKernel(new Scratch.Common.Module(), new AppModule());

            var telemetryClient = new TelemetryClient();
            telemetryClient.InstrumentationKey = "2a8f2947-dfe9-48ef-8c8d-13184f9e46f9";
            telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
            telemetryClient.Context.Device.Language = Thread.CurrentThread.CurrentUICulture.Name;
            telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.VersionString;
            telemetryClient.Context.Device.ScreenResolution = string.Format("{0}x{1}", SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight);
            telemetryClient.Context.Component.Version = typeof(App).Assembly.GetName().Version.ToString();
            telemetryClient.TrackEvent("Application Start");
            _kernel.Bind<TelemetryClient>().ToConstant(telemetryClient).InSingletonScope();
        }
Пример #28
0
        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");
        }
Пример #30
0
        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();
        }
 public async static Task SendMessageDialogAsync(string message, bool isSuccess)
 {
     var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
     var title = isSuccess ? loader.GetString("SuccessText/Text") : loader.GetString("ErrorText/Text");
     var dialog = new MessageDialog((string.Concat(title, Environment.NewLine, Environment.NewLine, message)));
     await dialog.ShowAsync();
     if (!isSuccess)
     {
         try
         {
             var tc = new TelemetryClient();
             var prop = new Dictionary<string, string> { { "errorMessage", message } };
             tc.TrackEvent("Error", prop);
         }
         catch (Exception)
         {
             // Ignore analytics failing. :\
         }
     }
 }
        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" } })
            };
        }
Пример #33
0
        public void ActivatingService(
            )
        {
            FGDiagnosticsAutoLoggerSamplesConsoleApplication1EventSource.Current.ActivatingService(
                _autogenerated,
                _machineName
                );

            System.Diagnostics.Debug.WriteLine($"[Infrastructure] ERR: ActivatingService");

            System.Diagnostics.Debug.WriteLine($"\t_autogenerated:\t{_autogenerated}");
            System.Diagnostics.Debug.WriteLine($"\tEnvironment.MachineName:\t{Environment.MachineName}");
            _telemetryClient.TrackEvent(
                nameof(ActivatingService),
                new System.Collections.Generic.Dictionary <string, string>()
            {
                { "Autogenerated", _autogenerated.ToString() },
                { "MachineName", Environment.MachineName }
            });
        }
    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");
    }
Пример #35
0
        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();
        }
Пример #36
0
    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");
    }
        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);
            });
        }
Пример #38
0
 public void ActivatingController(
     string correlationId,
     string userId)
 {
     WebApiServiceEventSource.Current.ActivatingController(
         _context,
         correlationId,
         userId
         );
     _telemetryClient.TrackEvent(
         nameof(ActivatingController),
         new System.Collections.Generic.Dictionary <string, string>()
     {
         { "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 },
         { "CorrelationId", correlationId },
         { "UserId", userId }
     });
 }
Пример #39
0
 public async Task<bool> getUserCollection(ObservableCollection<CollectionUsersTeam> teamData)
 {
     try
     {
         libMethods = new methodLibrary();
         //await libMethods.writeToLogFile((DateTime.UtcNow).ToString() + ": in getUserCollection method");
         string resp = await libMethods.readSerializedUserClass();
         var rootuser = usersDataDeserializer(resp);
         var teamsobject = rootuser.teams;
         teamData.Clear();
         foreach (var teams in teamsobject)
         {
             teamData.Add(teams);
         }
     }
     catch (Exception ex)
     {
         var tc = new TelemetryClient();
         tc.TrackEvent("getUserCollection Exception : " + ex);
         //await libMethods.writeToLogFile((DateTime.UtcNow).ToString() + ": Exception in getUserCollection");
         return false;
     }
     return true;
 }
Пример #40
0
 public ActionResult Create([Bind(Include = "LastName, FirstMidName, EnrollmentDate")]Student student)
 {
     try
     {
         if (ModelState.IsValid)
         {
             db.Students.Add(student);
             db.SaveChanges();
             TelemetryClient telemetry = new TelemetryClient();
             telemetry.TrackEvent("NewStudent");
             return RedirectToAction("Index");
         }
     }
     catch (RetryLimitExceededException /* dex */)
     {
         //Log the error (uncomment dex variable name and add a line here to write a log.
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     return View(student);
 }
Пример #41
0
 public ActionResult Create([Bind(Include = "LastName,FirstMidName,HireDate,OfficeAssignment")]Instructor instructor, string[] selectedCourses)
 {
     if (selectedCourses != null)
     {
         instructor.Courses = new List<Course>();
         foreach (var course in selectedCourses)
         {
             var courseToAdd = db.Courses.Find(int.Parse(course));
             instructor.Courses.Add(courseToAdd);
         }
     }
     if (ModelState.IsValid)
     {
         db.Instructors.Add(instructor);
         db.SaveChanges();
         TelemetryClient telemetry = new TelemetryClient();
         telemetry.TrackEvent("NewInstructor");
         return RedirectToAction("Index");
     }
     PopulateAssignedCourseData(instructor);
     return View(instructor);
 }
Пример #42
0
 /// <summary>
 /// Log and track custom app insights 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="eventName"></param>
 /// <param name="properties"></param>
 internal static void TrackEvent(string eventName, IDictionary <string, string> properties)
 {
     // add common properties
     AddCommonProperties(ref properties);
     _TelemetryClient.TrackEvent(eventName, properties);
 }
Пример #43
0
 /// <summary>
 /// Reports an event to the telemetry manager.
 /// </summary>
 /// <param name="component">The object reporting the event, this will be logged</param>
 /// <param name="eventName"></param>
 public void ReportEvent(object component, string eventName)
 {
     TelemetryClient client = new TelemetryClient();
     client.TrackEvent(component.GetType().Name + ":" +eventName);
 }
Пример #44
0
        public async Task<IHttpActionResult> Post(string userId, string deviceName)
        {
            var aiTelemetry = new TelemetryClient();
            Device device = null;
            EnsureRegistryManagerInitialized();
            MobileAppSettingsDictionary settings = Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();

            await GetDevices();
            int maxDevices = int.Parse(settings["MaxDevices"]);
            MyDrivingContext context = new MyDrivingContext();
            var curUser = context.UserProfiles.FirstOrDefault(user => user.UserId == userId) ??
                          context.UserProfiles.Add(new MyDriving.DataObjects.UserProfile
                          {
                              Id = Guid.NewGuid().ToString(),
                              UserId = userId
                          });

            if (curUser.Devices == null)
            {
                curUser.Devices = new List<MyDriving.DataObjects.Device>();
            }

            if (curUser.Devices.Count >= maxDevices)
            {
                aiTelemetry.TrackEvent("Max number of devices reached for user = "******"You already have more than the maximum number of devices");
            }


            try
            {
                device = await registryManager.GetDeviceAsync(deviceName);
            }
            catch (Exception e)
            {
                aiTelemetry.TrackException(e);
            }

            if (device == null)  //device not found 
            {
                try
                {
                    device = await registryManager.AddDeviceAsync(new Device(deviceName));

                    if (device != null)
                    {
                        curUser.Devices.Add(new MyDriving.DataObjects.Device { Name = deviceName });
                        await context.SaveChangesAsync();
                    }
                    else  //registration failed
                    {
                        aiTelemetry.TrackEvent(String.Format("Registration failed for device {0}", deviceName));
                        return BadRequest("Error. Cannot register device");
                    }
                }
                catch (Exception e)
                {
                    aiTelemetry.TrackException(e);
                    aiTelemetry.TrackEvent(String.Format("Registration failed for device {0}", deviceName));
                    return BadRequest("Device provisioning failed on server with exception " + e.Message);
                }
                aiTelemetry.TrackEvent(String.Format("New device {0} registered for user {1}. Total devices: {2}", deviceName, curUser.Id, curUser.Devices.Count));
            }

            
            return Created("api/provision", device?.Authentication?.SymmetricKey?.PrimaryKey);
        }
Пример #45
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var transfer = (timerToChartsTransfer)e.Parameter;
            var tc = new TelemetryClient();
            tc.TrackEvent("Charts Viewed");
            Demands.Clear();
            //for(int i=0; i<transfer.trackact.activity[(int)transfer.activity_pos].timer_data.Count; i++)
            //{
            //    TimeTable tb = new TimeTable();
            //    tb.eventCount = i + 1;
            //    tb.seconds = transfer.trackact.activity[(int)transfer.activity_pos].timer_data[i].time_in_seconds;
            //    Demands.Add(tb);
            //}
            DateTime dt = (DateTime.Now).AddDays(-10);
            for (int i = 0; i < transfer.trackact.activity[(int)transfer.activity_pos].timer_data.Count; i++)
            {
                TimeTable tb = new TimeTable();
                DateTime da = transfer.trackact.activity[(int)transfer.activity_pos].timer_data[i].startTime;
                tb.Demand = da.ToLocalTime();
                tb.runningMedian = transfer.trackact.activity[(int)transfer.activity_pos].timer_data[i].running_median;
                tb.seconds = transfer.trackact.activity[(int)transfer.activity_pos].timer_data[i].time_in_seconds;
                Demands.Add(tb);
            }
            //SfChart chart = new SfChart();
            myChart.HorizontalAlignment = HorizontalAlignment.Center;
            myChart.VerticalAlignment = VerticalAlignment.Center;
            myChart.Header = "Time and Median";
            myChart.Foreground = new SolidColorBrush(Colors.White);

            DateTimeCategoryAxis primaryCategoryAxis = new DateTimeCategoryAxis();
            primaryCategoryAxis.Interval = 1;
            primaryCategoryAxis.Header = "Timer Started";

            primaryCategoryAxis.LabelFormat = "dd/MM hh:mm tt";
            primaryCategoryAxis.Foreground = new SolidColorBrush(Colors.White);
            myChart.PrimaryAxis = primaryCategoryAxis;
            NumericalAxis secondaryNumericalAxis = new NumericalAxis();
            secondaryNumericalAxis.Header = "Time (in seconds)";
            secondaryNumericalAxis.Minimum = 0;
            secondaryNumericalAxis.Foreground = new SolidColorBrush(Colors.White);
            myChart.SecondaryAxis = secondaryNumericalAxis;
            SplineSeries series2 = new SplineSeries();
            series2.ItemsSource = Demands;
            series2.ShowTooltip = true;
            series2.Label = "Median Time";
            series2.XBindingPath = "Demand";
            series2.YBindingPath = "runningMedian";
            series2.EnableAnimation = true;

            ColumnSeries series1 = new ColumnSeries();
            series1.EnableAnimation = true;
            series1.ShowTooltip = true;
            series1.Label = "Time (in seconds)";
            series1.ItemsSource = Demands;
            series1.XBindingPath = "Demand";
            series1.YBindingPath = "seconds";

            myChart.Series.Add(series1);
            myChart.Series.Add(series2);
            myChart.Legend = new ChartLegend() { Visibility = Visibility.Visible };

            //Hashtable datetime_ht = new Hashtable();
            //List<long> total_time_day = new List<long>();
            //datetime_ht.Clear();
            //total_time_day.Clear();
            //Demands = new ObservableCollection<GoldDemand>();
            //transfer = (timerToChartsTransfer)e.Parameter;
            //var activity = transfer.trackact.activity[(int)transfer.activity_pos];
            //int m = 0;
            //for (int l = 0; l < activity.timer_data.Count; l++)
            //{
            //    if (!datetime_ht.Contains(((activity.timer_data[l].startTime).ToLocalTime()).Date))
            //    {
            //        datetime_ht.Add(((activity.timer_data[l].startTime).ToLocalTime()).Date, m);
            //        total_time_day.Add(activity.timer_data[l].time_in_seconds);
            //        m++;
            //    }
            //    else
            //    {
            //        int pos = (int)datetime_ht[((activity.timer_data[l].startTime).ToLocalTime()).Date];
            //        total_time_day[pos] = total_time_day[pos] + activity.timer_data[l].time_in_seconds;
            //    }
            //}
            //Demands.Clear();
            //int i = 0;
            //foreach (var act in activity.timer_data)
            //{
            //    GoldDemand dem_event = new GoldDemand();
            //    if (datetime_ht.Contains(((act.startTime).ToLocalTime()).Date))
            //    {
            //        GoldDemand dem = new GoldDemand();
            //        dem.date = ((act.startTime).ToLocalTime()).Date;
            //        dem.Demand = String.Format("{0:dd/MM}", dem.date);
            //        //myChart.Header = ;

            //        //dem.Demand = i + 1;
            //        int pos = (int)datetime_ht[((act.startTime).ToLocalTime()).Date];
            //        dem.seconds = total_time_day[pos];
            //        datetime_ht.Remove(((act.startTime).ToLocalTime()).Date);
            //        Demands.Add(dem);
            //        //total_time_day.RemoveAt(pos);
            //    }
            //    dem_event.event_count = i;
            //    i = i + 1;
            //}
            //this.DataContext = this;
            //i = 0;
        }
Пример #46
0
        /// <summary>
        /// I created a new version of the function that already exists in methodlibrary because I needed an offcase which returned the string response.
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="response"></param>
        /// <param name="href"></param>
        /// <returns></returns>
        public async Task<string> apiPOSTCreateMember(string access_token, string response, string href)
        {

            methodLibrary mlibrary = new methodLibrary();
            HttpClient httpClient = new HttpClient();
            string resp = null;
            try
            {
                httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", access_token);
                httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));

                var httpResponseMessage = await httpClient.PostAsync(new Uri(href), new HttpStringContent(response));
                resp = await httpResponseMessage.Content.ReadAsStringAsync();
                //await mlibrary.writeFile("POSTresponse", resp);
                //Debug.WriteLine(resp);
                ApplicationData.Current.LocalSettings.Values["POSTCallMade"] = true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Caught exception : " + ex);
                var tc = new TelemetryClient();
                tc.TrackEvent("POST Fail :  " + href);
                return null;
            }
            return resp;
        }
Пример #47
0
        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);
        }
Пример #48
-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);
            }
        }
Пример #49
-1
        public static void LogServiceCallFailure(string url, int attempt)
        {
            TelemetryClient telemetry = new TelemetryClient();

            var d = new Dictionary<string, string>();
            d.Add("service call failed", url);
            d.Add("attempt", attempt.ToString());
            telemetry.TrackEvent(url, d);
        }