コード例 #1
0
        public void TrackDependencySendsGivenDependencyTelemetryToTelemetryChannel()
        {
            var             sentTelemetry = new List <ITelemetry>();
            TelemetryClient client        = this.InitializeTelemetryClient(sentTelemetry);

            var clientDependency = new DependencyTelemetry();

            client.TrackDependency(clientDependency);

            var channelDependency = (DependencyTelemetry)sentTelemetry.Single();

            Assert.Same(clientDependency, channelDependency);
        }
コード例 #2
0
        public void TrackDependencySendsDependencyTelemetryWithGivenNameCommandnameTimestampDurationAndSuccessToTelemetryChannel()
        {
            var             sentTelemetry = new List <ITelemetry>();
            TelemetryClient client        = this.InitializeTelemetryClient(sentTelemetry);

            var timestamp = DateTimeOffset.Now;

            client.TrackDependency("name", "command name", timestamp, TimeSpan.FromSeconds(42), false);

            var dependency = (DependencyTelemetry)sentTelemetry.Single();

            Assert.Equal("name", dependency.Name);
            Assert.Equal("command name", dependency.Data);
            Assert.Equal(timestamp, dependency.Timestamp);
            Assert.Equal(TimeSpan.FromSeconds(42), dependency.Duration);
            Assert.Equal(false, dependency.Success);
        }
コード例 #3
0
        public void ObsoleteTrackDependencySendsDependencyTelemetryWithGivenNameCommandnameTimestampDurationAndSuccessToTelemetryChannel()
        {
            var             sentTelemetry = new List <ITelemetry>();
            TelemetryClient client        = this.InitializeTelemetryClient(sentTelemetry);

            var timestamp = DateTimeOffset.Now;

#pragma warning disable CS0612 // Type or member is obsolete
            client.TrackDependency("name", "command name", timestamp, TimeSpan.FromSeconds(42), false);
#pragma warning restore CS0612 // Type or member is obsolete

            var dependency = (DependencyTelemetry)sentTelemetry.Single();

            Assert.AreEqual("name", dependency.Name);
            Assert.AreEqual("command name", dependency.Data);
            Assert.AreEqual(timestamp, dependency.Timestamp);
            Assert.AreEqual(TimeSpan.FromSeconds(42), dependency.Duration);
            Assert.AreEqual(false, dependency.Success);
        }
コード例 #4
0
        /// <summary>
        /// Track a Cosmos dependency call in Azure Monitor Application Insights
        /// </summary>
        /// <typeparam name="T">The type parameter of the Cosmos Response<typeparamref name="T"/></typeparam>
        /// <param name="telemetry">An initialised TelemetryClient</param>
        /// <param name="response">The Cosmos Response returned</param>
        /// <param name="command">The command text to display in the dependency trace. NOTE: Do not include PII or Secrets</param>
        /// <param name="timestamp">The timestamp for this call. Usually the DateTimeOffset.UtcNow immediately before the dependency call was made.</param>
        /// <param name="duration">The measured duration of the dependency call as TimeSpan</param>
        public static void TrackCosmosDependency <T>(
            this TelemetryClient telemetry,
            Response <T> response,
            string command,
            DateTimeOffset timestamp,
            TimeSpan duration)
        {
            var diagnostics = Diagnostics(response);
            var statistics  = diagnostics.Context.FirstOrDefault(c => c.Id == "StoreResponseStatistics");

            var dependency = new DependencyTelemetry
            {
                Data       = command,
                Duration   = duration,
                Name       = Name(statistics),
                ResultCode = StatusCode(response),
                Timestamp  = timestamp,
                Success    = StatusCodeSuccess(response),
                Target     = statistics?.LocationEndpoint?.Host,
                Type       = "Azure DocumentDB" // This type name will display the Cosmos icon in the UI
            };

            telemetry.TrackDependency(dependency);
        }
