Exemplo n.º 1
0
        public ActionContext([CallerMemberName] string name = null, IEnumerable <ISanitizer> logSanitizers = null)
        {
            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _parent        = _current.Value;
            _current.Value = this;

            ContextName = name;

            if (IsRoot)
            {
                Depth  = 0;
                State  = new ContextState(logSanitizers);
                Logger = new ContextLogger(this);
            }
            else
            {
                Depth = _parent.Depth + 1;
                State = _parent.State;

                Logger = _parent.Logger;
                Logger.TrySetContext(this);
            }

            Loaded?.Invoke(this);
        }
Exemplo n.º 2
0
        public void ContextLoggerCanSetContext()
        {
            const string message1 = "This is a test 1";
            const string message2 = "This is a test 2";

            using var context1 = new ActionContext("default", "TestContext1");
            using var context2 = new ActionContext("default", "TestContext2");

            var logger = new ContextLogger(context1);

            logger.Trace(message1);
            logger.TrySetContext(context2);
            logger.Trace(message2);

            Assert.NotNull(logger.LogEntries);
            Assert.Equal(2, logger.LogEntries.Count);

            var entries = logger.LogEntries.ToList();
            var entry1  = entries[0];
            var entry2  = entries[1];

            Assert.Equal(LogLevel.Trace, entry1.LogLevel);
            Assert.Equal(message1, entry1.Message);
            Assert.Equal(context1.Info.ContextName, entry1.ContextName);
            Assert.Equal(context1.Info.Id, entry1.ContextId);

            Assert.Equal(LogLevel.Trace, entry2.LogLevel);
            Assert.Equal(message2, entry2.Message);
            Assert.Equal(context2.Info.ContextName, entry2.ContextName);
            Assert.Equal(context2.Info.Id, entry2.ContextId);
        }
Exemplo n.º 3
0
        public TargetLogger()
        {
            var logger = new ContextLogger();

            targetEventSource  = new TargetEventSource(logger);
            buildEventSource   = new BuildEventSource(logger);
            projectEventSource = new ProjectEventSource(logger);
        }
Exemplo n.º 4
0
 public override void Trigger()
 {
     if (ContextLogger.OnSignalDispatch == null)
     {
         return;
     }
     ContextLogger.OnSignalDispatch(Signal);
     Pool <SignalDispatchLog> .Retire(this);
 }
Exemplo n.º 5
0
    public ContextLogger Build()
    {
        ContextLogger printer = new ContextLogger();

        if (!Context.Equals(null))
        {
            printer.Context = Context;
            printer.Level   = Level;
        }
        else
        {
            printer.Level = Level;
        }
        return(printer);
    }
Exemplo n.º 6
0
        public void ContextLoggerOutputsHighestLogLevelCorrectly(LogLevel[] levels, LogLevel expected)
        {
            const string message = "This is a test";

            using var context = new ActionContext("default", "TestContext");

            var logger = new ContextLogger(context);

            foreach (var level in levels)
            {
                logger.Log(level, message);
            }

            Assert.NotNull(logger);
            Assert.Equal(levels.Length, logger.LogEntries.Count);
            Assert.Equal(expected, logger.GetHighestLogLevel());
        }
