FileLoger Class : LogBase
Inheritance: LogBase
Esempio n. 1
0
        static void Main(string[] args)
        {
            //find out how to initialize Engine property of the Task in .NET 4 version of MSBuild
            Engine engine = new Engine();
            engine.BinPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.System)
                + @"\..\Microsoft.NET\Framework\v2.0.50727";

            FileLogger logger = new FileLogger();
            logger.Parameters = @"logfile=C:\temp\test.msbuild.log";
            engine.RegisterLogger(logger);

            string[] tasks = new string[] { "MyTask" };
            BuildPropertyGroup props = new BuildPropertyGroup();
            props.SetProperty("parm1","hello Build!");

            var task = new RazorCodeGen();
            const string path = @"C:\work\projects\SyncCloud.Backend\AirPlans.Web\";
            task.ProjectRoot = path;
            task.CodeGenDirectory = Path.Combine(task.ProjectRoot, @"obj\CodeGen\Views\");
            var allViewFiles = Directory.EnumerateFiles(Path.Combine(task.ProjectRoot, @"Views\"), "*.cshtml", SearchOption.AllDirectories).ToList();
            task.FilesToPrecompile = allViewFiles.Select(x => new TaskItem(x)).ToArray();

            task.Execute();

            Console.ReadKey();
        }
Esempio n. 2
0
 private static void Main(string[] args)
 {
     var logger = new FileLogger();
     logger.OpenLog();
     logger.Log("Hello World!");
     logger.Log("Just another log message");
     logger.CloseLog();
 }
Esempio n. 3
0
 public MainForm()
 {
     InitializeComponent();
     r_FacebookConfig = FacebookConfig.LoadFromFile(k_ConfigFileName);
     m_FileLoger = new FileLogger(r_FacebookConfig.LogFilePath);
     r_FacebookClient = new FacebookClientTraceLoggerProxy(new FacebookClient(r_FacebookConfig), m_FileLoger);
     m_PopularityFactory = new PopularityFactory(r_FacebookClient);
     OnError += this.showError;
     OnError += (sender, error) => m_FileLoger.Error(error.GetException().Message, error.GetException());
 }
Esempio n. 4
0
    public static void Main()
    {
        FileLogger fl = new FileLogger("process.log");

          MyClass myClass = new MyClass();

          MyClass.LogHandler lh = new MyClass.LogHandler(fl.Logger);

          myClass.Process(lh);
          fl.Close();
    }
		public ILog GetFileLogger(string name, string logFileName, LogLevel level)
		{
			lock (loggers)
			{
				if (loggers.ContainsKey(name))
				{
					return loggers[name];
				}

				ILog logger = new FileLogger(Path.GetDirectoryName(logFileName), Path.GetFileName(logFileName), level);
				loggers.Add(name, logger);

				return logger;
			}
		}
        protected void debugFileLoggerTestCallback(IWrite iWrite, string cmdName, object[] cmdArguments)
        {
            // I can use FileLoggerTestDataSimple or FileLoggerTestData structures - both work
            FileLogger<FileLoggerTestData> logger = new FileLogger<FileLoggerTestData>("test", "test.csv", false, "");
            logger.Start();

            // add an entry to the log
            logger.AddEntry(new FileLoggerTestData());

            // wait little bit before I tear the logger down - i want to let the logger to finish writing
            Thread.Sleep(200);

            logger.Stop();
            logger.Dispose();
        }
Esempio n. 7
0
        private static void DemoFileLogger()
        {
            Console.Write("using file logger ... ");
            var logger = new FileLogger
            {
                FileNameTemplate = "dotlog-##.log",
                LogLevel = LogLevel.Verbose, // this is the default
                LogPath = "Logs", // this is the default
            };

            logger.Log("test entry 1");
            logger.Log("test entry 2", LogLevel.Verbose);
            logger.Log("test entry 3", LogLevel.Verbose, "example category");

            Console.WriteLine("log saved to: " + logger.FullPathName);
        }
Esempio n. 8
0
        public void LogLineShouldWriteTextEndingWithNewLineToTheFile()
        {
            const string FileName = "LogLineShouldWriteTextEndingWithNewLineToTheFile.txt";
            const string Message = "тест";

            if (File.Exists(FileName))
            {
                File.Delete(FileName);
            }

            using (ILogger logger = new FileLogger(FileName))
            {
                logger.LogLine(Message);
            }

            Assert.AreEqual(Message + Environment.NewLine, File.ReadAllText(FileName));
        }
Esempio n. 9
0
        public void LogShouldAppendToTheFile()
        {
            const string FileName = "LogShouldAppendToTheFile.txt";
            const string Message = "тест";

            if (File.Exists(FileName))
            {
                File.Delete(FileName);
            }

            using (ILogger logger = new FileLogger(FileName))
            {
                logger.Log(Message);
            }

            using (ILogger logger = new FileLogger(FileName))
            {
                logger.Log(Message);
            }

            Assert.AreEqual(Message + Message, File.ReadAllText(FileName));
        }
Esempio n. 10
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            var fileLogger = new FileLogger();
            var quickbloxClient = new QuickbloxClient(ApplicationKeys.ApplicationId, ApplicationKeys.AuthorizationKey, ApplicationKeys.AuthorizationSecret, ApplicationKeys.ApiBaseEndPoint, ApplicationKeys.ChatEndpoint, fileLogger);
            QmunicateLoggerHolder.LoggerInstance = fileLogger;
            var fileStorage = new FileStorage();

            ServiceLocator.Locator.Bind<INavigationService, NavigationService>(LifetimeMode.Singleton);
            ServiceLocator.Locator.Bind<IQuickbloxClient, QuickbloxClient>(quickbloxClient);
            ServiceLocator.Locator.Bind<IMessageService, MessageService>(LifetimeMode.Singleton);
            ServiceLocator.Locator.Bind<IDialogsManager, IDialogsManager>(new DialogsManager(quickbloxClient));
            ServiceLocator.Locator.Bind<IPushNotificationsManager, IPushNotificationsManager>(new PushNotificationsManager(quickbloxClient));
            ServiceLocator.Locator.Bind<IFileStorage, IFileStorage>(fileStorage);
            ServiceLocator.Locator.Bind<IImageService, IImageService>(new ImagesService(quickbloxClient, fileStorage));
            ServiceLocator.Locator.Bind<ICachingQuickbloxClient, ICachingQuickbloxClient>(new CachingQuickbloxClient(quickbloxClient));
            ServiceLocator.Locator.Bind<ICredentialsService, CredentialsService>(LifetimeMode.Singleton);

            UnhandledException += OnUnhandledException;

            this.InitializeComponent();
            this.Suspending += this.OnSuspending;
        }
Esempio n. 11
0
 public void Configure() {
   FileLogger logger = new FileLogger();
   logger.Configure();
   Assert.IsNotNull(logger.Logger);
 }
Esempio n. 12
0
 public void Log()
 {
     FileLogger logger = new FileLogger(FileUtils.CombineWinPath(pTempFolder, "LoggerTest.log"), false);
     Assert.NotNull(logger);
     logger.Log("Test", "test logger");
 }
 public ExistenceController(StoredDataFileAccessor storedData, StoredDataCache storedDataCache, FileLogger logger)
 {
     _dataCache = storedDataCache;
     _data      = storedData;
     _logger    = logger;
 }
Esempio n. 14
0
        /// <summary>
        /// Checks and install the status database.
        /// </summary>
        /// <returns></returns>
        private static bool CheckAndInstallStatusDatabase()
        {
            try {
                // If we are the hub, install our status database
                if (Settings.Instance.IsHub)
                {
                    Logging.Log(LogLevelEnum.Info, "Installing service status database");
                    int serviceId = SC_StatusDb.DatabaseInstaller.CreateDatabase(Settings.Instance.Service,
                                                                                 Settings.Instance.ServiceStatusDbSetupSql, Settings.Instance.LoggerConfiguration);
                    if (serviceId > -1)
                    {
                        Settings.Instance.ServiceId = serviceId;
                    }
                    Logging.Log(LogLevelEnum.Info, "Service status database installed");
                }
                else                 // Find it!!!
                {
                    if (string.IsNullOrEmpty(Settings.Instance.ServiceStatusDatabasePath))
                    {
                        bool adminFromHub = MessageBox.Show(string.Format("Set up hub administration of {0}?", Settings.Instance.ServiceDisplayName), String.Empty, MessageBoxButtons.YesNo) == DialogResult.Yes;

                        if (adminFromHub)
                        {
                            Logging.Log(LogLevelEnum.Info, string.Format("Setting up hub administration of {0}", Settings.Instance.ServiceDisplayName));
                            OpenFileDialog openFileDialog = new OpenFileDialog {
                                FileName = Path.GetFileName(Settings.DefaultServiceStatusDbFileName),
                                Filter   = "Service Status Database (*.db)|*.db",
                                Title    = "Locate Service Status Database"
                            };

                            if (openFileDialog.ShowDialog() == DialogResult.OK)
                            {
                                Logging.Log(LogLevelEnum.Debug, string.Format("Service status database path: {0}", openFileDialog.FileName));
                                Settings.Instance.SetServiceStatusDatabasePath(openFileDialog.FileName);
                                int serviceId = SC_StatusDb.DatabaseInstaller.InitializeService(new SC_StatusDb.Service {
                                    ServiceName               = Settings.Instance.ServiceName,
                                    ServiceDescription        = Settings.Instance.ServiceDescription,
                                    ServiceDisplayName        = Settings.Instance.ServiceDisplayName,
                                    ServiceStatusDatabasePath = Settings.Instance.ServiceStatusDatabasePath
                                },
                                                                                                Settings.Instance.LoggerConfiguration);
                                if (serviceId > -1)
                                {
                                    Settings.Instance.ServiceId = serviceId;
                                }
                            }
                            else
                            {
                                // Prompt to install service
                                if (MessageBox.Show(string.Format("Are you certain you do not want to have the hub monitor({0})?\n\nYou will not be able administer it through the hub application.", Settings.Instance.ServiceDisplayName), String.Empty, MessageBoxButtons.YesNo) == DialogResult.No)
                                {
                                    CheckAndInstallStatusDatabase();
                                }
                                else
                                {
                                    adminFromHub = false;
                                }
                            }
                            Logging.Log(LogLevelEnum.Info, string.Format("Hub administration of {0} set up", Settings.Instance.ServiceName));
                        }

                        if (!adminFromHub)
                        {
                            MessageBox.Show(string.Format("{0} will not be administered via the hub application.\n\nNote: You will be prompted to administer {0} via the hub application on the next start up of this admin application.", Settings.Instance.ServiceDisplayName), String.Empty, MessageBoxButtons.OK);
                            Logging.Log(LogLevelEnum.Info, string.Format("Hub administration of {0} bypassed", Settings.Instance.ServiceDisplayName));
                        }
                    }
                }
            }
            catch (Exception ex) {
                Logging.Log(LogLevelEnum.Fatal, "Status database install failed: " + FileLogger.GetInnerException(ex).Message);
                MessageBox.Show("Could not install status database for " + Settings.Instance.ServiceName);
            }

            return(true);
        }
Esempio n. 15
0
        protected static List <LogRecord> Parse(LogLevelEnum logLevel, FileLoggerConfiguration configuration)
        {
            FileLogger fileLogger = FileLogger.Instance(configuration);

            return(fileLogger.Parse(logLevel));
        }
Esempio n. 16
0
 public void DoAction(Game games)
 {
     FileLogger.Log("State pattern: created state action");
     Console.WriteLine("New game is created");
     games.SetState(this);
 }
Esempio n. 17
0
        public void Logger_WhenUsingFile_ThenWritesOutputToFile()
        {
            var logger = new FileLogger {LogLevel = LogLevel.Information};
            logger.Log("test", LogLevel.Information);
            logger.Close();

            Assert.IsTrue(File.Exists(logger.FullPathName));

            logger.TryDeleteFile();
        }
Esempio n. 18
0
        public override string Display()
        {
            FileLogger.Log("Composite pattern: child dsiplay");

            return(_name);
        }
Esempio n. 19
0
        public LevelMenuItem(string name)
        {
            FileLogger.Log("Composite pattern: child");

            _name = name;
        }
        static void Main(string[] args)
        {
            IFormatter form = new CustomFormatter();

            FileStream fs = new FileStream("tekst.txt", FileMode.Create);

            var logger   = new FileLogger("FileLogger.txt");
            var context  = new ShopContext();
            var inserter = new ConstantDataInserter();

            inserter.InitializeContextWithData(context);
            var repo    = new ShopRepository(context, logger);
            var service = new ShopService(repo, logger);

            var owner = new Owner()
            {
                Name = "TurTur"
            };
            var car1 = new Car()
            {
                Owner = owner,
                Model = "Niezly",
                Year  = 1234
            };
            var car2 = new Car()
            {
                Owner = owner,
                Model = "gorszy",
                Year  = 0022
            };
            var list = new List <Car>
            {
                car1,
                car2
            };
            var driver = new Driver()
            {
                Cars = new Car[] { car1, car2 }
            };

            var prod = new ProductState(new Product("213"), 12, (decimal)14.32, new Percentage(12));

            Produktieren products = new Produktieren();

            products.states.Add(prod);

            ShopContextWrapper wrapper = new ShopContextWrapper(context);

            form.Serialize(fs, wrapper);

            FileStream deserFS      = new FileStream("tekst.txt", FileMode.Open);
            var        deser        = form.Deserialize(deserFS);
            var        deserContext = ((ShopContextWrapper)deser).GetContext();
            var        client       = deserContext.Invoices.First().Client;

            foreach (var cl in deserContext.Clients)
            {
                if (client == cl)
                {
                    cl.FirstName = "fafafaf";
                    Console.WriteLine("Szach mat!!!");
                }
            }
        }
Esempio n. 21
0
        internal static void StartMiningCorePool(string configFile)
        {
            try
            {
                // Display Software Version Info
                var basePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
                Console.WriteLine($"{Assembly.GetEntryAssembly().GetName().Name} - MinerNL build v{Assembly.GetEntryAssembly().GetName().Version}");
                Console.WriteLine($"Run location: {basePath}");
                Console.WriteLine(" ");

                // log unhandled program exception errors
                AppDomain currentDomain = AppDomain.CurrentDomain;
                currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MC_UnhandledException);
                currentDomain.ProcessExit        += OnProcessExit;
                Console.CancelKeyPress           += new ConsoleCancelEventHandler(OnCancelKeyPress);

                // ValidateRuntimeEnvironment();
                // root check
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.UserName == "root")
                {
                    logger.Warn(() => "Running as root is discouraged!");
                }

                // require 64-bit Windows OS
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && RuntimeInformation.ProcessArchitecture == Architecture.X86)
                {
                    throw new PoolStartupAbortException("Miningcore requires 64-Bit Windows");
                }

                // Read config.json file
                clusterConfig = PoolConfig.GetConfigContent(configFile);

                // Initialize Logging
                FileLogger.ConfigureLogging();

                // LogRuntimeInfo();
                //-----------------------------------------------------------------------------
                logger.Info(() => $"{RuntimeInformation.FrameworkDescription.Trim()} on {RuntimeInformation.OSDescription.Trim()} [{RuntimeInformation.ProcessArchitecture}]");

                // Bootstrap();
                //-----------------------------------------------------------------------------
                ZcashNetworks.Instance.EnsureRegistered();

                // Service collection
                var builder = new ContainerBuilder();
                builder.RegisterAssemblyModules(typeof(AutofacModule).GetTypeInfo().Assembly);
                builder.RegisterInstance(clusterConfig);
                builder.RegisterInstance(pools);
                builder.RegisterInstance(gcStats);

                // AutoMapper
                var amConf = new MapperConfiguration(cfg => { cfg.AddProfile(new AutoMapperProfile()); });
                builder.Register((ctx, parms) => amConf.CreateMapper());

                PostgresInterface.ConnectDatabase(builder);
                container = builder.Build();

                // Configure Equihash
                if (clusterConfig.EquihashMaxThreads.HasValue)
                {
                    EquihashSolver.MaxThreads = clusterConfig.EquihashMaxThreads.Value;
                }

                MonitorGarbageCollection();

                // Start Miningcore Pool Services
                if (!cts.IsCancellationRequested)
                {
                    StartMiningcorePoolServices().Wait(cts.Token);
                }
            }

            catch (PoolStartupAbortException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                {
                    Console.WriteLine(ex.Message);
                }

                Console.WriteLine("\nCluster cannot start. Good Bye!");
            }

            catch (JsonException)
            {
                // ignored
            }

            catch (IOException)
            {
                // ignored
            }

            catch (AggregateException ex)
            {
                if (!(ex.InnerExceptions.First() is PoolStartupAbortException))
                {
                    Console.WriteLine(ex);
                }

                Console.WriteLine("Cluster cannot start. Good Bye!");
            }

            catch (OperationCanceledException)
            {
                // Ctrl+C
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex);

                Console.WriteLine("Cluster cannot start. Good Bye!");
            }

            finally
            {
                // Shutdown();
                Console.WriteLine("Miningcore is shuting down... bye!");
                logger?.Info(() => "Miningcore is shuting down... bye!");

                foreach (var poolToStop in pools.Values)
                {
                    Console.WriteLine($"Stopping pool {poolToStop}");
                    poolToStop.Stop();
                }

                shareRelay?.Stop();
                shareReceiver?.Stop();
                shareRecorder?.Stop();
                statsRecorder?.Stop();
                Process.GetCurrentProcess().Kill();
            }
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            string theGuess = rng.Next(0, 9999).ToString();

            if (theGuess.Length < 4)
            {
                for (int x = 0; x < 5 - theGuess.Length; x++)
                {
                    theGuess = "0" + theGuess;
                }
            }

            FileLogger masterLogger = new FileLogger(Properties.Settings.Default.LoggingDir + "_" + System.DateTime.Now.ToString("yyyy-MM-dd_hhmmss") + ".txt");

            int numTries = 0;

            int.TryParse(Properties.Settings.Default.NumberOfTries, out numTries);
            masterLogger.Log(LogSeverity.Info, "Mastermind - New Game Begin | Answer: " + theGuess + " | Number of tries: " + numTries);

            string tries = (numTries == 1) ? " try" : " tries";

            Console.WriteLine("Welcome to Mastermind! You have " + numTries + tries + " to guess a randomly determined four digit number!\n\nFor each guess submitted, the system will return a + for each character in your guess that matches both the number and position, and a - for a matching number, but not a matching position.\nGood luck!");

            do
            {
                Console.Write(numTries + " remaining..." + "Please enter your next guess:" + "\n");
                string userGuess = Console.ReadLine();

                int userCheck;
                while (userGuess.Length != 4 || !int.TryParse(userGuess, out userCheck))
                {
                    Console.WriteLine("Your guess must be a 4 digit number...\nPlease enter another guess...");
                    userGuess = Console.ReadLine();
                }

                masterLogger.Log(LogSeverity.Info, "User guess: " + userGuess + " | Answer: " + theGuess);
                userGuess = processGuess(userGuess, theGuess);
                Console.WriteLine("Guess result: " + userGuess);
                masterLogger.Log(LogSeverity.Info, "Guess Result: " + userGuess);

                if (userGuess == "++++")
                {
                    Console.WriteLine("\nYou solved it!\nEnter y to play again or enter to exit...");
                    if (Console.ReadLine() == "y")
                    {
                        Main(args);
                    }
                    else
                    {
                        numTries -= numTries;
                        return;
                    }
                }

                else if (numTries == 1)
                {
                    Console.WriteLine("You lost :( - the answer was " + theGuess + "\r\nPress y to play again or any other key to exit...");
                    if (Console.ReadLine() == "y")
                    {
                        Main(args);
                    }
                    else
                    {
                        return;
                    }
                }

                numTries--;
            } while (numTries > 0);
        }
