Пример #1
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);
            }
        }
Пример #2
0
        public static TelemetryClient Get()
        {
            lock (_instanceLock)
            {
                if (_activeConfig == null)
                {
                    TelemetryConfiguration config = TelemetryConfiguration.Active;
                    config.InstrumentationKey = "1b3b7cd2-f058-4eb3-b153-a4425e95e20e";
#if DEBUG
                config.TelemetryChannel.DeveloperMode = true;
#endif
                    config.ContextInitializers.Add(new ComponentContextInitializer());
                    config.ContextInitializers.Add(new DeviceContextInitializer());
                    config.ContextInitializers.Add(new UserSessionInitializer());

                    _activeConfig = config;
                }

                if (_instance == null)
                {

                    var ret = new TelemetryClient(_activeConfig);
                    PopulateContext(ret);
                    _instance = ret;
                }

                return _instance;
            }
        }
Пример #3
0
 public static void Start()
 {
     if (null == s_telemetryClient)
     {
         s_telemetryClient = new TelemetryClient();
     }
 }
        public void MaximumNumberOfAggregations()
        {
            var propertyValues = new string[] { "Value1", "Value2", "Value3", "Value4", "Value4", "Value5", null, "Value6", "Value6", "Value7", "Value8" };

            var client = new TelemetryClient();

            for (int i = 1; i <= 2; i++)
            {
                for (int p1 = 0; p1 < propertyValues.Count(); p1++)
                {
                    for (int p2 = 0; p2 < propertyValues.Count(); p2++)
                    {
                        for (int p3 = 0; p3 < propertyValues.Count(); p3++)
                        {
                            client.TrackAggregateMetric("My Counter", 50 * i, propertyValues[p1], propertyValues[p2], propertyValues[p3]);
                        }
                    }
                }
            }

            Assert.AreEqual(1, AggregateMetrics.aggregationSets.Count);

            AggregationSet aggregationSet;
            AggregateMetrics.aggregationSets.TryGetValue(AggregateMetrics.aggregationSets.Keys.First(), out aggregationSet);

            Assert.AreEqual(5, aggregationSet.property1Values.Count);
            Assert.AreEqual(5, aggregationSet.property2Values.Count);
            Assert.AreEqual(5, aggregationSet.property3Values.Count);

            var aggregations = aggregationSet.RemoveAggregations();

            Assert.AreEqual((Constants.MaxPropertyCardinality + 2) * (Constants.MaxPropertyCardinality + 2) * (Constants.MaxPropertyCardinality + 2), aggregations.Count);
        }
Пример #5
0
        private static TelemetryClient CreateClient(string clientName, string instrumentationKey,
            Assembly sourceAssembly)
        {
            if (_clientsAndConfigs.ContainsKey(clientName))
            {
                throw new ArgumentException(
                    $"A client already exists with name \"{clientName}\". Use GetClient() to retrieve it.",
                    nameof(clientName));
            }

            if (_clientsAndConfigs.Any(c => c.Value.Item1.InstrumentationKey.Equals(instrumentationKey, StringComparison.OrdinalIgnoreCase)))
            {
                throw new ArgumentException(
                    "A client already exists with the given instrumentation key.", nameof(instrumentationKey));
            }

            var config = TelemetryConfiguration.CreateDefault();
            var client = new TelemetryClient(config);
            ConfigureApplication(instrumentationKey, client, config,
                new TelemetryInitializer(sourceAssembly));

            _clientsAndConfigs.Add(clientName, Tuple.Create(client, config));

            return client;
        }
Пример #6
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);
        }
Пример #7
0
        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 128;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            bool result = base.OnStart();

            TelemetryConfiguration.Active.InstrumentationKey = CloudConfigurationManager.GetSetting("APPINSIGHTS_INSTRUMENTATIONKEY");

            // TODO: disable
            // TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;
            this.telemetry = new TelemetryClient();

            this.telemetry.TrackTrace("WorkerRole starting", SeverityLevel.Information);

            try
            {
                this.trainProcesserHost = new LearnEventProcessorHost();
                this.settingsWatcher = new OnlineTrainerSettingsWatcher(this.trainProcesserHost);

                this.StartRESTAdminEndpoint();
            }
            catch (Exception e)
            {
                this.telemetry.TrackException(e);
                // still start to give AppInsights a chance to log
            }

            return result;
        }