Exemplo n.º 7
0
        public ActionContext(
            string contextGroupName                = "default",
            [CallerMemberName] string name         = null,
            ActionContextSettings settings         = null,
            IEnumerable <ISanitizer> logSanitizers = null)
        {
            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _parent = _namedContexts.GetOrAdd(contextGroupName, new AsyncLocal <ActionContext>()).Value;
            _namedContexts[contextGroupName].Value = this;

            ContextName      = name;
            ContextGroupName = contextGroupName;

            if (IsRoot)
            {
                Settings = settings ?? new ActionContextSettings();

                Depth  = 0;
                State  = new ContextState(logSanitizers);
                Logger = new ContextLogger(this);
            }
            else
            {
                Settings = _parent.Settings;

                Depth = _parent.Depth + 1;
                State = _parent.State;

                Logger = _parent.Logger;
                Logger.TrySetContext(this);
            }

            var shouldSuppressStartMessage = !IsRoot && Settings.SuppressChildContextStartMessages;
            var shouldAlwaysShowStart      = Settings.EnableContextStartMessage && !shouldSuppressStartMessage;

            Logger.Log(Settings.ContextStartMessageLevel,
                       $"Context {ContextName} has started.", !shouldAlwaysShowStart);

            Loaded?.Invoke(this);
        }
        public GenericPollerProcess(IUnityContainer container)
        {
            _container      = container;
            _idGuid         = Guid.NewGuid();
            _totalStopwatch = new Stopwatch();

            _assemblyLocator  = this._container.Resolve <IAssemblyLocator>();
            _assemblyResolver = this._container.Resolve <IAssemblyResolver>();
            _logger           = (ContextLogger)this._container.Resolve <ILogger>();
            _tracer           = (ContextTracer)this._container.Resolve <ITracer>();

            var config = this._container.Resolve <GenericPollerConfiguration>();

            _pollerSleepMilliseconds = config.DefaultSleepMilliseconds;

            ConfigureAutoShutdown(config);

            this._logger.OtherData["GenericPollerVersion"] = Assembly.GetExecutingAssembly().FullName;
            this._tracer.OtherData["GenericPollerVersion"] = Assembly.GetExecutingAssembly().FullName;
        }
Exemplo n.º 9
0
        public void ContextLoggerInformationOutputsSuccessfully()
        {
            const string message = "This is a test";

            using var context = new ActionContext("default", "TestContext");
            Thread.Sleep(10);

            var logger = new ContextLogger(context);

            logger.Information(message);

            var entry = logger.LogEntries?.FirstOrDefault();

            Assert.NotNull(entry);
            Assert.Single(logger.LogEntries);
            Assert.Equal(LogLevel.Information, entry.LogLevel);
            Assert.Equal(message, entry.Message);
            Assert.Equal(context.Info.ContextName, entry.ContextName);
            Assert.Equal(context.Info.Id, entry.ContextId);
            Assert.True(entry.TimeElapsed.TotalMilliseconds > 10);
        }
