Ejemplo n.º 1
0
        public IAsyncResult BeginMethod(System.AsyncCallback callback, object state)
        {
            this.BeginMethodCount++;
            if (BeginMethodCount < CountToThrowAtBegin)
            {
                if (ExceptionToThrowAtBegin != null)
                {
                    throw ExceptionToThrowAtBegin;
                }
            }

            if (ThrowFatalExceptionAtBegin == true)
            {
                if (FatalException != null)
                {
                    Console.WriteLine("Throwing exception of type {0}", FatalException.GetType().ToString());
                    throw FatalException;
                }
            }

            var noOperationAction = new Action(() => { });
            var asyncResult       = noOperationAction.BeginInvoke(callback, state);

            return(asyncResult);
        }
Ejemplo n.º 2
0
        public void ArchiveLogFiles(string applicationName, FileLoggerOptions options, string logFileNamePattern)
        {
            try
            {
                foreach (string LogFilePath in _FileSystem.EnumerateFiles(
                             options.LogFileDirectory !,
                             FileNameGenerator.GenerateWildcardFileName(applicationName, logFileNamePattern),
                             SearchOption.TopDirectoryOnly))
                {
                    if (_LogFiles.Any(i => i.Value.FinalFullPath == LogFilePath))
                    {
                        continue;
                    }

                    if (_FileSystem.GetFileCreationTimeUtc(LogFilePath) < DateTime.UtcNow.Date)
                    {
                        TryArchiveLogFile(options, LogFilePath);
                    }
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception FatalException)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                Console.Error.WriteLine(FatalException.ToString());
            }
        }
Ejemplo n.º 3
0
        public async Task Start <TData, TStep>(TData data, Action <object> onCompletedWorkflow)
            where TData : new()
            where TStep : Step
        {
            _logger.Log(LogLevel.Trace, "Main Workflow started.");
            var   task = _mainWorkflowManager.Start <TData, TStep>(data, onCompletedWorkflow);
            await task;

            if (task.IsCompletedSuccessfully)
            {
                _logger.Log(LogLevel.Trace, "Main Workflow completed successfully.");
            }

            if (task.IsCanceled)
            {
                _logger.Log(LogLevel.Warning & LogLevel.Trace, "Main Workflow was canceled.");
            }

            if (task.Exception != null)
            {
                _logger.LogFatalException(task.Exception);
            }

            if (task.IsFaulted)
            {
                _logger.LogFatalException(FatalException.GetFatalException("Main workflow stopped unexpected."));
            }
        }
Ejemplo n.º 4
0
        protected StepDependencyPack GetStepDependencyPack <T>() where T : Step
        {
            var type = typeof(T);
            var pack = _stepDependencyPacks.SingleOrDefault(x => x.StepType == type);

            if (pack == null)
            {
                throw FatalException.GetFatalException(string.Empty);
            }

            return(pack);
        }
Ejemplo n.º 5
0
        private async Task ThrowOnFatalResponseAsync(HttpResponseMessage response, string requestUrl, int attemptIndex, string identity, List <HttpResponseSignature> allowlistedResponses)
        {
            if (response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.NotModified)
            {
                return;
            }

            string responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            HttpStatusCode responseStatusCode = response.StatusCode;

            try
            {
                JObject responseContentObject = JObject.Parse(responseContent);
                string  message = responseContentObject.SelectToken("$.message").Value <string>();

                foreach (HttpResponseSignature allowlistedResponse in allowlistedResponses)
                {
                    if (allowlistedResponse.statusCode == responseStatusCode && allowlistedResponse.Matches(responseStatusCode, message))
                    {
                        Dictionary <string, string> allowlistedResponseProperties = new Dictionary <string, string>()
                        {
                            { "RequestUrl", requestUrl },
                            { "ResponseStatusCode", responseStatusCode.ToString() },
                            { "ResponseMessage", message },
                        };
                        this.telemetryClient.TrackEvent("AllowlistedResponse", allowlistedResponseProperties);

                        return;
                    }
                }
            }
            catch (Exception)
            {
                // Done as best effort, ignore since the response content is already logged.
            }

            Exception fatalException = new FatalException($"Request to url '{requestUrl}' failed with status code: '{responseStatusCode}'. Response content: '{responseContent}'.");
            Dictionary <string, string> properties = new Dictionary <string, string>()
            {
                { "Url", requestUrl },
                { "Identity", identity },
                { "ResponseContent", responseContent },
                { "ResponseStatusCode", responseStatusCode.ToString() },
                { "AttemptIndex", attemptIndex.ToString() },
                { "Retried", false.ToString() },
                { "Fatal", true.ToString() },
            };

            this.telemetryClient.TrackException(fatalException, "Web request failed.", properties);
            this.failedRequestCount++;
            throw fatalException;
        }