Пример #8
0
        private void InitializeTelemetry()
        {
            try
            {
                _client = new TelemetryClient();
                _client.InstrumentationKey = InstrumentationKey;
                _client.Context.Session.Id = Guid.NewGuid().ToString();

                _client.Context.Device.OperatingSystem = RuntimeEnvironment.OperatingSystem;

                _commonProperties = new Dictionary<string, string>();
                _commonProperties.Add(OSVersion, RuntimeEnvironment.OperatingSystemVersion);
                _commonProperties.Add(OSPlatform, RuntimeEnvironment.OperatingSystemPlatform.ToString());
                _commonProperties.Add(RuntimeId, RuntimeEnvironment.GetRuntimeIdentifier());
                _commonProperties.Add(ProductVersion, Product.Version);
                _commonProperties.Add(TelemetryProfile, Environment.GetEnvironmentVariable(TelemetryProfileEnvironmentVariable));
                _commonMeasurements = new Dictionary<string, double>();
            }
            catch (Exception)
            {
                _client = null;
                // we dont want to fail the tool if telemetry fails.
                Debug.Fail("Exception during telemetry initialization");
            }
        }
		public HtmlToShortPlainTextConverter()
		{
			if (!DesignMode.DesignModeEnabled)
			{
				_telemetryClient = ServiceLocator.Current.GetInstance<TelemetryClient>();
			}
		}
Пример #10
0
        static BuildTelemetryClient()
        {
            TelemetryConfiguration.Active.TelemetryChannel.EndpointAddress = Properties.Resources.TelemetryEndpoint;
            TelemetryConfiguration.Active.InstrumentationKey = Properties.Resources.AppInsightsInstrumentationKey;
            _telemetryClient = new TelemetryClient();

            try
            {
                /*
                 * Explicitly open the registry as 64-bit so the values under SQMClient show up on 64-bit OS.
                 * On 32-bit OS this will not have any effect and the values under SQMClient will show up.
                 */
                RegistryKey sqmClientKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
                sqmClientKey = sqmClientKey.OpenSubKey(SqmClientRegKey, false);
                if (sqmClientKey != null)
                {
                    string machineId = (string)sqmClientKey.GetValue(SqmMachineIdRegValue, string.Empty);
                    if (!string.IsNullOrEmpty(machineId))
                    {
                        Guid parsedMachineId = Guid.Empty;
                        Guid.TryParse(machineId, out parsedMachineId);
                        _machineId = parsedMachineId.ToString();
                    }
                }
                else
                {
                    _machineId = Guid.Empty.ToString();
                }
            }
            catch (Exception)
            {
                _machineId = Guid.Empty.ToString();
            }
        }
Пример #11
0
        /// <summary>
        /// Initializes the singleton instance of the <see cref="App"/> class. This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            TelemetryClient = new TelemetryClient();

            this.InitializeComponent();
            this.Suspending += this.OnSuspending;
        }
        void InitializeTelemetry()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException      += TaskScheduler_UnobservedTaskException;

#if !CORE
            TelemetryConfiguration.Active.InstrumentationKey = "c54faeb2-109e-40c8-ad03-58aa69c17592";
            Microsoft.ApplicationInsights.TelemetryClient tc = new Microsoft.ApplicationInsights.TelemetryClient();
            tc.InstrumentationKey             = "c54faeb2-109e-40c8-ad03-58aa69c17592";
            tc.Context.User.Id                = Environment.UserName;
            tc.Context.Session.Id             = Guid.NewGuid().ToString();
            tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
            tc.Context.Component.Version      = Assembly.GetEntryAssembly().GetName().Version.ToString();

            InnerClient = tc;
            try
            {
                LogFile = new StreamWriter("log.txt");
            }
            catch (Exception)
            {
                LogFile = null;
            }