Exemplo n.º 10
0
        public void ContextLoggerOutputsSummaryCorrectly(LogLevel[] levels, LogLevel expectedLevel, string expectedMessage)
        {
            const string message = "This is a test";

            using var context = new ActionContext("default", "TestContext");
            Thread.Sleep(10);

            var logger = new ContextLogger(context);

            foreach (var level in levels)
            {
                logger.Log(level, message);
            }

            var summary = logger.GetSummaryLogEntry();

            Assert.NotNull(logger);
            Assert.Equal(levels.Length, logger.LogEntries.Count);
            Assert.Equal(context.Info.ContextName, summary.ContextName);
            Assert.Equal(context.Info.Id, summary.ContextId);
            Assert.Equal(expectedLevel, summary.LogLevel);
            Assert.StartsWith($"The context '{context.Info.ContextName}' ended {expectedMessage}", summary.Message);
            Assert.True(summary.TimeElapsed.TotalMilliseconds > 10);
        }
        /// <summary>
        /// TestCase results
        /// </summary>
        /// <param name="testStatus"></param>
        public void TestCaseResults(TestContext testContext)
        {
            TestStatus    testStatus    = testContext.Result.Outcome.Status;
            ResultAdapter resultAdapter = testContext.Result;

            object[]      endTestCaseParameterArray;
            List <string> testResults = new List <string>();
            TestResult    testResult  = TestResult.Inconclusive;

            Type                 myClass = Assembly.GetCallingAssembly().GetType(className);
            MethodInfo           EndOfTestCaseExecution = myClass.GetMethod("EndOfTestCaseExecution");
            TestBaseClassService myObj = (TestBaseClassService)Activator.CreateInstance(myClass);

            try
            {
                if (testStatus == TestStatus.Passed)
                {
                    if (Initialize.DisplayExecutionTimeInLogger)
                    {
                        watch.Stop();
                        timeElapsed = watch.ElapsedMilliseconds.ToString();
                    }

                    //Logging testcase details after pass
                    ContextLogger.LogAfterTestCasePass(moduleName, className, testCaseName, timeElapsed, testStatus.ToString());
                    endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, true };
                    EndOfTestCaseExecution.Invoke(myObj, endTestCaseParameterArray);
                    testResult = TestResult.Passed;
                }

                else if (testStatus == TestStatus.Failed)
                {
                    //Logging if test case fails
                    if (Initialize.DisplayExecutionTimeInLogger)
                    {
                        watch.Stop();
                        timeElapsed = watch.ElapsedMilliseconds.ToString();
                    }

                    //Logging testCase details after fails
                    ContextLogger.LogAfterTestCaseFails(moduleName, className, testCaseName, testDataService.TestData, timeElapsed, testStatus.ToString());
                    endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, false };
                    EndOfTestCaseExecution.Invoke(myObj, endTestCaseParameterArray);
                    testResult = TestResult.Failed;
                    testResults.Add(resultAdapter.Message);
                    testResults.Add(resultAdapter.StackTrace);
                }
                else if (testStatus == TestStatus.Skipped)
                {
                    //Logging if test case fails
                    if (Initialize.DisplayExecutionTimeInLogger)
                    {
                        watch.Stop();
                        timeElapsed = watch.ElapsedMilliseconds.ToString();
                    }

                    //Logging testCase details after fails
                    ContextLogger.LogAfterTestCaseSkipped(moduleName, className, testCaseName, timeElapsed, testStatus.ToString());
                    endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, false };
                    EndOfTestCaseExecution.Invoke(myObj, endTestCaseParameterArray);
                    testResult = TestResult.Skipped;
                    testResults.Add(resultAdapter.Message);
                }
                else if (testStatus == TestStatus.Inconclusive)
                {
                    if (Initialize.DisplayExecutionTimeInLogger)
                    {
                        watch.Stop();
                        timeElapsed = watch.ElapsedMilliseconds.ToString();
                    }

                    //Logging testCase details after fails
                    ContextLogger.LogAfterTestCaseInConclusive(moduleName, className, testCaseName, timeElapsed, testStatus.ToString());
                    endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, false };
                    EndOfTestCaseExecution.Invoke(myObj, endTestCaseParameterArray);
                    testResult = TestResult.Inconclusive;
                }
            }
            catch (IgnoreException ex)
            {
                //Logging testCase details after fails
                ContextLogger.LogAfterTestCaseSkipped(moduleName, className, testCaseName, timeElapsed, "Skipped" + ex.Message);
                endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, false };
                EndOfTestCaseExecution.Invoke(myObj, endTestCaseParameterArray);
                testResult = TestResult.Skipped;
            }
            catch (Exception ex)
            {
                ContextLogger.LogIfException(moduleName, className, testCaseName, ex.Message);
                endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, false };
                EndOfTestCaseExecution.Invoke(myObj, endTestCaseParameterArray);
                testResult = TestResult.Failed;
                if (testResults.Count == 0)
                {
                    testResults.Add("Test is executed with:" + testResult.ToString() + "status");
                }

                testResultService.InsertTestResults(testCaseName, testResult, testResults.ToArray());
            }
            finally
            {
                if (testResults.Count == 0)
                {
                    testResults.Add("Test is executed with:" + testResult.ToString() + "status");
                }

                testResultService.InsertTestResults(testCaseName, testResult, testResults.ToArray());
            }
        }
        /// <summary>
        /// Assign Query Filters base and other set on <see cref="IEntityTypeConfiguration{TEntity}">map</see>
        /// </summary>
        /// <param name="builder"></param>
        protected virtual void AssignTenantAndOtherQueryFilterOnModelCreating([NotNull] ModelBuilder builder)
        {
            foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
            {
                relationship.DeleteBehavior = DeleteBehavior.Restrict;
            }

            var allTypes = ScanAssemblyTypes();
            var tt       = GetAllEntityTypes(allTypes);


            foreach (Type entityType in tt)
            {
                var entityName     = entityType.Name;
                var entityFullName = entityType.FullName ?? entityName;

                try
                {
                    #region QueryFilters

                    var paramName = $"{entityName}_p";

                    var entityTypeFromModel = builder.Model.FindEntityType(entityFullName);
                    var queryFilter         = entityTypeFromModel.GetQueryFilter();
                    var queryParam          = queryFilter?.Parameters.FirstOrDefault();
                    if (null != queryParam)
                    {
                        paramName = queryParam.Name;
                    }


                    ParameterExpression paramExpr = Expression.Parameter(entityType, paramName);


                    Expression bodyDeleted = Expression.Equal(Expression.Property(paramExpr, "Deleted"),
                                                              Expression.Constant(false)
                                                              );
                    Expression body = null;
                    if (null != queryFilter)
                    {
                        var res = Expression.Lambda(Expression.Invoke(queryFilter, paramExpr), paramExpr);


                        body = Expression.AndAlso(bodyDeleted, res.Body);
                    }
                    else
                    {
                        body = bodyDeleted;
                    }


                    var name = $"TenantQueryFilter_{entityName}";

                    LambdaExpression lambdaExpr = Expression.Lambda(body, name,
                                                                    new List <ParameterExpression>()
                    {
                        paramExpr
                    }
                                                                    );

                    var entyTYpeBuilder = builder.Entity(entityType);


                    entyTYpeBuilder.HasQueryFilter(lambdaExpr);

                    #endregion
                }
                catch (Exception e)
                {
                    var err = $"Error configuring '{entityName}'";
                    ContextLogger?.LogCritical(err, e);
                    throw new Exception(err, e);
                }
            }
        }