コード例 #5
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
コード例 #6
0
        public ActionResult Index()
        {
            var sw = Stopwatch.StartNew();
            var ai = new TelemetryClient();
            var startTime = DateTime.UtcNow;
            var newsViewModel = new List<NewsModel>();
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext == null) return View(newsViewModel);

                //get user info
                var spUser = clientContext.Web.CurrentUser;
                clientContext.Load(spUser, user => user.LoginName);
                clientContext.ExecuteQuery();

                IDatabase cache = RedisHelper.Connection.GetDatabase();
                var cacheKey = $"news_{spUser.LoginName}";

                if (cache.KeyExists(cacheKey))
                {
                    newsViewModel = JsonConvert.DeserializeObject<List<NewsModel>>(cache.StringGet(cacheKey));
                    sw.Stop();
                    var timespanCache = sw.Elapsed;
                    ViewBag.Time = $"{timespanCache.Minutes:00}m:{timespanCache.Seconds:00}s:{timespanCache.Milliseconds / 10:00}ms";
                    ai.TrackDependency("Redis", cacheKey, startTime, sw.Elapsed, true);
                    return View(newsViewModel);
                }

                //Get news items
                Web web = clientContext.Web;
                List newsList = web.GetList("sites/Portal/Lists/News");
                clientContext.Load(newsList);
                var items = newsList.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(items,
                    includes =>
                        includes.Include(y => y["Device"], y => y["Department"], y => y.Client_Title,
                            y => y["NewsContent"]));
                clientContext.ExecuteQuery();



                //get user profile property
                PeopleManager peopleManager = new PeopleManager(clientContext);

                var profilePropertyNames = new[] { "Device", "SPS-Department", "Title" };
                UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(
                    clientContext, spUser.LoginName, profilePropertyNames);
                IEnumerable<string> profilePropertyValues =
                    peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

                // Load the request and run it on the server.
                clientContext.Load(profilePropertiesForUser);
                clientContext.ExecuteQuery();

                var propertyValues = profilePropertyValues as IList<string> ?? profilePropertyValues.ToList();
                var devices = propertyValues.ToList()[0];
                var department = propertyValues.ToList()[1];

                foreach (var item in items)
                {
                    TaxonomyFieldValueCollection col = item["Device"] as TaxonomyFieldValueCollection;

                    foreach (var taxItem in col)
                    {
                        if (devices.Contains(taxItem.Label))
                        {
                            int index = newsViewModel.FindIndex(i => i.Title == item.Client_Title);
                            if (index != 0)
                            {
                                newsViewModel.Add(new NewsModel(item.Client_Title, item["NewsContent"].ToString()));
                            }
                        }
                    }
                }
                cache.StringSet(cacheKey, JsonConvert.SerializeObject(newsViewModel), new TimeSpan(0, 0, 1, 0));
            }


            sw.Stop();
            var timespan = sw.Elapsed;
            ViewBag.Time = $"{timespan.Minutes:00}m:{timespan.Seconds:00}s:{timespan.Milliseconds / 10:00}ms";
            ai.TrackDependency("SharePoint", "GetNews", startTime, sw.Elapsed, true);
            return View(newsViewModel);
        }
コード例 #7
0
        public async Task<JsonpResult> GetTips()
        {
            IDatabase cache = RedisHelper.Connection.GetDatabase();
            var cacheKey = "tip";
            var ai = new TelemetryClient();
            var startTime = DateTime.UtcNow;
            var timer = System.Diagnostics.Stopwatch.StartNew();

            if (cache.KeyExists(cacheKey))
            {
                timer.Stop();
                ai.TrackDependency("Redis", "GetTip", startTime, timer.Elapsed, true);
                return new JsonpResult(JsonConvert.DeserializeObject<TipsModel>(await cache.StringGetAsync(cacheKey)));
            }

            var tip = GetTipForCurrentUser();

            await cache.StringSetAsync(cacheKey, JsonConvert.SerializeObject(tip), new TimeSpan(0, 0, 10, 0));
            timer.Stop();
            ai.TrackDependency("SharePoint", "GetTip", startTime, timer.Elapsed, true);
            return new JsonpResult(tip);
        }