コード例 #1
0
        public async Task <TimeSpan> Wait(TimeSpan timeout)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            if (DefaultLogger.IsDebug)
            {
                DefaultLogger.Debug(
                    $"[{_id}] Waiting for state {string.Join(",", _awaitedStates)} for {timeout.TotalSeconds} seconds");
            }

            if (_awaitedStates.Contains(_connection.State))
            {
                DefaultLogger.Debug($"Current state is {_connection.State}. Desired state reached.");
                return(TimeSpan.Zero);
            }

            _connection.On(Conn_StateChanged);
            var resultTask    = _taskCompletionSource.Task;
            var completedTask = await Task.WhenAny(resultTask, Task.Delay(timeout)).ConfigureAwait(false);

            if (completedTask == resultTask)
            {
                stopwatch.Stop();
                return(stopwatch.Elapsed);
            }

            DefaultLogger.Debug($"[{_id} Timeout exceeded. Throwing TimeoutException");
            RemoveListener();
            throw new TimeoutException(
                      $"Expected ''{_awaitedStates.Select(x => x.ToString()).JoinStrings()}' but current state was '{_connection.State}'");
        }
コード例 #2
0
 protected void importButton_Click(object sender, EventArgs e)
 {
     if (!Helper.HasImportFiles)
     {
         ImportStatus("No files found for import.");
     }
     else
     {
         var defaultLogger = new DefaultLogger();
         try
         {
             new Importers.Importer(new ImportSettings
             {
                 ImportProductCatalogGroups = importProductCatalogGroups.Checked,
                 ImportProductCatalogs = importProductCatalogs.Checked,
                 ImportProductCategories = importProductCategories.Checked,
                 ImportProducts = importProducts.Checked,
                 ImportMarketingFoundation = importMarketingFoundation.Checked,
                 PerformCleanUp = performCleanUp.Checked,
                 CmsProvider = new SitecoreProvider()
             }, Helper.SyncDataPath, defaultLogger).Import();
         }
         catch (Exception ex)
         {
             defaultLogger.Error(ex, "An unexpected error occurred during import");
         }
         if (defaultLogger.HasError)
             ImportStatus(string.Format("An error occurred - see log file ({0}) for details.",
                 WriteLog("import error", defaultLogger)));
         else
             ImportStatus("Imported completed.");
     }
 }
コード例 #3
0
        /// <summary>
        /// 通过字符串名获取ILog实例。
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns>ILog instance</returns>
        public static ILog GetLogger(string name)
        {
            string loggerName = name;

            if (string.IsNullOrEmpty(name) || name.Trim().Length == 0)
            {
                loggerName = "defaultLogger";
            }

            ILog log;

            if (!_logs.TryGetValue(loggerName, out log))
            {
                lock (lockObject)
                {
                    if (!_logs.TryGetValue(loggerName, out log))
                    {
                        log = new DefaultLogger(loggerName);
                        var newLogs = new Dictionary <string, ILog>(_logs);
                        newLogs.Add(loggerName, log);

                        _logs = newLogs;
                    }
                }
            }

            return(log);
        }
コード例 #4
0
        public static float AdjustPitch(AudioClip song, int sampleKey)
        {
            int key = KeyFinder.KeyFind(song);

            Log.Write("the key of song is " + key);

            //int sampleKey = 21; //GMinor

            int minMajDiff = (sampleKey % 2 == 0) ? -3 : 3;

            minMajDiff = ((key % 2) == (sampleKey % 2)) ? 0 : minMajDiff;

            Log.Write("minMajDiff is " + minMajDiff);

            int diff = ((int)(key - sampleKey) / 2 + minMajDiff + 24) % 12;

            float pitch = 1f;

            if (diff <= 7)
            {
                for (int i = 0; i < diff; i++)
                {
                    pitch *= SEMITONE;
                }
            }
            else
            {
                for (int i = 0; i < 12 - diff; i++)
                {
                    pitch /= SEMITONE;
                }
            }

            return(pitch);
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: deefault/LabApp
        public static int Main(string[] args)
        {
            DefaultLogger.CreateNlog(null);
            var logger = DefaultLogger.CreateNlog(null);

            try
            {
                var host = CreateHostBuilder(args).Build();

                using (var serviceScope = host.Services.GetRequiredService <IServiceScopeFactory>().CreateScope())
                    using (var context = serviceScope.ServiceProvider.GetService <AppDbContext>())
                    {
                        logger.Info("Migrations started ...");
                        context.Database.Migrate();
                        logger.Info("Migrations finished.");
                    }

                host.Run();
            }
            catch (Exception exception)
            {
                logger.Error(exception, "Stopped program because of exception");

                return(1);
            }
            finally
            {
                NLog.LogManager.Shutdown();
            }

            return(0);
        }
コード例 #6
0
        private bool isDisposed = false;         // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                    // TODO: delete managed state (managed objects).

                    if (assimpImporter != null)
                    {
                        assimpImporter.Dispose();
                    }

                    if (context != null)
                    {
                        context.threads.Dispose();
                    }

                    DefaultLogger.kill();
                }

                // TODO: free unmanaged resources (unmanaged objects) and replace finalizer below.
                // TODO: set fields of large size with null value.

                isDisposed = true;
            }
        }