Ejemplo n.º 6
0
        public IWorkflow <T> CreateWorkflow <T>(T workflowData, string key) where T : new()
        {
            FatalException.ArgumentNullException(workflowData, nameof(workflowData));

            var wf = new Workflow <T>
            {
                WorkflowData = workflowData
            };

            key = workflowData.GetType().GenerateKey(key);
            _workflows.Add(key, wf);
            return(wf);
        }
Ejemplo n.º 7
0
        public void RunInBackground(Step step, string key = null)
        {
            key = step.GetType().GenerateKey(key);

            if (MemoryProcesses.ContainsKey(key))
            {
                FatalException.ArgumentException($"Key already exists for background process : {key}");
            }

            var flow = this.RunWorkflowAsync(step);

            MemoryProcesses.Add(key, flow);
        }
Ejemplo n.º 8
0
        public async Task <TFlow> Run <TFlow, TStep>(TStep step)
            where TFlow : IWorkflow
            where TStep : Step
        {
            var result = await this.RunWorkflowAsync(step);

            if (result is TFlow correctResultType)
            {
                return(correctResultType);
            }

            throw FatalException.GetFatalException("");
        }
Ejemplo n.º 9
0
        public async Task <TFlow> AwaitProcessAsync <TFlow, TStep>(string key = null)
            where TFlow : IWorkflow
            where TStep : Step <TFlow>
        {
            key = typeof(TStep).GenerateKey(key);

            if (MemoryProcesses.TryGetValue(key, out var value))
            {
                return(value is Task <TFlow> task
                    ? await task
                    : throw FatalException.GetFatalException(""));
            }

            throw FatalException.GetFatalException("");;
        }
Ejemplo n.º 10
0
 public Result <string> GetErrorMessageByErrorCode(string code)
 {
     try
     {
         return(Result <String> .Succeed(ExceptionMessages.ResourceManager.GetString(code)));
     }
     catch (BaseException exc)
     {
         return(Result <string> .Failure(exc));
     }
     catch (Exception unknownExc)
     {
         var fatalExc = new FatalException(unknownExc);
         return(Result <string> .Failure(fatalExc));
     }
 }
        public static bool IsNotFatal(this Exception e)
        {
            Exception exception     = e;
            Type      exceptionType = e.GetType();

            if (FatalTypes.Contains(exceptionType))
            {
                StackTrace stackTrace     = new StackTrace(1, true);
                string     stackTraceText = stackTrace.ToString();
                string     message        = $"Exception type is fatal: {exceptionType}, {e}\n at \n{stackTraceText}";
                FatalException?.Invoke(null, new FatalExceptionEventArgs(message, exception));
                return(false);
            }

            return(true);
        }
Ejemplo n.º 12
0
 public Result HasAccessToMenu(Guid menuId, IEnumerable <string> roleNames)
 {
     try
     {
         var res = _roleMenuRepository.HasAccessToMenu(menuId, roleNames);
         return(res == true?Result.Succeed() : Result.Failure());
     }
     catch (BaseException exc)
     {
         return(Result.Failure(exc));
     }
     catch (Exception unknownExc)
     {
         var fatalExc = new FatalException(unknownExc);
         return(Result.Failure(fatalExc));
     }
 }
Ejemplo n.º 13
0
 public virtual Result <IQueryable <T> > GetAll(ISpecification <T> spec)
 {
     try
     {
         var result = _repository.GetAll(spec);
         return(Result <IQueryable <T> > .Succeed(result));
     }
     catch (BaseException exc)
     {
         return(Result <IQueryable <T> > .Failure(exc));
     }
     catch (Exception unknownExc)
     {
         var fatalExc = new FatalException(unknownExc);
         return(Result <IQueryable <T> > .Failure(fatalExc));
     }
 }
Ejemplo n.º 14
0
        public virtual async Task <Result> EditAsync(T model)
        {
            try
            {
                await _repository.UpdateAsync(model);

                return(Result.Succeed());
            }
            catch (BaseException exc)
            {
                return(Result.Failure(exc));
            }
            catch (Exception unknownExc)
            {
                var fatalExc = new FatalException(unknownExc);
                return(Result.Failure(fatalExc));
            }
        }