Esempio n. 23
0
    // 1 回実行
    public void ExecOnce()
    {
        this.DnsClient = null !;

        Config config = new Config(ConfigFileName, this.LastOkHostList);

        if (config.DnsServer._IsEmpty())
        {
            this.DnsClient = DnsResolver.CreateDnsResolverIfSupported(
                new DnsResolverSettings(null, DnsResolverFlags.DisableCache | DnsResolverFlags.UdpOnly | DnsResolverFlags.UseSystemDnsClientSettings, 3000, 2));
        }
        else
        {
            this.DnsClient = DnsResolver.CreateDnsResolverIfSupported(
                new DnsResolverSettings(null, DnsResolverFlags.DisableCache | DnsResolverFlags.UdpOnly, 3000, 2,
                                        dnsServersList: config.DnsServer._Split(StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries, ",", " ").Select(x => new IPEndPoint(x._ToIPAddress() !, Consts.Ports.Dns))));
        }

        try
        {
            PingerTask[] tasks = ExecTasksMulti(config);

            string prefix = config.SubjectPrefix + " ";
            if (config.SubjectPrefix._IsEmpty())
            {
                prefix = "";
            }

            DateTime now = DateTime.Now;
            if (lastDate.Day != now.Day)
            {
                if (lastDate.Ticks != 0)
                {
                    if (config.SendAliveMessage)
                    {
                        string text = "報告日時: " + DateTime.Now.ToString() + "\n\n";
                        Mail(config, config.SmtpFromAlive, prefix + "生きています", text);
                    }
                }

                lastDate = now;
            }

            res.Merge(tasks);

            byte[] hash = res.GetHash();

            string str = res.GetString();

            // ログ保存
            if (config.SaveLog)
            {
                try
                {
                    string saveStr = Str.NormalizeCrlf(str).Replace(Env.NewLine, "\\n");

                    if (logger == null)
                    {
                        logger       = new FileLogger(LogDirName);
                        logger.Flush = true;
                    }

                    logger.Write(saveStr);
                }
                catch
                {
                }
            }

            if (Util.MemEquals(lastHash, hash) == false)
            {
                lastHash = hash;

                string okngStr = $"NG:{res.NumError} OK:{res.NumOk}";

                var progamInfo = Env.GenerateMyProgramAndEnvironmentReport()._GetResult();

                // メール送信
                string mailStr = "【" + okngStr + "】\r\n" + "報告日時: " + DateTime.Now._ToDtStr() + "\r\n\r\n" + str + "\r\n\r\n" +
                                 $"Pinger version: {Env.BuildTimeStamp._ToDtStr()}\r\n" +
                                 $"Pinger machine: {Env.DnsFqdnHostName}\r\n\r\n" +
                                 $"Program Info:\r\n" +
                                 progamInfo._ObjectToJson() + "\r\n" +
                                 config.Footer._NonNull()._DecodeCEscape() + "\r\n";

                mailStr = Str.NormalizeCrlf(mailStr);

                Mail(config, config.SmtpFrom, prefix + okngStr, mailStr);

                //Console.WriteLine("----------");
                //Console.WriteLine(mailStr);

                Console.WriteLine("Mail Sent.");
            }
        }
        finally
        {
            this.DnsClient._DisposeSafe();
            this.DnsClient = null !;
        }
    }