コード例 #7
0
        public void TestNumber()
        {
            var logger    = new DefaultLogger();
            var targeting = new Flagship.Services.Bucketing.TargetingMatch(logger);

            Assert.IsTrue(targeting.MatchNumber(1, TargetingOperator.EQUALS, 1));
            Assert.IsFalse(targeting.MatchNumber(2, TargetingOperator.EQUALS, 3));

            Assert.IsFalse(targeting.MatchNumber(1, TargetingOperator.NOT_EQUALS, 1));
            Assert.IsTrue(targeting.MatchNumber(2, TargetingOperator.NOT_EQUALS, 3));

            Assert.IsTrue(targeting.MatchNumber(2, TargetingOperator.GREATER_THAN, 1));
            Assert.IsFalse(targeting.MatchNumber(1, TargetingOperator.GREATER_THAN, 1));
            Assert.IsFalse(targeting.MatchNumber(1, TargetingOperator.GREATER_THAN, 2));

            Assert.IsTrue(targeting.MatchNumber(2, TargetingOperator.GREATER_THAN_OR_EQUALS, 1));
            Assert.IsTrue(targeting.MatchNumber(1, TargetingOperator.GREATER_THAN_OR_EQUALS, 1));
            Assert.IsFalse(targeting.MatchNumber(1, TargetingOperator.GREATER_THAN_OR_EQUALS, 2));

            Assert.IsTrue(targeting.MatchNumber(1, TargetingOperator.LOWER_THAN, 2));
            Assert.IsFalse(targeting.MatchNumber(1, TargetingOperator.LOWER_THAN, 1));
            Assert.IsFalse(targeting.MatchNumber(2, TargetingOperator.LOWER_THAN, 1));

            Assert.IsTrue(targeting.MatchNumber(1, TargetingOperator.LOWER_THAN_OR_EQUALS, 2));
            Assert.IsTrue(targeting.MatchNumber(1, TargetingOperator.LOWER_THAN_OR_EQUALS, 1));
            Assert.IsFalse(targeting.MatchNumber(2, TargetingOperator.LOWER_THAN_OR_EQUALS, 1));

            Assert.IsFalse(targeting.MatchNumber(1, TargetingOperator.CONTAINS, 1), "Unhandled targeting operator should not match");
            Assert.IsFalse(targeting.MatchNumber(1, TargetingOperator.NULL, 1), "Unhandled targeting operator should not match");
        }
コード例 #8
0
        public override void OnException(ExceptionContext context)
        {
            if (context.Exception is AggregateException)
            {
                AggregateException aggregateException = context.Exception as AggregateException;
                foreach (Exception exception in aggregateException.InnerExceptions)
                {
                    DefaultLogger.Error(exception);
                }
                context.Exception = aggregateException.InnerException;
            }

            if (context.Exception is UnauthorizedAccessException)
            {
                context.HttpContext.Response.StatusCode = 401;
            }
            else
            {
                // Unhandled errors
#if !DEBUG
                var    errorMessage = "An unhandled error occurred.";
                string callStack    = null;
#else
                var    errorMessage = context.Exception.GetBaseException().Message;
                string callStack    = context.Exception.StackTrace;
#endif

                context.HttpContext.Response.StatusCode = 500;
            }
            // handle logging here
            JMResult result = context.HttpContext.RequestServices.GetRequiredService <IExceptionHandler>().HandleException(context.Exception);
            //always return a JSON result
            context.Result = new JsonResult(result);
            base.OnException(context);
        }