Ejemplo n.º 15
0
        public IWorkflow <T> GetWorkflow <T>(string key) where T : new()
        {
            key = typeof(T).GenerateKey(key);

            if (_workflows.TryGetValue(key, out var value))
            {
                if (value is IWorkflow <T> wf)
                {
                    return(wf);
                }
                else
                {
                    throw FatalException.GetFatalException(string.Empty);
                }
            }

            throw FatalException.GetFatalException(string.Empty);
        }
Ejemplo n.º 16
0
        /*    private string GenerateIdentificationNumberForOrganization(Organization model)
         *  {
         *      StringBuilder result = new StringBuilder();
         *
         *      if (model.ProductType == ProductType.CarParts.ToString())
         *          result.Append("CR");
         *      else
         *          result.Append("DF");
         *
         *      result.Append(DateTime.Now.ToString("yyyyMMdd"));
         *
         *      var lastOrganizationInThisMonth = _organizationRepository.GetAll()
         *                                                      .Where(m => m.CreatedDate.Year == DateTime.Now.Year && m.CreatedDate.Month == DateTime.Now.Month)
         *                                                          .OrderByDescending(m => m.CreatedDate)
         *                                                              .FirstOrDefault();
         *      int incrementNum = 0;
         *      if (lastOrganizationInThisMonth != null)
         *      {
         *          var num = lastOrganizationInThisMonth.IdentificationNumber.Substring(lastOrganizationInThisMonth.IdentificationNumber.Length - 3, 3);
         *          incrementNum = Convert.ToInt32(num);
         *      }
         *      incrementNum++;
         *      result.Append(incrementNum.ToString().PadLeft(3, '0'));
         *      return result.ToString();
         *  }*/

        public async Task <Result <int> > ChangeTitleAsync(string title)
        {
            try
            {
                var res = await _organizationRepository.ChangeTitleAsync(title);

                return(Result <int> .Succeed(res));
            }
            catch (BaseException exc)
            {
                return(Result <int> .Failure(exc));
            }
            catch (Exception unknownExc)
            {
                var fatalExc = new FatalException(unknownExc);
                return(Result <int> .Failure(fatalExc));
            }
        }
