Esempio n. 1
0
        private static void LogHandledExceptionCore(Exception e, string aggregateExceptionId)
        {
            try
            {
                var currentHttpContext = HttpContext.Current;
                if (currentHttpContext != null)
                {
                    var elmahException = new ElmahException(e, GetObfuscatedServerVariables(new HttpContextWrapper(currentHttpContext)));
                    ErrorSignal.FromCurrentContext().Raise(elmahException);
                }
                else
                {
                    ErrorLog.GetDefault(null).Log(new Error(e));
                }

                // send exception to AppInsights
                Telemetry.TrackException(e, new Dictionary <string, string>
                {
                    { "aggregateExceptionId", aggregateExceptionId }
                });
            }
            catch
            {
                // logging failed, don't allow exception to escape
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Generic method to download from blob and copy to app settings temp folder
        /// </summary>
        /// <param name="blobSynname"></param>
        /// <param name="tempFilename"></param>
        /// <param name="synonymFileName"></param>
        /// <returns></returns>
        public async Task <bool> DownloadFile(string blobFileName, string tempfolder)
        {
            //Set up the client
            CloudStorageAccount storageAccount = new CloudStorageAccount(
                new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
                    _storagename,                     //"ncsfindacourse",  //"dfcdevfacostr",
                    _storagekey), true);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            MemoryStream ms = new MemoryStream();

            try
            {
                CloudBlobContainer container = blobClient.GetContainerReference(_containername);
                CloudBlockBlob     blockBlob = container.GetBlockBlobReference(blobFileName);

                var existsAsync = blockBlob.ExistsAsync();
                existsAsync.Wait();

                if (existsAsync.Result)
                {
                    using (var fileStream = System.IO.File.OpenWrite(System.IO.Path.Combine(tempfolder, blobFileName)))
                    {
                        await blockBlob.DownloadToStreamAsync(fileStream);
                    }
                }
                else
                {
                    _telemetry.TrackEvent("DownloadFile", new Dictionary <string, string>()
                    {
                        { "BlobFileName", blobFileName },
                        { "Tempfolder", tempfolder }
                    });

                    return(false);
                }
            }
            catch (StorageException stex)
            {
                _telemetry.TrackException(stex);
                return(false);
            }
            catch (Exception ex)
            {
                _telemetry.TrackException(ex);
                return(false);
            }
            return(true);
        }
Esempio n. 3
0
        private void ApiPingAndLog(IHostingEnvironment env, ITelemetryClient telemetryClient)
        {
            Ping pinger = null;

            try
            {
                telemetryClient.TrackEvent($"Start Up Api HttpRequest: {nameof(Environment.MachineName)} = {Environment.MachineName}");
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(env.EnvironmentName)} = {env.EnvironmentName}");
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(env.ApplicationName)} = {env.ApplicationName}");

                var uri = new Uri(Configuration["Tribal:APIAddress"]);
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(uri.Host)} = {uri.Host}");

                pinger = new Ping();
                var reply = pinger.Send(uri.Host);
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(reply.Address)} = {reply?.Address}");
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(reply.Options.DontFragment)} = {reply?.Options?.DontFragment}");
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(reply.Options.Ttl)} = {reply?.Options?.Ttl}");
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(reply.RoundtripTime)} = {reply?.RoundtripTime}");
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(reply.Buffer.Length)} = {reply?.Buffer?.Length}");
                telemetryClient.TrackEvent($"Start Up Api Ping: {nameof(reply.Status)} = {reply?.Status}");
            }
            catch (Exception e)
            {
                telemetryClient.TrackEvent($"Start Up Api Ping: exception");
                telemetryClient.TrackException(e);
            }
            finally
            {
                if (pinger != null)
                {
                    pinger.Dispose();
                }
            }
        }