コード例 #9
0
        /// <summary>
        /// Loads the logger.
        /// </summary>
        private void LoadLogger()
        {
            var type = typeof(ILogger);

            if (Logger == null)
            {
                var availableTypes =
                    TypeFinder.GetAssembliesWithKnownExclusions()
                    .SelectMany(a => a.GetLoadableTypes())
                    .Where(t => type.IsAssignableFrom(t) && t.IsClass && !t.IsAbstract)
                    .ToList();

                // There's more than one so load the first that is not our default.
                if (availableTypes.Count > 1)
                {
                    Logger = availableTypes.Where(l => l != typeof(DefaultLogger))
                             .Select(f => (Activator.CreateInstance(f) as ILogger))
                             .First();
                }
                else
                {
                    Logger = new DefaultLogger();
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// 构造方法
        /// </summary>
        public DbEngineConfigurationSection()
        {
            DatabaseSets      = new List <DatabaseSetElement>();
            DatabaseSets      = DatabaseProviderElementCollection.DatabaseSetElement();
            DatabaseProviders = new DatabaseProviderElementCollection();
            ConnectionLocator = new ConnectionLocatorElement();
            DefaultLogger defaultLogger = new DefaultLogger();

            System.Threading.Tasks.Task.Run(() =>
            {
                bool bo = true;
                while (bo)
                {
                    bo = false;
                    try
                    {
                        defaultLogger.RunLog();
                    }
                    catch (Exception)
                    {
                        bo = true;
                    }
                }
            });

            //logListeners = new ConfigurationProperty("logListeners", typeof(ListenerElementCollection), null, ConfigurationPropertyOptions.None);
            //metrics = new ConfigurationProperty("metrics", typeof(MetricsElement), null, ConfigurationPropertyOptions.None);
            //tracing = new ConfigurationProperty("tracing", typeof(TracingElement), null, ConfigurationPropertyOptions.None);
            //log = new ConfigurationProperty("log", typeof(LoggingElement), null, ConfigurationPropertyOptions.None);
            //connectionLocator = new ConfigurationProperty("connectionLocator", typeof(ConnectionLocatorElement), null, ConfigurationPropertyOptions.None);
            //rw = new ConfigurationProperty("rw", typeof(RWSplittingElement), null, ConfigurationPropertyOptions.None);
            //executor = new ConfigurationProperty("executor", typeof(ExecutorElement), null, ConfigurationPropertyOptions.None);
        }
コード例 #11
0
        public void SetupInfrastructure()
        {
            var metadata = new ScenarioMetadata
            {
                FeatureName  = FeatureContext.FeatureInfo.Title,
                ScenarioName = ScenarioContext.ScenarioInfo.Title
            };

            Register(metadata);

            var factory = new PossumLabs.Specflow.Core.Variables.ObjectFactory();

            Register(factory);
            Register(new PossumLabs.Specflow.Core.Variables.Interpeter(factory));
            var logger = new DefaultLogger(new DirectoryInfo(Environment.CurrentDirectory));

            Register((PossumLabs.Specflow.Core.Logging.ILog)logger);
            Register(new PossumLabs.Specflow.Core.Exceptions.ActionExecutor(logger));

            Register(new FileManager(new DatetimeManager()
            {
                Now = () => DateTime.Now
            }));
            FileManager.Initialize(FeatureContext.FeatureInfo.Title, ScenarioContext.ScenarioInfo.Title, null /*Specflow limitation*/);
            var templateManager = new PossumLabs.Specflow.Core.Variables.TemplateManager();

            templateManager.Initialize(Assembly.GetExecutingAssembly());
            Register(templateManager);

            Log.Message($"feature: {FeatureContext.FeatureInfo.Title} scenario: {ScenarioContext.ScenarioInfo.Title} \n" +
                        $"Tags: {FeatureContext.FeatureInfo.Tags.LogFormat()} {ScenarioContext.ScenarioInfo.Tags.LogFormat()}");
        }
コード例 #12
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // Initialize the logger system
            DefaultLogger.Initialize(this, "../../../DefaultLog.txt");
            EntityIoLogger.Initialize("../../../IoLogfile.txt");

            // Give the IOC container a refence to the game.
            IocContainer.SetGameReference(this);

            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            // Resolve controllers
            _entityController     = IocContainer.Resolve <IEntityController>();
            _renderableController = IocContainer.Resolve <IRenderableController>();
            _aiController         = IocContainer.Resolve <IAiController>();
            _collidableController = IocContainer.Resolve <ICollidableController>();
            _playerController     = IocContainer.Resolve <IInteractiveController>();

            // Resolve messaging system
            _entityMessagingSystem = IocContainer.Resolve <IPriorityMessageQueue>();


            base.Initialize();
        }
コード例 #13
0
        public async Task <TimeSpan> Wait(TimeSpan timeout)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            if (DefaultLogger.IsDebug)
            {
                DefaultLogger.Debug($"[{_id}] Waiting for state {string.Join(",", _awaitedStates)} for {timeout.TotalSeconds} seconds");
            }

            if (_awaitedStates.Contains(Connection.State))
            {
                DefaultLogger.Debug($"Current state is {Connection.State}. Desired state reached.");
                return(TimeSpan.Zero);
            }

            Connection.InternalStateChanged += conn_StateChanged;
            var tResult    = _taskCompletionSource.Task;
            var tCompleted = await Task.WhenAny(tResult, Task.Delay(timeout)).ConfigureAwait(true);

            if (tCompleted == tResult)
            {
                stopwatch.Stop();
                return(stopwatch.Elapsed);
            }

            DefaultLogger.Debug($"[{_id} Timeout exceeded. Throwing TimeoutException");
            RemoveListener();
            throw new TimeoutException();
        }
コード例 #14
0
        public TestForm(string pUsername, string pPassword, string pMailserver)
        {
            EmailUsername = pUsername;
            EmailPassword = pPassword;
            MailServer    = pMailserver;
            InitializeComponent();
            DefaultLogger.SetLog(new FileLogger());
            FileLogger.Enabled     = true;
            FileLogger.Verbose     = true;
            tmrMailChecker.Enabled = true;
            pop3Client             = new Pop3Client();
            string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string file   = Path.Combine(myDocs, "OpenPopLogin.txt");

            if (File.Exists(file))
            {
                using (StreamReader reader = new StreamReader(File.OpenRead(file)))
                {
                    popServerTextBox.Text  = reader.ReadLine();                       // Hostname
                    portTextBox.Text       = reader.ReadLine();                       // Port
                    useSslCheckBox.Checked = bool.Parse(reader.ReadLine() ?? "true"); // Whether to use SSL or not
                    loginTextBox.Text      = reader.ReadLine();                       // Username
                    passwordTextBox.Text   = reader.ReadLine();                       // Password
                }
            }
            tmrMailChecker.Enabled = true;
            CheckTEmailRecivetimer = new System.Threading.Timer(this.CheckTEmailRecivetimerCheck, this, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(60));
        }
コード例 #15
0
        private void ParseRequest(Stream stream, DefaultLogger logger)
        {
            MemoryStream buffer = new MemoryStream();

            ReadToBuffer(stream, buffer);

            string startLine = ReadLine(stream, buffer);

            ParseStartLine(startLine);

            string headerLine = ReadLine(stream, buffer);

            while (headerLine != String.Empty)
            {
                ParseHeaderLine(headerLine);
                headerLine = ReadLine(stream, buffer);
            }

            ReadMessageBody(stream, buffer);
            if (Logging.TraceEnabled)
            {
                long position = buffer.Position;
                buffer.Position = 0;
                byte[]       bytes   = new byte[position];
                StreamReader reader  = new StreamReader(buffer);
                string       message = reader.ReadToEnd();
                if (message.Contains("\0"))
                {
                    message = message.Substring(0, message.IndexOf("\0"));
                }
                logger.TraceMessage(message);
                buffer.Position = position;
            }
        }
コード例 #16
0
        public ScanMail_Auto()
        {
            InitializeComponent();
            FillGrid_MailList();
            DefaultLogger.SetLog(new FileLogger());

            // Enable file logging and include verbose information
            FileLogger.Enabled = true;
            FileLogger.Verbose = true;

            pop3Client = new Pop3Client();

            //讀取設定檔
            // This is only for faster debugging purposes
            // We will try to load in default values for the hostname, port, ssl, username and password from a file
            string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string file   = Path.Combine(myDocs, "OpenPopLogin.txt");

            if (File.Exists(file))
            {
                using (StreamReader reader = new StreamReader(File.OpenRead(file)))
                {
                    // This describes how the OpenPOPLogin.txt file should look like
                    popServerTextBox.Text  = reader.ReadLine();                       // Hostname
                    portTextBox.Text       = reader.ReadLine();                       // Port
                    useSslCheckBox.Checked = bool.Parse(reader.ReadLine() ?? "true"); // Whether to use SSL or not
                    //loginTB.Text = reader.ReadLine(); // Username
                    //passwordTB.Text = reader.ReadLine(); // Password
                }
            }
        }
コード例 #17
0
        public static bool Setup()
        {
            if (isInited)
            {
                return(true);
            }

            isInited = true;
            bool ret = false;

            lock (logTable)
            {
                ret = NAdvLogWrapper.Init();
                if (ret)
                {
                    DefaultLogger = GetLogger(dafaultLogName);
                }
            }

            if (DefaultLogger != null)
            {
                DefaultLogger.Debug("==================================================");
                DefaultLogger.Debug("############### Application Started ###############");
                DefaultLogger.Debug("==================================================");
            }
            LogFile = NAdvLogWrapper.GetLogFile();
            return(ret);
        }
コード例 #18
0
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            if (tbNewUser.Text == "")
            {
                AppUtility.ShowKryptonMessageBox("No User Name", "Please input user name", "", ComponentFactory.Krypton.Toolkit.TaskDialogButtons.OK, MessageBoxIcon.Error, this);
                return;
            }

            if (_allUsers.ChildExists(tbNewUser.Text))
            {
                AppUtility.ShowKryptonMessageBox("Duplicate User Name", String.Format("User name \"{0}\" already exist.", tbNewUser.Text), "", ComponentFactory.Krypton.Toolkit.TaskDialogButtons.OK, MessageBoxIcon.Error, this);
                return;
            }

            try
            {
                DefaultLogger logger = U.GetComponent(AppConstStaticName.DEFAULT_LOGGER) as DefaultLogger;
                logger.Abort();
                AppUserInfo newUser = new AppUserInfo(tbNewUser.Text);
                newUser.Initialize();
                _allUsers.Add(newUser);
                newUser.InitializeIDReferences();
                logger.Abort();
                componentBrowser.Rebuild(_allUsers);
                AppUtility.ShowKryptonMessageBox("Add New User Completed", String.Format("Add New User \"{0}\" Completed", tbNewUser.Text), "", ComponentFactory.Krypton.Toolkit.TaskDialogButtons.OK, MessageBoxIcon.Information, this);
                tbNewUser.Clear();
            }
            finally
            {
            }
        }