Ejemplo n.º 17
0
        public virtual async Task <Result <T> > GetByIdAsync(Guid id)
        {
            try
            {
                var result = await _repository.GetByIdAsync(id);

                return(Result <T> .Succeed(result));
            }
            catch (BaseException exc)
            {
                return(Result <T> .Failure(exc));
            }
            catch (Exception unknownExc)
            {
                var fatalExc = new FatalException(unknownExc);
                return(Result <T> .Failure(fatalExc));
            }
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Initializes a new BoxCutter for debugging.
 /// </summary>
 /// <param name="sortType">True if you want the logs written to be sorted by writer, false if you want them to be written
 /// chronologically. If true, the buffer has to be flushed when the game closes; if it closes unexpectedly the file may
 /// be empty. Also, it keeps everything written in memory; this could become massive fast.</param>
 /// <param name="overwriteOldLogs">True if you want the log to save to debug.log, false if you want the date and time appended
 /// to the filename.</param>
 public BoxCutter(bool sortLogs, bool overwriteOldLogs, string savePath)
 {
     #if DEBUG || TRACE
     string path;
     this.sortLogs = sortLogs;
     overwriteLogs = overwriteOldLogs;
     d = new Default();
     n = new NonFatalException();
     f = new FatalException();
     if(overwriteOldLogs)
     {
         path = savePath + "debug.log";
         if(File.Exists(path))
             file = File.Open(path, FileMode.Truncate);
         else
             file = File.Open(path, FileMode.CreateNew);
     }
     else
     {
         IEnumerable<string> filenames = Directory.EnumerateFiles(savePath, "debug*.log");
         int debuglogs = filenames.Count<string>();
         if(debuglogs > 9)
         {
             int logstodelete = debuglogs - 9;
             for(int i = 0; i < logstodelete; i++)
                 try { File.Delete(filenames.ElementAt(i)); }
                 catch { }
         }
         path = savePath + "debug[" + DateTime.Now.ToShortDateString().Replace(@"/", @"-").Replace(@"\", @"-") + "][" + DateTime.Now.ToLongTimeString().Replace(@":", @".") + "].log";
         file = File.Open(path, FileMode.Create);
     }
     writer = new StreamWriter(file);
     if(sortLogs)
     {
         sortedBuffer = new Dictionary<object, List<string>>();
         sortedBuffer.Add(d, new List<string>());
         sortedBuffer.Add(n, new List<string>());
         sortedBuffer.Add(f, new List<string>());
     }
     #endif
 }
Ejemplo n.º 19
0
        public Result <IQueryable <Menu> > GetUserMenus(Guid userId)
        {
            try
            {
                var res = _menuRepository.GetUserMenus(userId);
                if (res.Any())
                {
                    return(Result <IQueryable <Menu> > .Succeed(res));
                }

                return(Result <IQueryable <Menu> > .Failure());
            }
            catch (BaseException exc)
            {
                return(Result <IQueryable <Menu> > .Failure(exc));
            }
            catch (Exception unknownExc)
            {
                var fatalExc = new FatalException(unknownExc);
                return(Result <IQueryable <Menu> > .Failure(fatalExc));
            }
        }
Ejemplo n.º 20
0
        public Result <Menu> GetMenuByRouteDetails(string area, string controller, string action)
        {
            try
            {
                var res = _menuRepository.GetMenuByRouteDetails(area, controller, action);
                if (res != null)
                {
                    return(Result <Menu> .Succeed(res));
                }

                return(Result <Menu> .Failure());
            }
            catch (BaseException exc)
            {
                return(Result <Menu> .Failure(exc));
            }
            catch (Exception unknownExc)
            {
                var fatalExc = new FatalException(unknownExc);
                return(Result <Menu> .Failure(fatalExc));
            }
        }
Ejemplo n.º 21
0
        public void RemoveWorkflow <TF, TD>(string key)
            where TF : IWorkflow <TD>
            where TD : new()
        {
            key = typeof(TD).GenerateKey(key);

            if (_workflows.TryGetValue(key, out var workflow))
            {
                if (workflow is TF)
                {
                    _workflows.Remove(key);
                }
                else
                {
                    throw FatalException.GetFatalException(string.Empty);
                }
            }
            else
            {
                throw FatalException.GetFatalException(string.Empty);
            }
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            //Application.VisualStyleState = System.Windows.Forms.VisualStyles.VisualStyleState.NoneEnabled;
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                SingleInstanceApplication application = new SingleInstanceApplication();
                //SingleInstanceApplication.Application.SplashScreen = new fSplash();


                //SingleInstanceApplication.Application.MinimumSplashScreenDisplayTime = 5000;

                SingleInstanceApplication.Application.UnhandledException += new Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventHandler(Application_UnhandledException);
                SingleInstanceApplication.Application.Run(args);
            }
            catch (Exception x)
            {
                FatalException x1 = new FatalException("Fatal Exception", x);
                UIHelper.HandleUIException(x1);
                x1             = null;
                UIHelper.AtMng = null;
            }
        }
Ejemplo n.º 23
0
        public virtual async Task <Result> RemoveAsync(Guid id)
        {
            try
            {
                var entity = await GetByIdAsync(id);

                if (!entity.IsSucceed)
                {
                    return(Result.Failure(entity.ExceptionMessage));
                }
                await _repository.DeleteAsync(entity.Data);

                return(Result.Succeed());
            }
            catch (BaseException exc)
            {
                return(Result.Failure(exc));
            }
            catch (Exception unknownExc)
            {
                var fatalExc = new FatalException(unknownExc);
                return(Result.Failure(fatalExc));
            }
        }