Exemplo n.º 13
0
 public AssemblyResolver(IPollHandlerToolkit toolkit, ILogger logger)
 {
     this._toolkit = toolkit;
     this._logger = (ContextLogger)logger;
 }
Exemplo n.º 14
0
 public L2(string context) {
     _context = context;
     log = new ContextLogger(logBase, "[" + context + "] ");
     log.DebugFormat("L2 logger created");
 }
Exemplo n.º 15
0
        private void ReExecutionOfTestCase
            (string moduleName, string className, string testCaseName,
            int testDataOrder, int retryCount, Type myClass, TestBaseClassService testBaseClassServiceObj)
        {
            object[]   endTestCaseParameterArray;
            TestResult testResult    = TestResult.Inconclusive;
            Exception  exceptionType = null;

            int        trackRetryCount        = 0;
            MethodInfo ExecuteMethod          = myClass.GetMethod(testCaseName);
            MethodInfo EndOfTestCaseExecution = myClass.GetMethod("EndOfTestCaseExecution");

            try
            {
                //Intial value of i is 1
                for (int i = 1; i <= retryCount; i++)
                {
                    try
                    {
                        trackRetryCount = i;
                        // Get Global TestData for the project
                        testDataService.FillGlobalTestData(mongoRepository.GetTestProjectRepository.GetId(Initialize.ProjectName));
                        // Get test data for the current testCase
                        testDataService.FillTestData(mongoRepository.GetTestCaseRepository.GetId(testCaseName), testDataOrder);

                        //Logging before Re-testCase Execute
                        ContextLogger.LogRetryStart(moduleName, className, testCaseName, testDataService.TestData);

                        //STOPWATCH FOR CALCULATING EXECUTION TIME OF TESTCASE.
                        dynamic clock = null;

                        //Execution Timein Logger Condition
                        if (Initialize.DisplayExecutionTimeInLogger)
                        {
                            clock = Stopwatch.StartNew();
                        }

                        ExecuteMethod.Invoke(testBaseClassServiceObj, null);
                        testResult = TestResult.Passed;
                    }
                    catch (Exception exception)
                    {
                        exceptionType = exception;
                        ContextLogger.LogIfException(moduleName, className, testCaseName, exception.Message);

                        //Logging if test case fails
                        if (Initialize.DisplayExecutionTimeInLogger)
                        {
                            watch.Stop();
                            timeElapsed = watch.ElapsedMilliseconds.ToString();
                        }

                        //Logging testCase details after fails
                        ContextLogger.LogAfterRetryTestCaseFails(moduleName, className, testCaseName, testDataService.TestData, timeElapsed, "Failed On Exception");
                        if (trackRetryCount != retryCount)
                        {
                            endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, false };
                            EndOfTestCaseExecution.Invoke(testBaseClassServiceObj, endTestCaseParameterArray);
                        }
                        testResult = TestResult.Failed;
                    }
                }
            }
            catch (Exception exception)
            {
                ContextLogger.LogIfException(moduleName, className, testCaseName, exception.Message);
                throw exception;
            }
            finally
            {
                if (testResult.Equals(TestResult.Failed))
                {
                    throw exceptionType;
                }
            }
        }