#endif
        }
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            WindowsAppInitializer.InitializeAsync()
                .ContinueWith(
                    task =>
                        {
                            TelemetryConfiguration.Active.TelemetryInitializers.Add(new UwpDeviceTelemetryInitializer());
                        })
                .ContinueWith(task => { Telemetry = new TelemetryClient(); });

            this.InitializeComponent();
            this.Suspending += this.OnSuspending;
            this.Resuming += this.OnResuming;
            this.UnhandledException += this.App_UnhandledException;

            if (ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
            {
                HardwareButtons.BackPressed += this.HardwareButtons_BackPressed;
            }

            try
            {
                TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
            }
            catch (Exception)
            {
                // on device which doesn't have it... (core)
            }
        }
Пример #14
0
 static void TCBuildUp()
 {
     tc = new TelemetryClient();
     tc.InstrumentationKey = "3fa22409-3d8d-499e-9fa6-1cf2b05af4a5";
     tc.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
     tc.Context.Properties["Assembly"] = AppDomain.CurrentDomain.FriendlyName;
 }
Пример #15
0
        internal EvalOperation(OnlineTrainerSettingsInternal settings)
        {
            this.telemetry = new TelemetryClient();

            // evaluation pipeline
            this.evalEventHubClient = EventHubClient.CreateFromConnectionString(settings.EvalEventHubConnectionString);

            this.evalBlock = new TransformManyBlock<object, EvalData>(
                (Func<object, IEnumerable<EvalData>>)this.OfflineEvaluate,
                new ExecutionDataflowBlockOptions
                {
                    MaxDegreeOfParallelism = 4,
                    BoundedCapacity = 1024
                });

            this.evalBlock.Completion.ContinueWith(t =>
            {
                this.telemetry.TrackTrace($"Stage 3 - Evaluation pipeline completed: {t.Status}");
                if (t.IsFaulted)
                    this.telemetry.TrackException(t.Exception);
            });

            // batch output together to match EventHub throughput by maintaining maximum latency of 5 seconds
            this.evalBlockDisposable = this.evalBlock.AsObservable()
                .GroupBy(k => k.PolicyName)
                   .Select(g =>
                        g.Window(TimeSpan.FromSeconds(5))
                         .Select(w => w.Buffer(245 * 1024, e => Encoding.UTF8.GetByteCount(e.JSON)))
                         .SelectMany(w => w)
                         .Subscribe(this.UploadEvaluation))
                   .Publish()
                   .Connect();
        }
Пример #16
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;
        }
Пример #17
0
        public App()
        {
            TelemetryClient = new TelemetryClient();

            InitializeComponent();
            Suspending += OnSuspending;
        }
		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);
		}
 /// <summary>
 /// Controller for hero photo operations.
 /// </summary>
 /// <param name="repository">Data layer.</param>
 /// <param name="telemetryClient">Telemetry client.</param>
 /// <param name="userRegistrationReferenceProvider">The user registration reference provider.</param>
 public HeroPhotoController(IRepository repository, TelemetryClient telemetryClient,
     IUserRegistrationReferenceProvider userRegistrationReferenceProvider)
     : base(userRegistrationReferenceProvider)
 {
     _repository = repository;
     _telemetryClient = telemetryClient;
 }
Пример #20
0
        public Telemetry()
        {
            bool optout = Env.GetEnvironmentVariableAsBool(TelemetryOptout);

            if (optout)
            {
                return;
            }

            try
            {
                _client = new TelemetryClient();
                _client.InstrumentationKey = InstrumentationKey;
                _client.Context.Session.Id = Guid.NewGuid().ToString();

                var runtimeEnvironment = PlatformServices.Default.Runtime;
                _client.Context.Device.OperatingSystem = runtimeEnvironment.OperatingSystem;

                _commonProperties = new Dictionary<string, string>();
                _commonProperties.Add(OSVersion, runtimeEnvironment.OperatingSystemVersion);
                _commonProperties.Add(OSPlatform, runtimeEnvironment.OperatingSystemPlatform.ToString());
                _commonProperties.Add(RuntimeId, runtimeEnvironment.GetRuntimeIdentifier());
                _commonProperties.Add(ProductVersion, Product.Version);
                _commonMeasurements = new Dictionary<string, double>();

                _isInitialized = true;
            }
            catch (Exception)
            {
                // we dont want to fail the tool if telemetry fais. We should be able to detect abnormalities from data 
                // at the server end
                Debug.Fail("Exception during telemetry initialization");
            }
        }