Ejemplo n.º 24
0
        private void PerformLog(LogEntry logEntry)
        {
            RequestTelemetry requestTelemetry = null;

            if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.DisplayUrl)) && HttpContextAccessor.HttpContext != null)
            {
                HttpContext httpContext = HttpContextAccessor.HttpContext;

                if (!httpContext.Items.ContainsKey(nameof(RequestTelemetry)))
                {
                    throw new InvalidOperationException($"Register app insight logger using dependencyManager.{nameof(IDependencyManagerExtensions.RegisterApplicationInsights)}();");
                }

                requestTelemetry = (RequestTelemetry)httpContext.Items[nameof(RequestTelemetry)];

                IUserInformationProvider userInformationProvider = httpContext.RequestServices.GetRequiredService <IUserInformationProvider>();

                if (userInformationProvider.IsAuthenticated())
                {
                    requestTelemetry.Context.User.AccountId = requestTelemetry.Context.User.AuthenticatedUserId = userInformationProvider.GetCurrentUserId();
                }
            }

            List <KeyVal> keyValues = logEntry.LogData.Select(ld =>
            {
                string k = ld.Key;

                if (k == nameof(IRequestInformationProvider.HttpMethod) ||
                    k == nameof(IRequestInformationProvider.DisplayUrl) ||
                    k == nameof(IRequestInformationProvider.UserAgent) ||
                    k == "UserId" ||
                    k == "ResponseStatusCode" ||
                    k == nameof(IRequestInformationProvider.ClientIp) ||
                    ld.Value == null)
                {
                    return(null); // Already being logged by app insights!
                }
                string v = null;

                if (ld.Value is string valueAsStr)
                {
                    v = valueAsStr;
                }

                if (k == "ClientLogs" || k == "OperationArgs")
                {
                    v = Formatter.Serialize(ld.Value);
                }
                else
                {
                    v = ld.Value.ToString();
                }

                return(new KeyVal {
                    Key = k, Value = v
                });
            })
                                      .Where(d => d != null)
                                      .ToList();

            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.MemoryUsage), Value = logEntry.MemoryUsage.ToString()
            });

            if (logEntry.AppServerDateTime.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerDateTime), Value = logEntry.AppServerDateTime.ToString()
                });
            }

            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.Severity), Value = logEntry.Severity
            });
            keyValues.Add(new KeyVal {
                Key = nameof(LogEntry.Message), Value = logEntry.Message
            });

            if (logEntry.Id.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Id), Value = logEntry.Id.ToString()
                });
            }

            if (logEntry.AppServerThreadId.HasValue)
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerThreadId), Value = logEntry.AppServerThreadId.ToString()
                });
            }

            if (requestTelemetry != null)
            {
                LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));
                if (userAgent != null)
                {
                    requestTelemetry.Context.User.UserAgent = (string)userAgent.Value;
                }

                foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                {
                    if (!requestTelemetry.Properties.ContainsKey(keyVal.Key))
                    {
                        requestTelemetry.Properties.Add(keyVal.Key, keyVal.Value);
                    }
                }
            }
            else
            {
                TelemetryClient telemetryClient = new TelemetryClient();

                Dictionary <string, string> customData = new Dictionary <string, string>();

                foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                {
                    if (!customData.ContainsKey(keyVal.Key))
                    {
                        customData.Add(keyVal.Key, keyVal.Value);
                    }
                }

                Exception ex = null;

                try
                {
                    customData.TryGetValue("ExceptionTypeAssemblyQualifiedName", out string exceptionTypeAssemblyQualifiedName);

                    if (!string.IsNullOrEmpty(exceptionTypeAssemblyQualifiedName))
                    {
                        ex = (Exception)Activator.CreateInstance(Type.GetType(exceptionTypeAssemblyQualifiedName) ?? throw new InvalidOperationException($"{exceptionTypeAssemblyQualifiedName} could not be found"), args: new object[] { logEntry.Message });
                    }
                }
                catch { }

                if (ex == null)
                {
                    switch (logEntry.Severity)
                    {
                    case "Information":
                        ex = new InformationException(logEntry.Message);
                        break;

                    case "Warning":
                        ex = new WarningException(logEntry.Message);
                        break;

                    case "Error":
                        ex = new ErrorException(logEntry.Message);
                        break;

                    case "Fatal":
                        ex = new FatalException(logEntry.Message);
                        break;

                    default:
                        ex = new Exception(logEntry.Message);
                        break;
                    }
                }

                telemetryClient.TrackException(ex, customData);
            }
        }
        private void PerformLog(LogEntry logEntry)
        {
            TelemetryClient          telemetryClient         = null;
            IUserInformationProvider userInformationProvider = null;
            bool isPerRequestTelemetryClient = false;

            if (logEntry.LogData.Any(ld => ld.Key == nameof(IRequestInformationProvider.RequestUri)))
            {
                IOwinContext owinContext = OwinContext.Value;

                IDependencyResolver resolver = owinContext.GetDependencyResolver();

                telemetryClient = resolver.Resolve <TelemetryClient>();

                userInformationProvider = resolver.Resolve <IUserInformationProvider>();

                isPerRequestTelemetryClient = true;
            }

            List <KeyVal> keyValues = logEntry.LogData.Select(ld =>
            {
                string k = ld.Key;

                if (k == nameof(IRequestInformationProvider.HttpMethod) ||
                    k == nameof(IRequestInformationProvider.RequestUri) ||
                    k == nameof(IRequestInformationProvider.UserAgent) ||
                    k == "UserId" ||
                    k == "ResponseStatusCode" ||
                    k == nameof(IRequestInformationProvider.ClientIp) ||
                    ld.Value == null)
                {
                    return(null);
                }

                string v = null;

                if (ld.Value is string valueAsStr)
                {
                    v = valueAsStr;
                }

                if (k == "ClientLogs" || k == "OperationArgs")
                {
                    v = Formatter.Serialize(ld.Value);
                }
                else
                {
                    v = ld.Value.ToString();
                }

                return(new KeyVal {
                    Key = k, Value = v
                });
            })
                                      .Where(d => d != null)
                                      .ToList();

            try
            {
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppEnvironmentName), Value = logEntry.AppEnvironmentName
                });

                if (logEntry.AppServerProcessId.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerProcessId), Value = logEntry.AppServerProcessId.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerAppDomainName), Value = logEntry.AppServerAppDomainName
                });

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerOSVersion), Value = logEntry.AppServerOSVersion
                });

                if (logEntry.AppServerDateTime.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerDateTime), Value = logEntry.AppServerDateTime.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerName), Value = logEntry.AppServerName
                });

                if (logEntry.AppWasInDebugMode.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppWasInDebugMode), Value = logEntry.AppWasInDebugMode.ToString()
                    });
                }

                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppServerUserAccountName), Value = logEntry.AppServerUserAccountName
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.AppVersion), Value = logEntry.AppVersion
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.ApplicationName), Value = logEntry.ApplicationName
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Severity), Value = logEntry.Severity
                });
                keyValues.Add(new KeyVal {
                    Key = nameof(LogEntry.Message), Value = logEntry.Message
                });

                if (logEntry.Id.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.Id), Value = logEntry.Id.ToString()
                    });
                }

                if (logEntry.AppServerThreadId.HasValue)
                {
                    keyValues.Add(new KeyVal {
                        Key = nameof(LogEntry.AppServerThreadId), Value = logEntry.AppServerThreadId.ToString()
                    });
                }

                if (isPerRequestTelemetryClient == true)
                {
                    if (userInformationProvider.IsAuthenticated())
                    {
                        telemetryClient.Context.User.AccountId = telemetryClient.Context.User.AuthenticatedUserId = userInformationProvider.GetCurrentUserId();
                    }

                    LogData userAgent = logEntry.LogData.FirstOrDefault(ld => ld.Key == nameof(IRequestInformationProvider.UserAgent));
                    if (userAgent != null)
                    {
                        telemetryClient.Context.User.UserAgent = (string)userAgent.Value;
                    }

                    foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                    {
                        if (!telemetryClient.Context.Properties.ContainsKey(keyVal.Key))
                        {
                            telemetryClient.Context.Properties.Add(keyVal.Key, keyVal.Value);
                        }
                    }
                }
                else
                {
                    telemetryClient = new TelemetryClient();

                    Dictionary <string, string> customData = new Dictionary <string, string>();

                    foreach (KeyVal keyVal in keyValues.OrderBy(kv => kv.Key))
                    {
                        if (!customData.ContainsKey(keyVal.Key))
                        {
                            customData.Add(keyVal.Key, keyVal.Value);
                        }
                    }

                    Exception ex = null;

                    try
                    {
                        customData.TryGetValue("ExceptionTypeAssemblyQualifiedName", out string exceptionTypeAssemblyQualifiedName);

                        if (!string.IsNullOrEmpty(exceptionTypeAssemblyQualifiedName))
                        {
                            ex = (Exception)Activator.CreateInstance(Type.GetType(exceptionTypeAssemblyQualifiedName) ?? throw new InvalidOperationException($"{exceptionTypeAssemblyQualifiedName} could not be found"), args: new object[] { logEntry.Message });
                        }
                    }
                    catch { }

                    if (ex == null)
                    {
                        switch (logEntry.Severity)
                        {
                        case "Information":
                            ex = new InformationException(logEntry.Message);
                            break;

                        case "Warning":
                            ex = new WarningException(logEntry.Message);
                            break;

                        case "Error":
                            ex = new ErrorException(logEntry.Message);
                            break;

                        case "Fatal":
                            ex = new FatalException(logEntry.Message);
                            break;

                        default:
                            ex = new Exception(logEntry.Message);
                            break;
                        }
                    }

                    telemetryClient.TrackException(ex, customData);
                }
            }
            finally
            {
                telemetryClient.Flush();
            }
        }
Ejemplo n.º 26
0
 private static void LogFailedTask(Task task)
 {
     FatalException?.Invoke(null, new FatalExceptionEventArgs(
                                "RunInBackground task failed", task.Exception));
 }