Exemplo n.º 16
0
 public void Trace(string message, params object[] parameters)
 {
     ContextLogger.Verbose(message, parameters);
 }
Exemplo n.º 17
0
 public void Debug(string message, params object[] parameters)
 {
     ContextLogger.Debug(message, parameters);
 }
        /// <summary>
        /// Execute test cases
        /// </summary>
        /// <param name="className"></param>
        /// <param name="testCaseName"></param>
        /// <param name="testDataOrder"></param>
        public void ExecuteTestCase(string className, string testCaseName, int testDataOrder)
        {
            object[] endTestCaseParameterArray;

            //Get ModulName
            ObjectId moduleId = mongoRepository.GetTestClassRepository.GetByName(className).Module_id;

            moduleName = mongoRepository.GetTestModuleRepository.GetById(moduleId).ModuleType;

            Type                 myClass                = Assembly.GetCallingAssembly().GetType(className);
            MethodInfo           ExecuteMethod          = myClass.GetMethod(testCaseName);
            MethodInfo           EndOfTestCaseExecution = myClass.GetMethod("EndOfTestCaseExecution");
            TestBaseClassService myObj = (TestBaseClassService)Activator.CreateInstance(myClass);

            try
            {
                /* Initialize the className and testCaseName to static variable
                 * for access out side of the method */
                TestCaseService.className    = className;
                TestCaseService.testCaseName = testCaseName;

                // Get Global TestData for the project
                testDataService.FillGlobalTestData(mongoRepository.GetTestProjectRepository.GetId(Initialize.ProjectName));
                // Get test data for the current testCase
                testDataService.FillTestData(mongoRepository.GetTestCaseRepository.GetId(testCaseName), testDataOrder);

                //Is dependent testcase is executed and if is null ? true : false
                bool isDependentTestCaseSuccess = true;

                if (Initialize.IsDependencyCheckEnabled)
                {
                    isDependentTestCaseSuccess = IsDependentTestCaseExecuted(testCaseName);
                }

                if (isDependentTestCaseSuccess)
                {
                    //Logging before testCase Execute
                    ContextLogger.LogBeforeTestCase(moduleName, className, testCaseName, testDataService.TestData);

                    //Execution Timein Logger Condition
                    if (Initialize.DisplayExecutionTimeInLogger)
                    {
                        watch = Stopwatch.StartNew();
                    }

                    ExecuteMethod.Invoke(myObj, null);
                    TestStatus result = TestExecutionContext.CurrentContext.CurrentResult.ResultState.Status;
                }
                else
                {
                    Assert.Ignore("TestCase is skipped:" + testCaseName + ",due to parent testcase is failed/not executed");
                }
            }
            catch (TargetInvocationException exception) when(exception.InnerException is Exception)
            {
                ContextLogger.LogIfException
                    (moduleName, className, testCaseName, exception.Message);
                if (Initialize.RetryOnException)
                {
                    IList <Type> attributes  = GetAvailableAttributes(ExecuteMethod);
                    bool         isAvailable = attributes.Any(attribute => attribute.Name.Equals("RetryByAttribute"));
                    if (isAvailable)
                    {
                        if (Initialize.DisplayExecutionTimeInLogger)
                        {
                            watch.Stop();
                            timeElapsed = watch.ElapsedMilliseconds.ToString();
                            ContextLogger.LogAfterTestCaseFails
                                (moduleName, className, testCaseName, testDataService.TestData, timeElapsed, "Failed On Exception");
                        }

                        //Execute end of testcase execution if any object needs to be disposed
                        endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, false };
                        EndOfTestCaseExecution.Invoke(myObj, endTestCaseParameterArray);

                        //Retry attribute object
                        RetryByAttribute retryAttribute = ExecuteMethod.GetRetryByAttribute();
                        lock (lockReTestExecutionObj)
                        {
                            //Re-Execution of Exception TestCase
                            ReExecutionOfTestCase
                                (moduleName, className, testCaseName, testDataOrder, retryAttribute._tryCount, myClass, myObj);
                        }
                    }
                    else
                    {
                        throw exception;
                    }
                }
                else
                {
                    throw exception;
                }
            }
            catch (TargetInvocationException exception) when(exception.InnerException is AssertionException)
            {
                AssertionException assertException = exception.InnerException as AssertionException;

                ContextLogger.LogIfException(moduleName, className, testCaseName, exception.Message);
                if (Initialize.RetryOnException)
                {
                    IList <Type> attributes  = GetAvailableAttributes(ExecuteMethod);
                    bool         isAvailable = attributes.Any(attribute => attribute.Name.Equals("RetryByAttribute"));
                    if (isAvailable)
                    {
                        if (Initialize.DisplayExecutionTimeInLogger)
                        {
                            watch.Stop();
                            timeElapsed = watch.ElapsedMilliseconds.ToString();
                            ContextLogger.LogAfterTestCaseFails
                                (moduleName, className, testCaseName, testDataService.TestData, timeElapsed, assertException.ResultState.Status);
                        }
                        //Execute end of testcase execution if any object needs to be disposed
                        endTestCaseParameterArray = new object[] { moduleName, className, testCaseName, false };
                        EndOfTestCaseExecution.Invoke(myObj, endTestCaseParameterArray);

                        //Retry attribute object
                        RetryByAttribute retryAttribute = ExecuteMethod.GetRetryByAttribute();
                        lock (lockReTestExecutionObj)
                        {
                            //Re-Execution of Exception TestCase
                            ReExecutionOfTestCase
                                (moduleName, className, testCaseName, testDataOrder, retryAttribute._tryCount, myClass, myObj);
                        }
                    }
                    else
                    {
                        throw exception;
                    }
                }
                else
                {
                    throw exception;
                }
            }
        }