Пример #21
0
        public static void Main(string[] args)
        {
            var config = new Configuration();
            var telemetry = new TelemetryClient();
            telemetry.InstrumentationKey = config.InstrumentationKey;
            telemetry.Context.Device.Id = Environment.MachineName;
            telemetry.Context.Session.Id = Guid.NewGuid().ToString();
            telemetry.Context.Location.Ip = Dns.GetHostEntryAsync(Dns.GetHostName())
                                                .Result
                                                .AddressList
                                                .FirstOrDefault(addr => addr.AddressFamily == AddressFamily.InterNetwork)
                                                .ToString();

            using (var amz = new AmazonSynchronizer(config, telemetry))
            {
                amz.WithInterval(TimeSpan.FromSeconds(1))
                    .StopWhen((obj) => false)
                    .Start(CancellationToken.None)
                    .Wait();
            }

            if (telemetry != null)
                telemetry.Flush();

            Console.WriteLine("Sync Server Stopped.Press any key to exit ...");
            Console.ReadKey();
        }
        /// <summary>
        /// Construct a sink that saves logs to the Application Insights account.
        /// </summary>
        /// <param name="telemetryClient">Required Application Insights telemetryClient.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <exception cref="ArgumentNullException">telemetryClient</exception>
        /// <exception cref="System.ArgumentNullException">telemetryClient</exception>
        public ApplicationInsightsSink(TelemetryClient telemetryClient, IFormatProvider formatProvider = null)
        {
            if (telemetryClient == null) throw new ArgumentNullException("telemetryClient");

            _telemetryClient = telemetryClient;
            _formatProvider = formatProvider;
        }
Пример #23
0
        private TelemetryService()
        {
            _telemetryClient = new TelemetryClient {InstrumentationKey = ""};
            TelemetryConfiguration.Active.ContextInitializers.Add(new UserSessionInitializer());

            HandleExcetion();
        }
 public RequestTrackingMiddleware(OwinMiddleware next, TelemetryConfiguration telemetryConfiguration) 
     : base(next)
 {
     _telemetryClient = telemetryConfiguration == null 
         ? new TelemetryClient()
         : new TelemetryClient(telemetryConfiguration);
 }
Пример #25
0
 public MfTargetDevice(MFPortDefinition port, MFDevice device)
 {
     _port = port;
     _device = device;
     _tc = App.Kernel.Get<TelemetryClient>();
     Task.Run(() => InitializeAsync());
 }
Пример #26
0
        public App()
        {

            TelemetryConfiguration.Active.InstrumentationKey = "5afcb70e-e5b7-41c5-9e57-aa6fb9f08c2a";
            Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
                Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
                Microsoft.ApplicationInsights.WindowsCollectors.Session |
                Microsoft.ApplicationInsights.WindowsCollectors.PageView |
                Microsoft.ApplicationInsights.WindowsCollectors.UnhandledException
        );
            InitializeComponent();
            SplashFactory = (e) => new Views.Splash(e);
            #region TelemetryClient Init
            Telemetry = new TelemetryClient();
            #endregion
           MobileService =
new MobileServiceClient(
    "https://petrolheadappuwp.azurewebsites.net"
);
            #region App settings

            var _settings = SettingsService.Instance;
            RequestedTheme = _settings.AppTheme;
            CacheMaxDuration = _settings.CacheMaxDuration;
            ShowShellBackButton = _settings.UseShellBackButton;

            #endregion
        }
Пример #27
0
    /// <summary>
    /// Initializes the telemetry client.
    /// </summary>
    public static void Initialize(IServiceProvider serviceProvider, string version, string telemetryKey)
    {
        if (_telemetry != null)
            throw new NotSupportedException("The telemetry client is already initialized");

        var dte = (DTE2)serviceProvider.GetService(typeof(DTE));

        _telemetry = new TelemetryClient();
        _telemetry.Context.Session.Id = Guid.NewGuid().ToString();
        _telemetry.Context.Device.Model = dte.Edition;
        _telemetry.InstrumentationKey = telemetryKey;
        _telemetry.Context.Component.Version = version;

        byte[] enc = Encoding.UTF8.GetBytes(Environment.UserName + Environment.MachineName);
        using (var crypto = new MD5CryptoServiceProvider())
        {
            byte[] hash = crypto.ComputeHash(enc);
            _telemetry.Context.User.Id = Convert.ToBase64String(hash);
        }

        _events = dte.Events.DTEEvents;
        _events.OnBeginShutdown += delegate { _telemetry.Flush(); };

        Enabled = true;
    }