Esempio n. 24
0
        private void JeepServiceCheck()
        {
            try
            {
                ServicesHelper.Exists(Settings.Default.ServiceName, Settings.Default.JeepServicePath, LiveUpdateClient);
            }
            catch (Exception ex)
            {
                throw new FileNotFoundException("Il servizio non esiste!", ex);
            }

            // Servizio presente
            // Versione servizio
            var jeepServiceVersion = ServicesHelper.ServiceVersion(Settings.Default.ServiceName,
                                                                   Settings.Default.JeepServicePath,
                                                                   LiveUpdateClient);

            string serviceExist;
            string serviceStatus;

            if (ServicesHelper.Installed(Settings.Default.ServiceName, Settings.Default.JeepServicePath,
                                         LiveUpdateClient))
            {
                // Il servizio è installato
                jeepServiceInstallToolStripMenuItem.Enabled   = false;
                jeepServiceUninstallToolStripMenuItem.Enabled = true;
                serviceExist = string.Format("Servizio [{0} v.{1}] installato.", Settings.Default.ServiceName,
                                             jeepServiceVersion);
                imgInstallationOFF.Visible = false;
                imgInstallationON.Visible  = true;

                var serviceControllerStatus = ServicesHelper.ServiceStatus(Settings.Default.ServiceName,
                                                                           Settings.Default.JeepServicePath,
                                                                           LiveUpdateClient);
                switch (serviceControllerStatus)
                {
                case ServiceControllerStatus.Running:
                    jeepServiceStartToolStripMenuItem.Enabled        = false;
                    jeepServiceStopToolStripMenuItem.Enabled         = true;
                    jeepServiceRestartToolStripMenuItem.Enabled      = true;
                    jeepServiceStartConsoleToolStripMenuItem.Enabled = false;
                    serviceStatus             = "The Service is Running.";
                    imgStatusPlay.Visible     = true;
                    imgStatusPause.Visible    = false;
                    imgStatusQuestion.Visible = false;
                    break;

                case ServiceControllerStatus.Stopped:
                    jeepServiceStartToolStripMenuItem.Enabled        = true;
                    jeepServiceStartConsoleToolStripMenuItem.Enabled = true;
                    jeepServiceStopToolStripMenuItem.Enabled         = false;
                    jeepServiceRestartToolStripMenuItem.Enabled      = false;
                    serviceStatus             = "The Service is Stopped.";
                    imgStatusPlay.Visible     = false;
                    imgStatusPause.Visible    = true;
                    imgStatusQuestion.Visible = false;
                    break;

                default:
                    jeepServiceStartToolStripMenuItem.Enabled = false;
                    serviceStatus = string.Format("The Service is {0}.", serviceControllerStatus);
                    jeepServiceStopToolStripMenuItem.Enabled    = false;
                    jeepServiceRestartToolStripMenuItem.Enabled = false;
                    imgStatusPlay.Visible     = false;
                    imgStatusPause.Visible    = false;
                    imgStatusQuestion.Visible = true;
                    break;
                }
            }
            else
            {
                // Servizio non installato
                jeepServiceInstallToolStripMenuItem.Enabled   = true;
                jeepServiceUninstallToolStripMenuItem.Enabled = false;
                editToolStripMenuItem.Enabled = true;
                serviceExist = string.Format("Servizio [{0} v.{1}] NON installato.", Settings.Default.ServiceName,
                                             jeepServiceVersion);
                serviceStatus = "";
                imgInstallationOFF.Visible = true;
                imgInstallationON.Visible  = false;

                jeepServiceStartToolStripMenuItem.Enabled        = false;
                jeepServiceStartConsoleToolStripMenuItem.Enabled = File.Exists(Settings.Default.JeepServicePath);
                jeepServiceStopToolStripMenuItem.Enabled         = false;
                jeepServiceRestartToolStripMenuItem.Enabled      = false;

                imgStatusPlay.Visible     = false;
                imgStatusPause.Visible    = false;
                imgStatusQuestion.Visible = false;
            }
            var jeepServiceStatus = string.Format("{0} {1}", serviceExist, serviceStatus);

            jeepServiceStatusLabel.Text = jeepServiceStatus;
            FileLogger.Info(Logger, jeepServiceStatus);
        }