コード例 #19
0
        public async Task <(bool, ConnectionState?)> Wait(TimeSpan timeout)
        {
            if (DefaultLogger.IsDebug)
            {
                DefaultLogger.Debug($"[{_id}] Waiting for state change for {timeout.TotalSeconds} seconds");
            }

            TaskCompletionSource <(bool, ConnectionState?)> taskCompletionSource =
                new TaskCompletionSource <(bool, ConnectionState?)>();

            try
            {
                _connection.InternalStateChanged += ChangeListener;
                var tResult = taskCompletionSource.Task;
                return(await tResult.TimeoutAfter(timeout, (false, null)));
            }
            finally
            {
                _connection.InternalStateChanged -= ChangeListener;
            }

            void ChangeListener(object sender, ConnectionStateChange change)
            {
                _currentState = change.Current;
                taskCompletionSource.SetResult((true, _currentState));
            }
        }
コード例 #20
0
        public static ILogger GetLogger(ILoggable instance)
        {
            ILogger result;

            if (instance == null)
            {
                return(null);
            }
            var depth = LoggableRecursionGuard.Value;

            try
            {
                LoggableRecursionGuard.Value++;
                if (depth == 0)
                {
                    result = instance.Logger;
                    if (result != null)
                    {
                        return(result);
                    }
                }

                var name = (instance as INamed)?.Name ?? Convert.ToString(instance);
                result = new DefaultLogger(name, GetDefaultAppenders(), null);
            }
            finally
            {
                LoggableRecursionGuard.Value = depth;
            }

            return(result);
        }