Exemplo n.º 19
0
 public void Info(string message, params object[] parameters)
 {
     ContextLogger.Information(message, parameters);
 }
Exemplo n.º 20
0
 public L2(string context)
 {
     _context = context;
     log      = new ContextLogger(logBase, "[" + context + "] ");
     log.DebugFormat("L2 logger created");
 }
Exemplo n.º 21
0
        private static void RunOptions(CommandLineOptions options)
        {
            // Build Container

            IContainer container = PluginManager.Compose();

            // Initialize Context Logger

            LogHelper     logHelper = container.Resolve <LogHelper>();
            ContextLogger logger    = logHelper.CreateContextLogger(Application.Current);

            // Test Logging

            string appVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            logger.Log(LogEventLevel.Information, "Ruminoid Studio - 版本{AppVersion}", appVersion);

            // Add Event Handler

            Application.Current.DispatcherUnhandledException += (sender, args) =>
            {
                args.Handled = true;

                logger.LogException(LogEventLevel.Error, "发生了一个故障。", args.Exception);

                new TaskDialog
                {
                    EnableHyperlinks = false,
                    MainInstruction  = "发生了一个故障。",
                    WindowTitle      = "灾难性故障",
                    Content          = args.Exception.Message,
                    MainIcon         = TaskDialogIcon.Error,
                    MinimizeBox      = false,
                    Buttons          =
                    {
                        new TaskDialogButton(ButtonType.Ok)
                    }
                }.ShowDialog();
            };

            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                if (!(args.ExceptionObject is Exception))
                {
                    return;
                }

                logger.LogException(LogEventLevel.Fatal, "发生了一个故障。", (Exception)args.ExceptionObject);

                new TaskDialog
                {
                    EnableHyperlinks = false,
                    MainInstruction  = "发生了一个故障。",
                    WindowTitle      = "灾难性故障",
                    Content          = ((Exception)args.ExceptionObject).Message ?? "Exception",
                    MainIcon         = TaskDialogIcon.Error,
                    MinimizeBox      = false,
                    Buttons          =
                    {
                        new TaskDialogButton(ButtonType.Ok)
                    }
                }.ShowDialog();
            };

            // Load Project

            logger.Log(LogEventLevel.Warning, "Lifecycle Helper: 开始加载项目。");

            ProjectManager projectManager = container.Resolve <ProjectManager>();

            projectManager.Load(options.ProjectFile);

            // Change Default Culture

            Resources.Culture = CultureInfo.CurrentUICulture;

            // Register Theme Service

            ThemeService.Current.Register(Application.Current, Theme.Windows, Accent.Windows);

            // Initialize Main Window

            Application.Current.MainWindow = new MainWindow();
            Application.Current.MainWindow.Show();

            // Change Default Theme

            Application.Current.Dispatcher?.Invoke(() => ThemeService.Current.ChangeTheme(Theme.Dark));
            Application.Current.Dispatcher?.Invoke(() => ThemeService.Current.ChangeAccent(Accent.Blue));
        }