Esempio n. 25
0
 public DoubleWorker(FileLogger logger)
 {
     this.logger = logger;
 }
Esempio n. 26
0
        public override string GetName()
        {
            FileLogger.Log("Composite pattern: get name");

            return(_name);
        }
Esempio n. 27
0
 /// <summary>
 /// Initializes the singleton process's logger instance.
 /// </summary>
 static FileLogger() {
     current_process_logger_ = new FileLogger();
     current_process_logger_.Configure();
 }
Esempio n. 28
0
        public static bool InstallService()
        {
            var serviceDescription = "\"Service initially installed from user " + Environment.UserName + ". This service watches all source dirs for CloudTransferTask to execute the corresponding actions\"";
            var binaryPath         = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            var returnVal          = false;

            try {
                System.Diagnostics.Process          process   = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                switch (os)
                {
                case "win":
                    startInfo.FileName = "cmd.exe";
                    break;

                case "lin":
                    //if (Directory.Exists("/etc/systemd/system")) {
                    if (!Directory.Exists(Json.serviceConfPathLnx))
                    {
                        FileLogger.Notice("Cannot find directory \"" + Json.serviceConfPathLnx + "\"! Creating it...");

                        try {
                            Directory.CreateDirectory(Json.serviceConfPathLnx);
                        } catch {
                            FileLogger.Error("Cannot create the directory \"" + Json.serviceConfPathLnx + "\"!");
                            Environment.Exit(1);
                        }
                    }

                    File.WriteAllText(Json.serviceInstallFullPathLnx,
                                      "[Unit]" + Environment.NewLine + "Description=" + serviceDescription + Environment.NewLine + Environment.NewLine +
                                      "[Service]" + Environment.NewLine + "Type=notify" + Environment.NewLine + "ExecStart=" + binaryPath + Environment.NewLine + Environment.NewLine +
                                      "[Install]" + Environment.NewLine + "WantedBy=default.target" + Environment.NewLine
                                      );

                    startInfo.FileName = "/bin/bash";
                    break;
                }

                startInfo.RedirectStandardInput = true;
                startInfo.UseShellExecute       = false;

                process.StartInfo = startInfo;
                process.Start();

                using (StreamWriter sw = process.StandardInput) {
                    if (sw.BaseStream.CanWrite)
                    {
                        switch (os)
                        {
                        case "win":
                            var serviceName = "CloudTransferTask";
                            sw.WriteLine("sc.exe create " + serviceName + " BinPath= \"" + binaryPath + "\" type= own start= auto ");
                            sw.WriteLine("sc.exe description " + serviceName + " " + serviceDescription);
                            break;

                        case "lin":
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                Console.WriteLine("ERROR: " + e.ToString());
            }

            return(returnVal);
        }
Esempio n. 29
0
        protected static void Log(LogLevelEnum logLevel, string message, FileLoggerConfiguration configuration)
        {
            FileLogger fileLogger = FileLogger.Instance(configuration);

            fileLogger.WriteLog(logLevel, message);
        }
Esempio n. 30
0
 public Persona(StoredDataFileAccessor storedData, StoredDataCache storedDataCache, FileLogger logger) : base(storedData, storedDataCache, logger)
 {
     AkashicRecord = new List <IAkashicEntry>();
 }
Esempio n. 31
0
        protected static List <LogRecord> Parse(FileLoggerConfiguration configuration)
        {
            FileLogger fileLogger = FileLogger.Instance(configuration);

            return(fileLogger.Parse());
        }
Esempio n. 32
0
        public override void SetAccessors(StoredDataFileAccessor storedData, StoredDataCache storedDataCache, FileLogger logger)
        {
            foreach (var entry in AkashicRecord)
            {
                entry.SetAccessors(storedDataCache);
            }

            base.SetAccessors(storedData, storedDataCache, logger);
        }
Esempio n. 33
0
        /// <summary>
        /// Extracts the resource.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        private static void ExtractResource(string resourceName)
        {
            if (!File.Exists(resourceName))
            {
                try {
                    Logging.Log(LogLevelEnum.Debug, "Extracting resource: " + resourceName);

                    Assembly assembly = Assembly.GetExecutingAssembly();
                    using (Stream strm = assembly.GetManifestResourceStream(ProgramStarter.DependencyPrefix + (!ProgramStarter.DependencyPrefix.LastIndexOf(".").Equals(ProgramStarter.DependencyPrefix.Length - 1) ? "." : string.Empty) + resourceName)) {
                        byte[] file = new byte[strm.Length];
                        strm.Read(file, 0, (int)file.Length);
                        strm.Close();

                        FileInfo fi = new FileInfo(resourceName);
                        using (FileStream fs = fi.Create()) {
                            fs.Write(file, 0, (int)file.Length);
                            fs.Close();
                        }
                    }

                    Logging.Log(LogLevelEnum.Debug, "Extracted resource: " + resourceName);
                }
                catch (Exception ex) {
                    Logging.Log(LogLevelEnum.Fatal, string.Format("Error extracting resource: {0}: {1})", resourceName, FileLogger.GetInnerException(ex).Message));
                    MessageBox.Show("Error extracting resource: " + resourceName);
                }
            }
        }
Esempio n. 34
0
        static void Main(string[] args)
        {
            var productRepository  = new ProductRepository();
            var ruleRepository     = new RuleRepository(productRepository);
            var discountRepository = new DiscountRepository(ruleRepository, productRepository);

            var compiler          = new DiscountCompiler();
            var compiledDiscounts = compiler.Compile(discountRepository.GetFromSource());

            var discountManager = new DiscountManager(compiledDiscounts);

            var basket = new Basket(discountManager);

            var products = productRepository.GetFromSource().ToArray();
            var butter   = products[0];
            var milk     = products[1];
            var bread    = products[2];

            basket.AddProducts(new BasketItem(1, butter), new BasketItem(1, milk), new BasketItem(1, bread));

            var logger = new FileLogger();

            Console.WriteLine("Case 1: ");
            var summary1 = basket.CalculateSum();

            Console.WriteLine(summary1);
            logger.Log(summary1);

            basket.Clear();
            basket.AddProducts(new BasketItem(2, butter), new BasketItem(2, bread));

            Console.WriteLine("Case 2: ");
            var summary2 = basket.CalculateSum();

            Console.WriteLine(summary2);
            logger.Log(summary2);

            basket.Clear();
            basket.AddProducts(new BasketItem(4, milk));

            Console.WriteLine("Case 3: ");
            var summary3 = basket.CalculateSum();

            Console.WriteLine(summary3);
            logger.Log(summary3);

            basket.Clear();
            basket.AddProducts(new BasketItem(2, butter), new BasketItem(1, bread), new BasketItem(8, milk));

            Console.WriteLine("Case 4:");
            var summary4 = basket.CalculateSum();

            Console.WriteLine(summary4);
            logger.Log(summary4);

            basket.Clear();
            basket.AddProducts(new BasketItem(2, butter), new BasketItem(1, bread), new BasketItem(9, milk));

            Console.WriteLine("Case 5:");
            var summary5 = basket.CalculateSum();

            Console.WriteLine(summary5);
            logger.Log(summary5);
        }
Esempio n. 35
0
 public LogManager()
 {
     _file = new FileLogger();
     _db   = new DBLogger();
 }
Esempio n. 36
0
        public void SetUp()
        {
            // The faked IOutpus must return a screen size to ConsoleViews ctor.
            _output = Substitute.For <IOutput>();
            _output.When(x => x.GetLargetsScreenSize(out int w, out int h)).Do(x =>
            {
                x[0] = 80;
                x[1] = 40;
            });

            _collisionDetector = new CollisionDetector();
            _trackStorage      = new TrackStorage();
            _airSpace          = new AirSpace();
            _log         = new FileLogger(_logPath);
            _consoleView = new ConsoleView(_output);
            _atm         = new AirTrafficController(_collisionDetector, _trackStorage, _airSpace, _consoleView, _log);

            // Create Tos with fake TransponderReceiver, attach ATM to subscribe on Tos.
            // _tos.Notify(_tos) will call _atm.Update(). Notify will start the system.
            _tos = new Tos(Substitute.For <ITransponderReceiver>());
            _tos.Attach(_atm);

            // Init some standard List with valid tracks, used to give to Tos before Notify() call.
            _tracks1 = new List <ITrack>
            {
                new Track
                {
                    Tag       = "AAA111",
                    PositionX = 15000,
                    PositionY = 30000,
                    Altitude  = 850,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
                new Track
                {
                    Tag       = "BBB222",
                    PositionX = 15000,
                    PositionY = 30000,
                    Altitude  = 850,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
                new Track
                {
                    Tag       = "CCC333",
                    PositionX = 15000,
                    PositionY = 30000,
                    Altitude  = 850,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
                new Track
                {
                    Tag       = "DDD444",
                    PositionX = 15000,
                    PositionY = 30000,
                    Altitude  = 850,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
                new Track
                {
                    Tag       = "EEE555",
                    PositionX = 15000,
                    PositionY = 30000,
                    Altitude  = 850,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
            };
            _tracks2 = new List <ITrack>
            {
                new Track
                {
                    Tag       = "AAA111",
                    PositionX = 15000,
                    PositionY = 80000,
                    Altitude  = 850,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
                new Track
                {
                    Tag       = "BBB222",
                    PositionX = 25000,
                    PositionY = 36000,
                    Altitude  = 850,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
                new Track
                {
                    Tag       = "CCC333",
                    PositionX = 10000,
                    PositionY = 27000,
                    Altitude  = 1900,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
                new Track
                {
                    Tag       = "DDD444",
                    PositionX = 45000,
                    PositionY = 66000,
                    Altitude  = 833,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
                new Track
                {
                    Tag       = "EEE555",
                    PositionX = 15000,
                    PositionY = 28000,
                    Altitude  = 2500,
                    Course    = 0,
                    Timestamp = DateTime.Now,
                    Velocity  = 0
                },
            };
        }
Esempio n. 37
0
 public void LoggerWithoutConfigure() {
   FileLogger logger = new FileLogger();
   Assert.IsNull(logger.Logger);
 }
Esempio n. 38
0
 public void RevertDiagonalLOS()
 {
     using (FileLogger logger = new FileLogger())
     {
         (int, int)[] coord     = new(int, int)[4];
Esempio n. 39
0
        public MainWindow()
        {
            InitializeComponent();

            NextCommand.InputGestures.Add(new KeyGesture(Key.N, ModifierKeys.Alt));
            PreviousCommand.InputGestures.Add(new KeyGesture(Key.P, ModifierKeys.Alt));
            PlayPauseCommand.InputGestures.Add(new KeyGesture(Key.Space, ModifierKeys.Alt));

            try
            {
                String appData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppName);
                var appDir = new DirectoryInfo(appData);
                
                if (!appDir.Exists)
                    Directory.CreateDirectory(appData);
                
                String logFile = Path.Combine(appData, "ultrasonic.log");

                FileLogger = new FileLogger(logFile, LoggingLevel.Verbose);
                FileLogger.Log("UltraSonic Started", LoggingLevel.Basic);
                
                WindowStartupLocation = WindowStartupLocation.Manual;

                FileLogger.Log($"WindowLeft: {Settings.Default.WindowLeft}", LoggingLevel.Verbose);
                Left = Settings.Default.WindowLeft;

                FileLogger.Log($"WindowTop: {Settings.Default.WindowTop}", LoggingLevel.Verbose);
                Top = Settings.Default.WindowTop;
                
                FileLogger.Log($"WindowHeight: {Settings.Default.WindowHeight}", LoggingLevel.Verbose);
                Height = Settings.Default.WindowHeight;

                FileLogger.Log($"WindowWidth: {Settings.Default.WindowWidth}", LoggingLevel.Verbose);
                Width = Settings.Default.WindowWidth;

                FileLogger.Log($"WindowMaximized: {Settings.Default.WindowMaximized}", LoggingLevel.Verbose);
                
                if (Settings.Default.WindowMaximized)
                    WindowState = WindowState.Maximized;

                PopulateSettings();
                MusicPlayStatusLabel.Content = "Stopped";
                ArtistTreeView.DataContext = ArtistItems;
                //DataGridDragAndDrop<TrackItem> playlistTrackDragAndDrop = DataGridDragAndDrop<TrackItem>.Create(_playlistTrackItems, PlaylistTrackGrid, this, PlaylistDragPopup);

                //PlaylistTrackGrid.BeginningEdit += playlistTrackDragAndDrop.DataGridOnBeginEdit;
                //PlaylistTrackGrid.CellEditEnding += playlistTrackDragAndDrop.DataGridOnEndEdit;
                //PlaylistTrackGrid.PreviewMouseLeftButtonDown += playlistTrackDragAndDrop.DataGridOnMouseLeftButtonDown;
                //MainGrid.MouseLeftButtonUp += playlistTrackDragAndDrop.DataGridOnMouseLeftButtonUp;
                //MainGrid.MouseMove += playlistTrackDragAndDrop.DataGridOnMouseMove;

                if (StreamProxy == null)
                {
                    FileLogger.Log("Creating StreamProxy", LoggingLevel.Information);

                    StreamProxy = StreamProxy.Instance;
                    StreamProxy.Start();

                    FileLogger.Log($"StreamProxy Port: {StreamProxy.GetPort()}", LoggingLevel.Information);
                }

                if (!string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password) && !string.IsNullOrWhiteSpace(ServerUrl))
                {
                    InitSubsonicApi();

                    SubsonicClient?.GetLicenseAsync(GetCancellationToken("MainWindow")).ContinueWith(CheckLicense);
                }
                else
                {
                    SettingsTab.IsSelected = true;
                    ServerSettingsExpander.IsExpanded = true;
                    SettingsServerAddressTextBox.Focus();
                }

                _mainTimer.Interval = TimeSpan.FromMilliseconds(500);
                _mainTimer.Tick += (o, s) => Ticktock();
                _mainTimer.Start();

                if (_nowPlayingInterval > 0)
                    UpdateNowPlaying();

                _nowPlayingTimer.Interval = TimeSpan.FromSeconds(_nowPlayingInterval);
                _nowPlayingTimer.Tick += (o, s) => UpdateNowPlaying();
                _nowPlayingTimer.Start();

                ConfigureChat(_chatMessagesInterval);

                MediaPlayer.MediaEnded += (o, args) => PlayNextTrack();
                MediaPlayer.Volume = Settings.Default.Volume;
                MediaPlayer.IsMuted = Settings.Default.VolumeMuted;
                VolumeSlider.Value = MediaPlayer.Volume*10;

                AlbumDataGrid.ItemsSource = _albumItems;
                NowPlayingDataGrid.ItemsSource = _nowPlayingItems;
                ChatListView.ItemsSource = _chatMessages;
                PlaylistTrackGrid.ItemsSource = _playlistTrackItems;
                PlaybackTrackGrid.ItemsSource = _playbackTrackItems;
                PlaylistsDataGrid.ItemsSource = _playlistItems;
                TrackDataGrid.ItemsSource = _trackItems;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Exception:\n\n{ex.Message}\n{ex.StackTrace}", AppName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Esempio n. 40
0
   private ITextLogger CreateLog()
   {
      MappedLogger logger = new MappedLogger();

      ITextLogger fileLogger = new FileLogger(OutlinerPaths.LogFile);
      logger.AddLogger(fileLogger);

      if (Configuration == null || Configuration.Core == null || Configuration.Core.WriteLogToMxsListener)
      {
         ITextLogger mxsLogger = new MaxscriptListenerLogger("Outliner");
         logger.AddLogger(mxsLogger);
      }

      logger.Info("Start logging");
      logger.HorizontalRule('-');

      return logger;
   }
Esempio n. 41
0
        private void LiveUpdateServiceCheck()
        {
            var liveUpdateServiceVersion = ServicesHelper.ServiceVersion(Settings.Default.LiveUpdateServiceName,
                                                                         Settings.Default.LiveUpdatePath,
                                                                         LiveUpdateClient);
            string serviceExist;
            string serviceStatus;

            // Servizio non installato
            if (!ServicesHelper.Exists(Settings.Default.LiveUpdateServiceName, Settings.Default.LiveUpdatePath, LiveUpdateClient))
            {
                // Servizio non installato
                liveUpdateServiceInstallStripMenuItem.Enabled   = true;
                liveUpdateServiceUninstallStripMenuItem.Enabled = false;
                editToolStripMenuItem.Enabled = true;
                serviceExist = string.Format("Service [{0} v.{1}] NOT installed.", Settings.Default.LiveUpdateServiceName,
                                             liveUpdateServiceVersion);
                serviceStatus = "";

                liveUpdateServiceStartStripMenuItem.Enabled        = false;
                liveUpdateServiceStartConsoleStripMenuItem.Enabled = File.Exists(Settings.Default.JeepServicePath);
                liveUpdateStopStripMenuItem.Enabled = false;
                liveUpdateServiceRestartToolStripMenuItem.Enabled = false;
            }
            else
            {
                // Servizio installato
                liveUpdateServiceInstallStripMenuItem.Enabled   = false;
                liveUpdateServiceUninstallStripMenuItem.Enabled = true;
                serviceExist = string.Format("Service [{0} v.{1}] installed.", Settings.Default.LiveUpdateServiceName, liveUpdateServiceVersion);
                imgInstallationOFF.Visible = false;
                imgInstallationON.Visible  = true;

                var serviceControllerStatus = ServicesHelper.ServiceStatus(Settings.Default.LiveUpdateServiceName,
                                                                           Settings.Default.LiveUpdatePath,
                                                                           LiveUpdateClient);
                switch (serviceControllerStatus)
                {
                case ServiceControllerStatus.Running:
                    liveUpdateServiceStartStripMenuItem.Enabled        = false;
                    liveUpdateStopStripMenuItem.Enabled                = true;
                    liveUpdateServiceStartConsoleStripMenuItem.Enabled = false;
                    liveUpdateServiceRestartToolStripMenuItem.Enabled  = false;
                    serviceStatus = string.Format("The Service is running.");
                    break;

                case ServiceControllerStatus.Stopped:
                    liveUpdateServiceStartStripMenuItem.Enabled        = true;
                    liveUpdateServiceStartConsoleStripMenuItem.Enabled = true;
                    liveUpdateStopStripMenuItem.Enabled = false;
                    liveUpdateServiceRestartToolStripMenuItem.Enabled = true;
                    serviceStatus = string.Format("The Service is stopped");
                    break;

                default:
                    liveUpdateServiceStartStripMenuItem.Enabled       = false;
                    liveUpdateStopStripMenuItem.Enabled               = false;
                    liveUpdateServiceRestartToolStripMenuItem.Enabled = false;
                    serviceStatus = string.Format("The Service is {0}.", serviceControllerStatus);
                    break;
                }
            }
            var liveUpdateServiceStatus = string.Format("{0} {1}", serviceExist, serviceStatus);

            liveUpdateStatusLabel.Text = liveUpdateServiceStatus;
            FileLogger.Info(Logger, liveUpdateServiceStatus);
        }
Esempio n. 42
0
        public SQLiteDatabase()
        {
            try
            {
                _maintenanceScheduler = new ActionBlock <bool>(async _ => await PerformDatabaseMaintenanceAsync(), new ExecutionDataflowBlockOptions {
                    BoundedCapacity = 2
                });
                _messageQueue = new AsynchronousMessageQueue(this, new[] { ContentDirectoryMessaging.CHANNEL });
                _messageQueue.MessageReceived += OnMessageReceived;
                _messageQueue.Start();

                _settings = ServiceRegistration.Get <ISettingsManager>().Load <SQLiteSettings>();
                _settings.LogSettings();

                LogVersionInformation();

                if (_settings.EnableTraceLogging)
                {
                    _sqliteDebugLogger = FileLogger.CreateFileLogger(ServiceRegistration.Get <IPathManager>().GetPath(@"<LOG>\SQLiteDebug.log"), LogLevel.Debug, false, true);
                    SQLiteLog.Initialize();
                    SQLiteLog.RemoveDefaultHandler();
                    SQLiteLog.Log += MPSQLiteLogEventHandler;
                }

                // We use our own collation sequence which is registered here to be able
                // to sort items taking into account culture specifics
                SQLiteFunction.RegisterFunction(typeof(SQLiteCultureSensitiveCollation));

                var    pathManager   = ServiceRegistration.Get <IPathManager>();
                string dataDirectory = pathManager.GetPath("<DATABASE>");
                string databaseFile  = Path.Combine(dataDirectory, _settings.DatabaseFileName);

                // We use an URI instead of a simple database path and filename. The reason is that
                // only this way we can switch on the shared cache mode of SQLite in System.Data.SQLite
                // However, when using an URI, SQLite ignores the page size value specified in the connection string.
                // Therefore we have to use a workaround below to create a database file with the specified page size.
                string databaseFileForUri = databaseFile.Replace('\\', '/');
                string databaseUri        = System.Web.HttpUtility.UrlPathEncode("file:///" + databaseFileForUri + "?cache=shared");

                _connectionPool = new ConnectionPool <SQLiteConnection>(CreateOpenAndInitializeConnection);

                // We are using the ConnectionStringBuilder to generate the connection string
                // This ensures code compatibility in case of changes to the SQLite connection string parameters
                // More information on the parameters can be found here: http://www.sqlite.org/pragma.html
                var connBuilder = new SQLiteConnectionStringBuilder
                {
                    // Name of the database file including path as URI
                    FullUri = databaseUri,

                    // Use SQLite database version 3.x
                    Version = 3,

                    // Store GUIDs as binaries, not as string
                    // Saves some space in the database and is said to make search queries on GUIDs faster
                    BinaryGUID = true,

                    DefaultTimeout = _settings.LockTimeout,
                    CacheSize      = _settings.CacheSizeInPages,

                    // Use the Write Ahead Log mode
                    // In this journal mode write locks do not block reads
                    // Needed to prevent sluggish behaviour of MP2 client when trying to read from the database (through MP2 server)
                    // while MP2 server writes to the database (such as when importing shares)
                    // More information can be found here: http://www.sqlite.org/wal.html
                    JournalMode = SQLiteJournalModeEnum.Wal,

                    // Do not use the inbuilt connection pooling of System.Data.SQLite
                    // We use our own connection pool which is faster.
                    Pooling = false,

                    // Sychronization Mode "Normal" enables parallel database access while at the same time preventing database
                    // corruption and is therefore a good compromise between "Off" (more performance) and "On"
                    // More information can be found here: http://www.sqlite.org/pragma.html#pragma_synchronous
                    SyncMode = SynchronizationModes.Normal,

                    // MP2's database backend uses foreign key constraints to ensure referential integrity.
                    // SQLite supports this, but it has to be enabled for each database connection by a PRAGMA command
                    // For details see http://www.sqlite.org/foreignkeys.html
                    ForeignKeys = true
                };

                if (_settings.EnableTraceLogging)
                {
                    connBuilder.Flags = SQLiteConnectionFlags.LogAll;
                }

                _connectionString = connBuilder.ToString();
                ServiceRegistration.Get <ILogger>().Info("SQLiteDatabase: Connection String used: '{0}'", _connectionString);

                if (!File.Exists(databaseFile))
                {
                    ServiceRegistration.Get <ILogger>().Info("SQLiteDatabase: Database file does not exists. Creating database file");

                    if (!Directory.Exists(dataDirectory))
                    {
                        Directory.CreateDirectory(dataDirectory);
                    }

                    // Since we use an URI in the standard connection string and system.data.sqlite therefore
                    // ignores the page size value in the connection string, this is a workaroung to make sure
                    // the page size value as specified in the settings is used. When the database file does
                    // not yet exists, we create a special connection string where we additionally set the
                    // datasource (which overrides the URI) and the page size. We then create a connection with
                    // that special connection string, open it and close it. That way the database file is created
                    // with the desired page size. The page size is permanently stored in the database file so that
                    // it is used when as of now we use connections with URI.
                    connBuilder.DataSource = databaseFile;
                    connBuilder.PageSize   = _settings.PageSize;
                    using (var connection = new SQLiteConnection(connBuilder.ToString()))
                    {
                        connection.Open();
                        connection.Close();
                    }
                }

                // The following is necessary to avoid the creation of of a shared memory index file
                // ("-shm"-file) when using exclusive locking mode. When WAL-mode is used, it is possible
                // to switch between normal and exclusive locking mode at any time. However, the creation
                // of a "-shm"-file can only be avoided, when exclusive locking mode is set BEFORE entering
                // WAL-mode. If this is the case, it is not possible to leave exclusive locking mode
                // without leaving WAL-mode before, because the "-shm"-file was not created.
                // The regular connections in our connection pool use WAL-mode. Therefore we have
                // to open one connection without WAL-Mode (here with JournalMode=OFF) and set locking_mode=
                // EXCLUSIVE before we create the first regular connection that goes into the pool.
                // To use exclusive locking mode, it is additionally necessary to set locking_mode=EXCLUSIVE
                // for every connection in the pool via the InitializationCommand. If "PRAGMA locking_mode=
                // EXCLUSIVE" is not in the InitializationCommand, normal locking mode is used
                // although we issue "PRAGMA locking_mode=EXCLUSIVE" at this point.
                // For details see here: http://sqlite.org/wal.html#noshm
                // Avoiding the creation of an "-shm"-file materially improves the database performance.
                if (_settings.UseExclusiveMode)
                {
                    connBuilder.JournalMode = SQLiteJournalModeEnum.Off;
                    using (var connection = new SQLiteConnection(connBuilder.ToString()))
                    {
                        connection.Open();
                        using (var command = new SQLiteCommand(SQLiteSettings.EXCLUSIVE_MODE_COMMAND, connection))
                            command.ExecuteNonQuery();
                        connection.Close();
                    }
                }

                // Just test one "regular" connection, which is the first connection in the pool
                using (var transaction = BeginTransaction())
                    transaction.Rollback();
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Critical("SQLiteDatabase: Error establishing database connection", e);
                throw;
            }
        }
Esempio n. 43
0
        public void Logger_WhenUsingFile_ThenRollingFilesShouldIncrement()
        {
            // create first rolling log file
            var logger1 = new FileLogger {LogLevel = LogLevel.Verbose};
            logger1.Log("test");
            Assert.IsTrue(File.Exists(logger1.FullPathName));
            logger1.Close();

            // create a new file logger (effectively a new logging session)
            // and create the second rolling log file
            var logger2 = new FileLogger {LogLevel = LogLevel.Verbose};
            logger2.Log("test");
            Assert.IsTrue(File.Exists(logger2.FullPathName));
            logger2.Close();

            // get the number values from each file
            // used the default file name template, so the format is
            // "logfile###.log"
            var logNumber1 = int.Parse(logger1.CurrentLogFileName.Substring(7, 3));
            var logNumber2 = int.Parse(logger2.CurrentLogFileName.Substring(7, 3));

            Assert.IsTrue(logNumber2 == logNumber1 + 1);

            // clean up
            logger1.TryDeleteFile();
            logger2.TryDeleteFile();
        }
Esempio n. 44
0
 protected SchedulerBase(FileLogger logger)
 {
     this._logger = logger;
 }
Esempio n. 45
0
    public NetworkListener()
    {
        initialMessageContainer = new List<Message>();

        netLogger = new FileLogger( SPW.path + "netlog_" + FileLogger.CurrentTimestamp + ".txt", false );
    }
        public static void CopyPlatformAndServerConfFiles(string _osInstallationFolder, string _iisApplicationHostPath, string _iisWebConfigPath, string _machineConfigPath, string _osPlatFilesDest)
        {
            string confFilePath = "";

            // List of OS services and components
            IDictionary <string, string> osServiceNames = new Dictionary <string, string> {
                { "ConfigurationTool", "Configuration Tool" },
                { "LogServer", "Log Service" },
                { "CompilerService", "Deployment Controller Service" },
                { "DeployService", "Deployment Service" },
                { "Scheduler", "Scheduler Service" },
                { "SMSConnector", "SMS Service" }
            };

            if (!Program.osPlatformVersion.StartsWith("10."))
            {
                osServiceNames.Add(@"Server.API\nlog", "Server API");
                osServiceNames.Add(@"Server.Identity\nlog", "Server Identity");
            }

            // Initialize dictionary with all the files that we need to get and can be accessed directly
            IDictionary <string, string> files = new Dictionary <string, string> {
                { "ServerHSConf", Path.Combine(_osInstallationFolder, "server.hsconf") },
                { "OSVersion", Path.Combine(_osInstallationFolder, "version.txt") },
                { "applicationHost.config", _iisApplicationHostPath },
                { "machine.config", _machineConfigPath },
                { "web.config", _iisWebConfigPath }
            };

            // Add OS log and configuration files
            foreach (KeyValuePair <string, string> serviceFileEntry in osServiceNames)
            {
                bool isNlogConfFile = serviceFileEntry.Key.ToLower().Contains(@"\nlog");

                confFilePath = isNlogConfFile ? Path.Combine(_osInstallationFolder, serviceFileEntry.Key + ".config") : Path.Combine(_osInstallationFolder, serviceFileEntry.Key + ".exe.config"); // Check if it's server API or identity

                // Get log file location from conf file
                OSServiceConfigFileParser confParser = new OSServiceConfigFileParser(serviceFileEntry.Value, confFilePath);

                string logPath = isNlogConfFile ? confParser.LogServerAPIAndIdentityFilePath : confParser.LogFilePath;

                // Add properties file
                files.Add(serviceFileEntry.Value + " config", confFilePath);

                // Add log file
                files.Add(serviceFileEntry.Value + " log", logPath);
            }

            // Copy all files to the temporary folder
            foreach (KeyValuePair <string, string> fileEntry in files)
            {
                String filepath       = fileEntry.Value;
                String fileAlias      = fileEntry.Key;
                bool   isNlogConfFile = false;

                if (filepath != null)
                {
                    isNlogConfFile = filepath.ToLower().Contains("nlog.config");
                }

                FileLogger.TraceLog("Copying " + fileAlias + "... ");
                if (File.Exists(filepath))
                {
                    String realFilename = isNlogConfFile ? Path.GetFileName(filepath) + "_" + fileAlias : Path.GetFileName(filepath);
                    File.Copy(filepath, Path.Combine(_osPlatFilesDest, realFilename));
                }
                else
                {
                    FileLogger.TraceLog("(File does not exist)", true);
                }
            }

            // Export Environment variables
            foreach (System.Collections.DictionaryEntry env in Environment.GetEnvironmentVariables())
            {
                string name  = (string)env.Key;
                string value = (string)env.Value;

                Utils.WinUtils.WriteToFile(Path.Combine(_osPlatFilesDest, "EnvironmentVariables.txt"), name + ": " + value);
            }

            // Copy application pool configurations %SYSTEMDRIVE%\inetpub\temp\appPools
            FileSystemHelper fsHelper = new FileSystemHelper();

            appPoolConfigPath = fsHelper.GetPathWithWindowsRoot(appPoolConfigPath);
            fsHelper.DirectoryCopy(appPoolConfigPath, Path.Combine(_osPlatFilesDest, "AppPoolConfigurations"), true, false);
        }
Esempio n. 47
0
 public void x0TestJacobi()
 {
     //МСГ - зависит от нач приближения.
     using (FileLogger logger = new FileLogger())
     {
         (int, int)[] coord     = new(int, int)[4];
Esempio n. 48
0
        void Init()
        {
            LED = new OutputPort(launcherSettings.LEDPin, false);

            #region Settings

            var sd = GetRootDirectory();

            var settings = Settings.Init(sd != null ? sd + @"\imBMW.ini" : null);

            if (settingsOverride != null)
            {
                settingsOverride(settings);
            }

            var log = settings.Log || settings.LogToSD;
#if DEBUG
            log = true;
            settings.LogMessageToASCII = true;
#else
            // already inited in debug mode
            if (settings.Log)
            {
                Logger.Logged += Logger_Logged;
                Logger.Info("Logger inited");
            }
#endif
            if (settings.LogToSD && sd != null)
            {
                FileLogger.Init(sd + @"\Logs", () =>
                {
                    VolumeInfo.GetVolumes()[0].FlushAll();
                });
            }

            Logger.Info(version);

            Localization.SetCurrent(settings.Language);
            Comfort.AutoLockDoors    = settings.AutoLockDoors;
            Comfort.AutoUnlockDoors  = settings.AutoUnlockDoors;
            Comfort.AutoCloseWindows = settings.AutoCloseWindows;
            Comfort.AutoCloseSunroof = settings.AutoCloseSunroof;
            Logger.Info("Preferences inited");

            SettingsScreen.Instance.Status = version.Length > 11 ? version.Replace(" ", "") : version;

            #endregion

            #region iBus Manager

            // Create serial port to work with Melexis TH3122
            //ISerialPort iBusPort = new SerialPortEcho();
            ISerialPort iBusPort = new SerialPortTH3122(launcherSettings.iBusPort, launcherSettings.iBusBusyPin);
            Logger.Info("TH3122 serial port inited");

            /*InputPort jumper = new InputPort((Cpu.Pin)FEZ_Pin.Digital.An7, false, Port.ResistorMode.PullUp);
             * if (!jumper.Read())
             * {
             *  Logger.Info("Jumper installed. Starting virtual COM port");
             *
             *  // Init hub between iBus port and virtual USB COM port
             *  ISerialPort cdc = new SerialPortCDC(USBClientController.StandardDevices.StartCDC_WithDebugging(), 0, iBus.Message.PacketLengthMax);
             *  iBusPort = new SerialPortHub(iBusPort, cdc);
             *  Logger.Info("Serial port hub started");
             * }*/

            Manager.Init(iBusPort);
            Logger.Info("iBus manager inited");

            #endregion

            #region iBus IO logging

            Message sent1 = null, sent2 = null; // light "buffer" for last 2 messages
            bool    isSent1 = false;
            Manager.BeforeMessageReceived += (e) =>
            {
                LED.Write(Busy(true, 1));
            };
            Manager.AfterMessageReceived += (e) =>
            {
                LED.Write(Busy(false, 1));

                if (!log)
                {
                    return;
                }

                var logIco = "< ";
                if (e.Message.ReceiverDescription == null)
                {
                    if (sent1 != null && sent1.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent1.ReceiverDescription;
                        logIco = "<E";
                    }
                    else if (sent2 != null && sent2.Data.Compare(e.Message.Data))
                    {
                        e.Message.ReceiverDescription = sent2.ReceiverDescription;
                        logIco = "<E";
                    }
                }
                if (settings.LogMessageToASCII && e.Message.ReceiverDescription == null)
                {
                    Logger.Info(e.Message.ToPrettyString(true, true), logIco);
                }
                else
                {
                    Logger.Info(e.Message, logIco);
                }
            };
            Manager.BeforeMessageSent += (e) =>
            {
                LED.Write(Busy(true, 2));
            };
            Manager.AfterMessageSent += (e) =>
            {
                LED.Write(Busy(false, 2));

                if (!log)
                {
                    return;
                }

                Logger.Info(e.Message, " >");
                if (isSent1)
                {
                    sent1 = e.Message;
                }
                else
                {
                    sent2 = e.Message;
                }
                isSent1 = !isSent1;
            };
            Logger.Info("iBus manager events subscribed");

            #endregion

            #region Features

#if DEBUG
            InstrumentClusterElectronics.RequestDateTimeAndSetLocal(false);
#endif

            #endregion

            #region CAN BUS

            if (launcherSettings.CanBus != 0)
            {
                var speed = CanAdapterSettings.CanSpeed.Kbps100;
                CanAdapter.Current = new CanNativeAdapter(launcherSettings.CanBus, speed);
                //var canInterrupt = Cpu.Pin.GPIO_NONE;
                //var canInterrupt = Pin.Di2;
                //CanAdapter.Current = new CanMCP2515Adapter(Pin.SPI, Pin.SPI_ChipSelect, canInterrupt, speed, CanMCP2515AdapterSettings.AdapterFrequency.Mhz8);
                if (log)
                {
                    CanAdapter.Current.MessageReceived += Can_MessageReceived;
                    CanAdapter.Current.MessageSent     += Can_MessageSent;
                    CanAdapter.Current.Error           += Can_ErrorReceived;
                }
                CanAdapter.Current.IsEnabled = true;

                if (launcherSettings.E65Seats)
                {
                    //HardwareButton.Toggle(Pin.Di2, pressed => { if (pressed) E65Seats.EmulatorPaused = true; else E65Seats.EmulatorPaused = false; });
                    E65Seats.Init();
                    E65Seats.AutoHeater             = true;
                    E65Seats.AutoVentilation        = true;
                    HomeScreen.Instance.SeatsScreen = E65SeatsScreen.Instance;
                }

                Logger.Info("CAN BUS inited");
            }

            #endregion

            #region Set iPod or Bluetooth as AUX or CDC-emulator for Bordmonitor or Radio

            BluetoothWT32 wt32;
            if (settings.MediaShield == "WT32")
            {
                wt32   = new BluetoothWT32(launcherSettings.MediaShieldPort, Settings.Instance.BluetoothPin);
                player = wt32;
                InternalCommunications.Register(wt32);

                //byte gain = 0;
                //HardwareButton.OnPress(Pin.Di14, () => wt32.SetMicGain((byte)(++gain % 16)));
            }
            else
            {
                player = new BluetoothOVC3860(launcherSettings.MediaShieldPort, sd != null ? sd + @"\contacts.vcf" : null);
            }

            MediaEmulator emulator;
            if (settings.MenuMode == MenuMode.BordmonitorAUX ||
                settings.MenuMode == MenuMode.BordmonitorCDC ||
                Manager.FindDevice(DeviceAddress.OnBoardMonitor))
            {
                if (player is BluetoothWT32)
                {
                    ((BluetoothWT32)player).NowPlayingTagsSeparatedRows = true;
                }
                if (settings.MenuMode == MenuMode.BordmonitorCDC)
                {
                    emulator = new CDChanger(player, true);
                    if (settings.NaviVersion == NaviVersion.MK2)
                    {
                        Localization.Current = new RadioLocalization();
                        SettingsScreen.Instance.CanChangeLanguage = false;
                    }
                }
                else
                {
                    emulator = new BordmonitorAUX(player);
                }
                Bordmonitor.NaviVersion         = settings.NaviVersion;
                BordmonitorMenu.FastMenuDrawing = settings.NaviVersion == NaviVersion.MK4;
                //MenuScreen.MaxItemsCount = 6;
                BordmonitorMenu.Init(emulator);

                Logger.Info("Bordmonitor menu inited");
            }
            else
            {
                Localization.Current = new RadioLocalization();
                SettingsScreen.Instance.CanChangeLanguage = false;
                MultiFunctionSteeringWheel.EmulatePhone   = true;
                if (settings.MenuMode == MenuMode.MIDAUX)
                {
                    Radio.HasMID = true;
                    emulator     = new MIDAUX(player);
                }
                else
                {
                    Radio.HasMID = Manager.FindDevice(DeviceAddress.MultiInfoDisplay);
                    emulator     = new CDChanger(player);
                }
                var menu = RadioMenu.Init(emulator);
                menu.IsDuplicateOnIKEEnabled    = true;
                menu.TelephoneModeForNavigation = settings.MenuMFLControl;
                Logger.Info("Radio menu inited" + (Radio.HasMID ? " with MID" : ""));
            }

            player.IsShowStatusOnIKEEnabled = true;

            ShieldLED = new OutputPort(launcherSettings.MediaShieldLED, false);
            player.IsPlayingChanged += (p, e) =>
            {
                ShieldLED.Write(e.IsPlaying);
                RefreshLEDs();
            };
            player.StatusChanged += (p, e) =>
            {
                if (e.Event == PlayerEvent.IncomingCall && !p.IsEnabled)
                {
                    InstrumentClusterElectronics.Gong1();
                }
            };
            Logger.Info("Player events subscribed");

            #endregion

            RefreshLEDs();

            LED.Write(true);
            Thread.Sleep(50);
            LED.Write(false);
            Logger.Info("LED blinked - inited");
        }
Esempio n. 49
0
        public void GetReaderTest()
        {
            using (FileLogger l = new FileLogger("MdbContextTest", new FileLogSettings()
            {
                DateFolderMask = "yyyy-MM-dd"
            }))
            {
                MdbContextOptions.GetOptions().CommandTimeout = 120;
                using (var ctx = new MdbContext(_cn))
                {
                    l.Debug("Test 1 Start ");
                    int i = 0;
                    using (var dr = ctx.GetReader("Select * From PayDocs Where Handle In @handle",
                                                  "@handle", Enumerable.Range(3999750, 100)))
                    {
                        for (; dr.Read(); i++)
                        {
                            l.Debug(dr.GetRowJSON());
                        }
                    }
                    l.Debug($"Test 1 Finish rows result {i}");
                    l.Debug("Test 2 Start ");
                    i = 0;
                    using (var dr = ctx.GetReader("Select * From PayDocs Where Handle = @handle",
                                                  "@handle", 3999750))
                    {
                        for (; dr.Read(); i++)
                        {
                            l.Debug(dr.GetRowJSON());
                        }
                    }
                    l.Debug($"Test 2 Finish rows result {i}");
                    l.Debug("Test 3 Start ");
                    i = 0;
                    using (var dr = ctx.GetReader("Select * From PayDocs Where DateOper Between @d1 And @d2",
                                                  "@d1", vbo.Date().AddDays(-4), "@d2", vbo.Date()))
                    {
                        for (; dr.Read();)
                        {
                            i++;
                        }
                    }
                    l.Debug($"Test 3 Finish rows result {i}");
                    l.Debug("Test 4 Start ");
                    i = 0;
                    using (var dr = ctx.GetReader("Select * From PayDocs Where DateOper In @handle",
                                                  "@handle", Enumerable.Range(1, 5).Select(item => vbo.Date().AddDays(-5).AddDays(item))))
                    {
                        for (; dr.Read();)
                        {
                            i++;
                        }
                    }
                    l.Debug($"Test 4 Finish rows result {i}");
                    l.Debug("Test 5 Start ");
                    i = 0;
                    using (var dr = ctx.GetReader(@"Select * From PayDocs Inner Join Memorials On PayDocs.DocId = Memorials.DocId 
					Where DateOper In @handle And Contents Like @RUR"                    ,
                                                  "@handle", Enumerable.Range(1, 5).Select(item => vbo.Date().AddDays(-5).AddDays(item)), "@RUR", "%'RUB'%"))
                    {
                        for (; dr.Read(); i++)
                        {
                            l.Debug(dr.GetRowJSON());
                        }
                    }
                    l.Debug($"Test 5 Finish rows result {i}");
                    l.Debug("Test 6 Start ");
                    i = 0;
                    using (var dr = ctx.GetReader("Select * From PayDocs Where DateOper Between @d1 And @d2",
                                                  new MdbParameter("@d1", vbo.Date().AddDays(-4)),
                                                  new MdbParameter("@d2", vbo.Date())))
                    {
                        for (; dr.Read();)
                        {
                            i++;
                        }
                    }
                    l.Debug($"Test 6 Finish rows result {i}");
                    l.Debug("Test 7 Start ");
                    i = 0;
                    using (var dr = ctx.GetReader("select * from VClients where clnum between 37361-100 and 37361"))
                    {
                        DisplayData(dr.ToDataTable(), l);
                    }
                    l.Debug($"Test 7 Finish rows result {i}");
                }
            }
        }
Esempio n. 50
0
 public ILogger CreateLogger(string categoryName) {
     var logger = new FileLogger(categoryName, _writer);
     _loggers.Add(logger);
     return logger;
 }