コード例 #21
0
 /// <summary>
 /// 默认配置信息
 /// 使用<see cref="DefaultLogger"/>和<see cref="DefaultHttpLogger"/>
 /// 处理顺序:<see cref="ConnectionHandler"/>=><see cref="RetryHandler"/>=><see cref="LoggingHandler"/>
 /// </summary>
 /// <param name="path">日志目录</param>
 public HttpClientConfigs(string path)
 {
     Logger            = new DefaultLogger(path);
     ConnectionHandler = new HttpConnectionHandler(Logger);
     HttpLogger        = new DefaultHttpLogger(path);
     LoggingHandler    = new HttpLoggingHandler(ConnectionHandler, HttpLogger);
     RetryHandler      = new HttpRetryHandler(LoggingHandler, Logger);
 }
コード例 #22
0
        protected void HandlePostImport()
        {
            DefaultLogger l = new DefaultLogger();

            new PostImport(l).Process();

            WriteLogs(l);
        }
コード例 #23
0
        protected void HandlePostImport()
        {
            DefaultLogger      l = new DefaultLogger();
            InformaPostProcess p = new InformaPostProcess(l);

            p.UpdateArticleReferences();

            WriteLogs(l);
        }
コード例 #24
0
        public async Task Test()
        {
            var embed = _defaultEmbedGenerator
                        .GenerateNotFoundEmbed("TestModule", "TestCommand", "Title", "Command was not found!").Build();
            await DefaultLogger.Logger(new LogMessage(LogSeverity.Error, "TestModule", "TestModule has crashed!",
                                                      new DllNotFoundException()));

            await ReplyAsync("", embed : embed);
        }