Пример #28
0
        protected void Application_Error(object sender, EventArgs e)
        {
            TelemetryClient telemetry = new TelemetryClient();

            var exception = Server.GetLastError();
            while (exception.InnerException != null)
                exception = exception.InnerException;

            string exceptionType = exception.GetType().ToString();
            string exceptionMessage = exception.Message;
            string stackTrace = exception.StackTrace;

            switch( exceptionType )
            {
                case "System.Data.SqlClient.SqlException" :
                    ErrorEvent.Log.DatabaseError( exceptionType, exceptionMessage, stackTrace);
                    break;
                case "MvcMusicStore.Proxy.ServiceCallException":
                    string serviceUrl = ((ServiceCallException)exception).ServiceUrl;
                    ErrorEvent.Log.ServiceCallError(exceptionType, exceptionMessage, stackTrace, serviceUrl);
                    break;
                default:
                    ErrorEvent.Log.ExcepcionNoManejada(exceptionType, exceptionMessage, stackTrace);
                    break;
            }
            //Server.ClearError();
        }
 public LearnEventProcessorHost()
 {
     this.telemetry = new TelemetryClient();
     
     // by default read from the beginning of Event Hubs event stream.
     this.eventHubStartDateTimeUtc = null;
 }
        public void IsEnabledReturnsTrueIfTelemetryTrackingIsEnabledInConfiguration()
        {
            var configuration = new TelemetryConfiguration { DisableTelemetry = false };
            var client = new TelemetryClient(configuration);

            Assert.True(client.IsEnabled());
        }
Пример #31
0
        /// <summary>
        /// Initialize telemetry for ApplicationInsights in Azure
        /// </summary>
        public static void InitializeTelemetry()
        {
            Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
                WindowsCollectors.Metadata | WindowsCollectors.Session | WindowsCollectors.UnhandledException);

            telemetry = new Microsoft.ApplicationInsights.TelemetryClient();
            telemetry.InstrumentationKey = appInsightsKey;
            TelemetryEnabled             = telemetry.IsEnabled();
        }
        private TelemetryClient GetTelemetryClient(bool telemetryEnabled)
        {
            TelemetryConfiguration telemetryConfiguration = TelemetryConfiguration.CreateDefault();

            telemetryConfiguration.InstrumentationKey = "60ab83db-108f-45ee-b537-d70dc47d3193";
            telemetryConfiguration.DisableTelemetry   = (telemetryEnabled == false);
            TelemetryClient tc = new Microsoft.ApplicationInsights.TelemetryClient(telemetryConfiguration);

            return(tc);
        }