Exemplo n.º 22
0
        public ActionContext(
            string contextGroupName                = "default",
            [CallerMemberName] string name         = null,
            ActionContextSettings settings         = null,
            IEnumerable <ISanitizer> logSanitizers = null)
        {
            _logSanitizers = logSanitizers?.ToList();

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _asyncLocalStacks.Value ??= new ConcurrentDictionary <string, ActionContextStack>();
            _namedStacks = _asyncLocalStacks.Value;
            _stack       = _namedStacks.GetOrAdd(contextGroupName, new ActionContextStack());

            _parent = _stack.Peek();
            _stack.Push(this);

            var id            = Guid.NewGuid();
            var causationId   = _parent?.Info.Id ?? id;
            var correlationId = _stack.CorrelationId;

            if (_parent == null)
            {
                Settings = settings ?? new ActionContextSettings();

                Info = new ContextInfo(
                    true,
                    0,
                    name,
                    contextGroupName,
                    _stack.CorrelationId);

                State  = new ContextState(_logSanitizers);
                Logger = new ContextLogger(this);
            }
            else
            {
                Settings = _parent.Settings;

                Info = new ContextInfo(
                    false,
                    _parent.Info.Depth + 1,
                    name,
                    contextGroupName,
                    _stack.CorrelationId,
                    _parent?.Info?.Id);

                State  = _parent.State;
                Logger = _parent.Logger;

                Logger.TrySetContext(this);
            }

            var entryType = Info.IsRoot ? ContextLogEntryType.ContextStart : ContextLogEntryType.ChildContextStart;

            Logger.LogAsType(Settings.ContextStartMessageLevel,
                             $"Context {Info.ContextName} has started.", entryType);

            Loaded?.Invoke(this);
        }
Exemplo n.º 23
0
 public void Warn(string message, params object[] parameters)
 {
     ContextLogger.Warning(message, parameters);
 }
Exemplo n.º 24
0
 public void Warn(Exception ex, string message, params object[] parameters)
 {
     ContextLogger.Warning(ex, message, parameters);
 }