コード例 #25
0
        protected void HandleImport(IDataMap map, DefaultLogger l)
        {
            ImportProcessor p = new ImportProcessor(map, l);

            p.Process();
            txtMessage.Text = l.GetLog();

            WriteLogs(l);
        }
コード例 #26
0
    /// <summary>
    /// Creates/initializes common infrastructure objects [Configuration, Logging, AppSetting] that are not previously added to <see cref="IServiceCollection" />.
    /// <remarks>
    /// Note: the objects [Configuration, Logging, AppSetting] will only be created/initialized if not added in:
    ///   - ConfigureCoreServices
    ///   - CoreServices
    ///   - ConfigureServices
    /// </remarks>
    /// </summary>
    /// <param name="serviceProvider">The <see cref="IServiceProvider"/> for application services.</param>
    /// <exception cref="Exception"></exception>
    public virtual void Initialize(IServiceProvider serviceProvider)
    {
        if (!_servicesConfigured || !_coreServicesConfigured || !_resolversConfigured || !_defaultHandlersConfigured)
        {
            throw new Exception("Services must be configured before application is initialized.");
        }

        #region Configuration

        var config = serviceProvider.GetService <IChromelyConfiguration>();
        if (config is null)
        {
            config = DefaultConfiguration.CreateForRuntimePlatform();
        }

        ChromelyApp.InitConfiguration(config);

        #endregion Configuration

        #region Application/User Settings

        var appSettings = serviceProvider.GetService <IChromelyAppSettings>();
        if (appSettings is null)
        {
            appSettings = new DefaultAppSettings();
        }

        var currentAppSettings = new CurrentAppSettings
        {
            Properties = appSettings
        };

        ChromelyAppUser.App = currentAppSettings;
        ChromelyAppUser.App.Properties.Read(config);

        #endregion

        #region Logger

        var logger = GetCurrentLogger(serviceProvider);
        if (logger is null)
        {
            logger = new SimpleLogger();
        }

        var defaultLogger = new DefaultLogger
        {
            Log = logger
        };
        Logger.Instance = defaultLogger;

        #endregion

        EnsureExpectedWorkingDirectory();

        _servicesInitialized = true;
    }
コード例 #27
0
 private void conn_StateChanged(object sender, ConnectionStateChange e)
 {
     if (_awaitedStates.Contains(e.Current))
     {
         DefaultLogger.Debug($"[{_id}] Desired state was reached.");
         RemoveListener();
         _taskCompletionSource.SetResult(true);
     }
 }
コード例 #28
0
ファイル: Manager.cs プロジェクト: DominikWiesend/wiesend-dll
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="Loggers">The loggers.</param>
 public Manager(IEnumerable <ILogger> Loggers)
 {
     Contract.Requires <ArgumentNullException>(Loggers != null, "Loggers");
     LoggerUsing = Loggers.FirstOrDefault(x => !x.GetType().Namespace.StartsWith("WIESEND", StringComparison.OrdinalIgnoreCase));
     if (LoggerUsing == null)
     {
         LoggerUsing = new DefaultLogger();
     }
 }