Пример #33
0
        public ActorLogger(
            FG.ServiceFabric.Diagnostics.ActorOrActorServiceDescription actor)
        {
            _actor = actor;

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #34
0
        public ConsoleLogger(
            )
        {
            // Do stuff in the constructor

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #35
0
        public WebApiLogger(
            System.Fabric.StatelessServiceContext context)
        {
            _context = context;

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #36
0
        public TitleServiceLogger(
            System.Fabric.StatefulServiceContext serviceContext,
            FG.ServiceFabric.Services.Remoting.FabricTransport.ServiceRequestContext requestContext)
        {
            _serviceContext = serviceContext;
            _requestContext = requestContext;

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #37
0
        public ServiceDomainLogger(
            Microsoft.ServiceFabric.Actors.Runtime.ActorService actorService,
            FG.ServiceFabric.Services.Remoting.FabricTransport.ServiceRequestContext context)
        {
            _actorService = actorService;
            _context      = context;

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #38
0
        public DependencyLogger(
            int processId,
            string machineName)
        {
            _processId   = processId;
            _machineName = machineName;
            // Do stuff in the constructor

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #39
0
        public InfrastructureLogger(
            bool autogenerated,
            string machineName)
        {
            _autogenerated = autogenerated;
            _machineName   = machineName;
            // Do stuff in the constructor

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #40
0
        public ConsoleRunnerLogger(
            int processId,
            string machineName,
            Microsoft.ServiceFabric.Actors.ActorId actorId)
        {
            _processId   = processId;
            _machineName = machineName;
            _actorId     = actorId;

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #41
0
        public PersonActorServiceLogger(
            Microsoft.ServiceFabric.Actors.Runtime.ActorService actorService,
            Guid correlationId,
            string message)
        {
            _actorService  = actorService;
            _correlationId = correlationId;
            _message       = message;

            _telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            _telemetryClient.Context.User.Id                = Environment.UserName;
            _telemetryClient.Context.Session.Id             = Guid.NewGuid().ToString();
            _telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
        }
Пример #42
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();
            }
        }
Пример #43
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);
            }
        }
        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);
        }
Пример #45
0
        // Create a CSV file and save to Blob storage with the Headers required for our Azure Function processing
        // A new request telemetry is created
        // The request is part of the parent request (since)
        public void CreateBlob(string fileName)
        {
            ///////////////////////////////////////////////////
            // Grab existing 
            ///////////////////////////////////////////////////
            Microsoft.ApplicationInsights.TelemetryClient telemetryClient = new Microsoft.ApplicationInsights.TelemetryClient();
            telemetryClient.Context.User.AuthenticatedUserId = "*****@*****.**";

            string traceoperation = null;
            string traceparent = null;
            System.Console.WriteLine("telemetryClient.Context.Operation.Id: " + telemetryClient.Context.Operation.Id);
            System.Console.WriteLine("telemetryClient.Context.Session.Id: " + telemetryClient.Context.Session.Id);
            System.Console.WriteLine("telemetryClient.Context.Operation.ParentId: " + telemetryClient.Context.Operation.ParentId);

            Microsoft.ApplicationInsights.DataContracts.RequestTelemetry requestTelemetry = new Microsoft.ApplicationInsights.DataContracts.RequestTelemetry();
            requestTelemetry.Name = "Create Blob: " + fileName;
            //requestTelemetry.Source = requestContext.Replace("appId=",string.Empty);
            requestTelemetry.Timestamp = System.DateTimeOffset.Now;
            requestTelemetry.Context.Operation.Id = traceoperation;
            requestTelemetry.Context.Operation.ParentId = traceparent;
            requestTelemetry.Context.User.AuthenticatedUserId = "*****@*****.**";

            using (var requestBlock = telemetryClient.StartOperation<Microsoft.ApplicationInsights.DataContracts.RequestTelemetry>(requestTelemetry))
            {
                ///////////////////////////////////////////////////
                // Request Telemetry
                ///////////////////////////////////////////////////
                requestBlock.Telemetry.Context.User.AuthenticatedUserId = "*****@*****.**";

                if (!string.IsNullOrWhiteSpace(traceoperation))
                {
                    // Use the existing common operation id
                    requestBlock.Telemetry.Context.Operation.Id = traceoperation;
                    System.Console.WriteLine("[Use existing] traceoperation: " + traceoperation);
                }
                else
                {
                    // Set the traceoperation (we did not know it until now)
                    traceoperation = requestBlock.Telemetry.Context.Operation.Id;
                    System.Console.WriteLine("[Set the] traceoperation = requestBlock.Telemetry.Context.Operation.Id: " + traceoperation);
                }

                if (!string.IsNullOrWhiteSpace(traceparent))
                {
                    // Use the existing traceparent
                    requestBlock.Telemetry.Context.Operation.ParentId = traceparent;
                    System.Console.WriteLine("[Use existing] traceparent: " + traceparent);
                }
                else
                {
                    traceparent = requestBlock.Telemetry.Id;
                    System.Console.WriteLine("[Set the] traceparent = requestBlock.Telemetry.Id: " + traceparent);
                }
                // Store future parent id
                traceparent = requestBlock.Telemetry.Id;
                System.Console.WriteLine("traceparent = requestBlock.Telemetry.Id: " + traceparent);



                ///////////////////////////////////////////////////
                // Create Dependency for future Azure Function processing
                // NOTE: I trick it by giving a Start Time Offset of Now.AddSeconds(1), so it sorts correctly in the Azure Portal UI
                ///////////////////////////////////////////////////
                string operationName = "Dependency: Blob Event";
                // Set the target so it points to the "dependent" app insights account app id
                // string target = "03-disttrace-func-blob | cid-v1:676560d0-81fb-4e5b-bfdd-7da1ad11c866"
                string target = "03-disttrace-func-blob | cid-v1:" + System.Environment.GetEnvironmentVariable("ai_03_disttrace_web_app_appkey");
                string dependencyName = "Dependency Name: Azure Function Blob Trigger";
                Microsoft.ApplicationInsights.DataContracts.DependencyTelemetry dependencyTelemetry =
                   new Microsoft.ApplicationInsights.DataContracts.DependencyTelemetry(
                    operationName, target, dependencyName,
                    "02-disttrace-web-app", System.DateTimeOffset.Now.AddSeconds(1), System.TimeSpan.FromSeconds(2), "200", true);
                dependencyTelemetry.Context.Operation.Id = traceoperation;
                dependencyTelemetry.Context.Operation.ParentId = requestBlock.Telemetry.Id;
                // Store future parent id
                traceparent = dependencyTelemetry.Id;
                System.Console.WriteLine("traceparent = dependencyTelemetry.Id: " + traceparent);
                telemetryClient.TrackDependency(dependencyTelemetry);



                ///////////////////////////////////////////////////
                // Blob code
                ///////////////////////////////////////////////////
                string containerName = "appinsightstest";
                string storageConnectionString = System.Environment.GetEnvironmentVariable("ai_storage_key");
                CloudStorageAccount storageAccount = null;
                System.Console.WriteLine("storageConnectionString: " + storageConnectionString);

                CloudStorageAccount.TryParse(storageConnectionString, out storageAccount);

                System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();

                list.Add("id,date");

                for (int i = 1; i <= 50000; i++)
                {
                    list.Add(i.ToString() + "," + string.Format("{0:MM/dd/yyyy}", System.DateTime.Now));
                }

                var text = string.Join("\n", list.ToArray());

                Microsoft.WindowsAzure.Storage.Blob.CloudBlobClient blobStorage = storageAccount.CreateCloudBlobClient();
                blobStorage.DefaultRequestOptions.RetryPolicy = new Microsoft.WindowsAzure.Storage.RetryPolicies.LinearRetry(System.TimeSpan.FromSeconds(1), 10);
                Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer container = blobStorage.GetContainerReference(containerName);
                container.CreateIfNotExistsAsync().Wait();

                Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

                ///////////////////////////////////////////////////
                // Set the blob's meta data
                // We need the values from the dependency
                ///////////////////////////////////////////////////
                // Request-Context: appId=cid-v1:{The App Id of the current App Insights Account}
                string requestContext = "appId=cid-v1:" + System.Environment.GetEnvironmentVariable("ai_02_disttrace_web_app_appkey");
                System.Console.WriteLine("Blob Metadata -> requestContext: " + requestContext);
                blob.Metadata.Add("RequestContext", requestContext);

                // Request-Id / traceparent: {parent request/operation id} (e.g. the Track Dependency)
                System.Console.WriteLine("Blob Metadata -> RequestId: " + traceparent);
                blob.Metadata.Add("RequestId", traceparent);
                System.Console.WriteLine("Blob Metadata -> traceparent: " + traceparent);
                blob.Metadata.Add("traceparent", traceparent);

                // Traceoperation {common operation id} (e.g. same operation id for all requests in this telemetry pipeline)
                System.Console.WriteLine("Blob Metadata -> traceoperation: " + traceoperation);
                blob.Metadata.Add("traceoperation", traceoperation);


                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(text)))
                {
                    blob.UploadFromStreamAsync(memoryStream).Wait();
                }

                requestTelemetry.ResponseCode = "200";
                requestTelemetry.Success = true;
                telemetryClient.StopOperation(requestBlock);
            } // using

            ///////////////////////////////////////////////////
            // For Debugging
            ///////////////////////////////////////////////////
            telemetryClient.Flush();

        } // Create Blob
Пример #46
-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);
            }
        }