Esempio n. 4
0
        private void ApiHttpRequestAndLog(IHostingEnvironment env, ITelemetryClient telemetryClient)
        {
            try
            {
                telemetryClient.TrackEvent($"Start Up Api HttpRequest: {nameof(Environment.MachineName)} = {Environment.MachineName}");
                telemetryClient.TrackEvent($"Start Up Api HttpRequest: {nameof(env.EnvironmentName)} = {env.EnvironmentName}");
                telemetryClient.TrackEvent($"Start Up Api HttpRequest: {nameof(env.ApplicationName)} = {env.ApplicationName}");

                var sw  = new Stopwatch();
                var uri = new Uri(Configuration["Tribal:APIAddress"]);
                telemetryClient.TrackEvent($"Start Up Api HttpRequest: {nameof(uri.Host)} = {uri.Host}");
                telemetryClient.TrackEvent($"Start Up Api HttpRequest: Address = {uri.OriginalString}");

                using (var httpClient = new HttpClient())
                {
                    telemetryClient.TrackEvent($"Start Up Api HttpRequest: Started at = {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")}");
                    sw.Start();
                    var statusCode = httpClient.GetAsync(uri).Result.StatusCode;
                    sw.Stop();
                    telemetryClient.TrackEvent($"Start Up Api HttpRequest: Ended at = {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")}");
                    telemetryClient.TrackEvent($"Start Up Api HttpRequest: Http Status Code = {statusCode}");
                    telemetryClient.TrackEvent($"Start Up Api HttpRequest: Time taken = {sw.ElapsedMilliseconds} ms");
                }
            }
            catch (Exception e)
            {
                telemetryClient.TrackEvent($"Start Up Api HttpRequest: exception");
                telemetryClient.TrackException(e);
            }
        }
Esempio n. 5
0
        public void TrackException(Exception exception, Action <Dictionary <string, string> > addProperties)
        {
            var telemetryProperties = new Dictionary <string, string>();

            addProperties(telemetryProperties);

            _telemetryClient.TrackException(exception, telemetryProperties, metrics: null);
        }
Esempio n. 6
0
 public override void OnException(ExceptionContext context)
 {
     if (context != null && context.Exception != null)
     {
         _telemetryClient.TrackException(context.Exception);
     }
     base.OnException(context);
 }
Esempio n. 7
0
        /// <summary>
        /// Write exception to ApplicationInsights.
        /// </summary>
        public void ExceptionEvent(Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            _telemetryClient.TrackException(exception);
        }
        public async Task <DeviceMetadata> GetMetadataAsync(string id)
        {
            if (FailedToDispatch)
            {
                return(null);                  // drop new messages if there is a dispatch problem
            }
            int current = 0;

            while (true)
            {
                try
                {
                    var request = new DeviceInfo()
                    {
                        Id = id
                    };
                    var response = await this.Client.GetMetadataAsync(request);

                    if (FailedToDispatch)
                    {
                        logger.LogDebug("gRPC client connected successfully.");
                        telemetryClient.TrackEvent($"gRPC client connected successfully from {System.Environment.MachineName}.");
                        FailedToDispatch = false;
                    }
                    return(response);
                }
                catch (RpcException ex)
                {
                    if (ex.StatusCode == StatusCode.Unavailable)
                    {
                        logger.LogWarning("gRPC client failed to connect...");
                        telemetryClient.TrackEvent($"gRPC client failed to connect from {System.Environment.MachineName}.");
                        FailedToDispatch = true;
                    }
                    else
                    {
                        telemetryClient.TrackException(ex);
                        throw ex;
                    }
                }
                current += 1000;
                if (current > CacheGrpcTimeout)
                {
                    logger.LogError("gRPC client timed out.");
                    telemetryClient.TrackEvent($"gRPC client timed out from {System.Environment.MachineName}.");
                    throw new Exception("gRPC client timed out.");
                }
                await Task.Delay(1000);
            }
        }
Esempio n. 9
0
        private async Task HandleException <TResource, TInput>(MutationRequest request, TInput input, Exception ex)
        {
            var failure = new Failed <TInput>(request, typeof(TResource).Name, input, ex.Message);

            _logger.LogError(30001, ex, "Exception in event handling");

            _telemetry.TrackException <TResource, TInput>(request, GrainId(), ex);

            await Persist(new List <EventDto>()
                          { new EventDto()
                            {
                                Name = $"Failed:{typeof(TInput).Name}", Event = failure
                            } });
        }