コード例 #29
0
        public HDEHost()
        {
            FUseAppdata = Environment.GetCommandLineArgs().Contains("/appdata");

            // Set vvvv.exe path
            ExePath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName((typeof(HDEHost).Assembly.Location)), @"..\.."));

            //add repository paths from commandline
            //from commandline
            var repoArg             = "/package-repositories";
            var packageRepositories = ExtractPaths(repoArg);

            AssemblyLoader.AddPackageRepositories(packageRepositories);

            //the built-in one
            if (Directory.Exists(PacksPath))
            {
                AssemblyLoader.AddPackageRepository(PacksPath);
            }
            //the one where the user is supposed to install packages to share it between vvvversions
            if (FUseAppdata)
            {
                if (Directory.Exists(UserPacksPath))
                {
                    AssemblyLoader.AddPackageRepository(UserPacksPath);
                }
            }
            //the legacy path
            if (Directory.Exists(UserPacksPathLegacy))
            {
                AssemblyLoader.AddPackageRepository(UserPacksPathLegacy);
            }

            // Set name to vvvv thread for easier debugging.
            Thread.CurrentThread.Name = "vvvv";

            // Create a windows forms sync context (FileSystemWatcher runs asynchronously).
            SynchronizationContext.SetSynchronizationContext(new MySynchronizationContext());

            // Register at least one ICommandHistory for top level element ISolution
            var mappingRegistry = new MappingRegistry();

            mappingRegistry.RegisterMapping <ISolution, ICommandHistory, CommandHistory>(MapInstantiation.PerInstanceAndItsChilds);

            var location = Shell.CallerPath.ConcatPath(@"..\..\lib\nodes\plugins").ConcatPath("Solution.sln");

            Solution = new Solution(location, mappingRegistry);

            EnumManager.SetHDEHost(this);

            Logger = new DefaultLogger();

            IORegistry = new IORegistry();

            // Will tell Windows Forms that a message loop is indeed running
            Application.RegisterMessageLoop(IsSendingMessages);
        }
コード例 #30
0
        protected UpgradeTaskBase(string name, string installDirectory, string folderPrefix = null)
        {
            Logger = DefaultLogger.Get(GetType());

            Name             = name;
            InstallDirectory = installDirectory;
            _folderPrefix    = folderPrefix ?? name;
            _versionRegex    = new Regex($@"^{_folderPrefix}-(\d+?\.\d+?\.\d+?)$", RegexOptions.Compiled);
        }
コード例 #31
0
        /// <summary>
        /// Create a file where to output the  logs of assimp import process.
        /// </summary>
        /// <param name="filename">The name of the file wher to write the logs.</param>
        public void SetLogFile(string filename)
        {
            if (!DefaultLogger.isNullLogger())
            {
                DefaultLogger.kill();
            }

            DefaultLogger.create(filename, global::Assimp.Logger.LogSeverity.VERBOSE, aiDefaultLogStream.aiDefaultLogStream_FILE);
        }
コード例 #32
0
        public void Error_RandomString_Void()
        {
            // arrange.

            var test = new DefaultLogger();

            // act.
            test.Error("yay", new Exception(), this);

            // assert.
            Assert.IsNotNull(test);

        }
コード例 #33
0
        public void Fatal_RandomString_Void()
        {
            // arrange.

            var test = new DefaultLogger();

            // act.
            test.Fatal("yay", this);

            // assert.
            Assert.IsNotNull(test);

        }
コード例 #34
0
 protected void btnExport_OnClick(object sender, EventArgs e)
 {
     var defaultLogger = new DefaultLogger();
     DownloadStatus(null);
     try
     {
         new Exporters.Exporter(new ExportSettings
         {
             ExportProducts = cbExportProducts.Checked,
             CmsProvider = new SitecoreProvider()
         }, Helper.SyncDataPath, defaultLogger).Export();
     }
     catch (Exception ex)
     {
         defaultLogger.Error(ex, "An unexpected error occurred during export");
     }
     if (defaultLogger.HasError)
     {
         ExportStatus(string.Format("An error occorred - see log file ({0}) for details.",
             WriteLog("export error", defaultLogger)));
     }
     else
         ExportStatus("Export completed.");
 }
コード例 #35
0
ファイル: Main.cs プロジェクト: knoxknox/dev-labs
 static Logger()
 {
   Current = new DefaultLogger();
 }