Esempio n. 10
0
        //ASB What is this doing?
        private async Task DownloadConfig(IMemoryCache cache, ITelemetryClient telemetryClient)
        {
            try
            {
                _filehelper = new FileHelper(Configuration, cache, telemetryClient);
                await _filehelper.DownloadSynonymFile();

                await _filehelper.DownloadConfigFiles();
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex,
                                               new Dictionary <string, string>()
                {
                    { "DownloadConfig", "Exception" }
                });
            }
        }
Esempio n. 11
0
        private static void LogHandledExceptionCore(Exception e, string aggregateExceptionId)
        {
            try
            {
                if (HttpContext.Current != null)
                {
                    ErrorSignal.FromCurrentContext().Raise(e);
                }
                else
                {
                    ErrorLog.GetDefault(null).Log(new Error(e));
                }

                // send exception to AppInsights
                Telemetry.TrackException(e, new Dictionary <string, string>
                {
                    { "aggregateExceptionId", aggregateExceptionId }
                });
            }
            catch
            {
                // logging failed, don't allow exception to escape
            }
        }
Esempio n. 12
0
        private void RefreshCore()
        {
            try
            {
                var blob = GetBlobReference();
                if (blob == null)
                {
                    return;
                }

                // The data in downloads.v1.json will be an array of Package records - which has Id, Array of Versions and download count.
                // Sample.json : [["AutofacContrib.NSubstitute",["2.4.3.700",406],["2.5.0",137]],["Assman.Core",["2.0.7",138]]....
                using (var jsonReader = new JsonTextReader(new StreamReader(blob.OpenRead())))
                {
                    try
                    {
                        jsonReader.Read();

                        while (jsonReader.Read())
                        {
                            try
                            {
                                if (jsonReader.TokenType == JsonToken.StartArray)
                                {
                                    JToken record = JToken.ReadFrom(jsonReader);
                                    string id     = record[0].ToString().ToLowerInvariant();

                                    // The second entry in each record should be an array of versions, if not move on to next entry.
                                    // This is a check to safe guard against invalid entries.
                                    if (record.Count() == 2 && record[1].Type != JTokenType.Array)
                                    {
                                        continue;
                                    }

                                    if (!_downloadCounts.ContainsKey(id))
                                    {
                                        _downloadCounts.Add(id, new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase));
                                    }
                                    var versions = _downloadCounts[id];

                                    foreach (JToken token in record)
                                    {
                                        if (token != null && token.Count() == 2)
                                        {
                                            string version = token[0].ToString().ToLowerInvariant();
                                            versions[version] = token[1].ToObject <int>();
                                        }
                                    }
                                }
                            }
                            catch (JsonReaderException ex)
                            {
                                _telemetryClient.TrackException(ex, new Dictionary <string, string>
                                {
                                    { "Origin", TelemetryOriginForRefreshMethod },
                                    { "AdditionalInfo", "Invalid entry found in downloads.v1.json." }
                                });
                            }
                        }
                    }
                    catch (JsonReaderException ex)
                    {
                        _telemetryClient.TrackException(ex, new Dictionary <string, string>
                        {
                            { "Origin", TelemetryOriginForRefreshMethod },
                            { "AdditionalInfo", "Data present in downloads.v1.json is invalid. Couldn't get download data." }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                _telemetryClient.TrackException(ex, new Dictionary <string, string>
                {
                    { "Origin", TelemetryOriginForRefreshMethod },
                    { "AdditionalInfo", "Unknown exception." }
                });
            }
        }
Esempio n. 13
0
 private void TrackExceptionCore(Exception exception, Dictionary <string, string> data,
                                 Dictionary <string, double> metrics)
 {
     _client.TrackException(exception, data, metrics);
 }