Exemplo n.º 1
0
        public void Common_Create_New_File_On_Size_Limit_Exceed()
        {
            TextFileLogger logger = new TextFileLogger("log", 10000);

            for (int i = 0; i < 200; i++)
            {
                logger.Log(String.Format("{0}, Запись в журнале", DateTime.Now));
            }

            Assert.IsTrue(File.Exists("log-0.log"));

            FileInfo fileInfo = new FileInfo("log-0.log");

            Assert.IsTrue(fileInfo.Length > 10000);

            Assert.IsTrue(File.Exists("log-1.log"));

            StreamReader streamReader = new StreamReader(new FileStream("log-1.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

            Assert.IsTrue(streamReader.ReadLine().Contains("Запись в журнале"));

            streamReader.Close();
            streamReader.Dispose();

            logger.Dispose();
        }
Exemplo n.º 2
0
		public void CreateProvider()
		{
			if (File.Exists(LogFilePath))
				File.Delete(LogFilePath);

			logger = new TextFileLogger();
		}
Exemplo n.º 3
0
        public void BeginScopeIsNotImplemented()
        {
            var mockFileSystem = new MockFileSystem();
            var logger         = new TextFileLogger(LogLevel.Information, _filePath, mockFileSystem);

            Assert.Throws <NotImplementedException>(() => logger.BeginScope("tester"));
        }
Exemplo n.º 4
0
        /// <summary>
        /// This method runs the DI Example.
        /// </summary>
        private void DependencyInject()
        {
            var logger = new TextFileLogger();
            var di     = new Worker(logger);

            di.DoSomeWork(logger);
        }
Exemplo n.º 5
0
        public static string GetEmailContentToXmlByNode(string fileName, string node)
        {
            TextFileLogger log = new TextFileLogger();

            try
            {
                XmlDocument oXmlDoc = new XmlDocument();
                //  oXmlDoc.Load(SF.Framework.SFConfig.WebsitePhysicalPath + "/Content/EmailTemplate/" + fileName);
                //AppDomain.CurrentDomain.BaseDirectory
                string path = "";
                if (System.Web.HttpContext.Current != null)
                {
                    path = System.Web.HttpContext.Current.Server.MapPath("~/Content/EmailTemplate/" + fileName);
                }
                else
                {
                    path = ConfigurationManager.AppSettings["WebsitePath"] + "/Content/EmailTemplate/" + fileName;
                }
                oXmlDoc.Load(path);
                XmlNode oNode = oXmlDoc.SelectSingleNode("/emails/email[position()=1]");
                string  body  = oNode.SelectSingleNode(node).InnerText;
                return(body);
            }
            catch (Exception ex)
            {
                log.Log(ex);
                return("");
            }
        }
Exemplo n.º 6
0
        private List <string> LoadSubdomains(string url)
        {
            string testUrl    = url.Trim(new char[] { '*', '.' });
            var    subDomains = new List <string>();

            //This will have to get moved to a central db
            List <string> knownSubdomains = new List <string>();
            string        existingFile    = Path.Combine(Settings.ExistingDir, testUrl.Replace(".", "") + ".txt");

            if (File.Exists(existingFile))
            {
                knownSubdomains = File.ReadAllLines(existingFile).ToList();
            }

            HunterRequest request = new HunterRequest();

            request.Domain               = testUrl;
            request.KnownSubdomains      = knownSubdomains;
            request.SecurityTrailsAPIKey = Settings.SecurityTrailsAPI;
            request.VirusTotalAPIKey     = Settings.VirusTotalAPI;

            subDomains = Hunter.GatherAll(request);

            Log("Subdomains found: " + subDomains.Count);
            TextFileLogger.WriteOverwriteFile(Settings.ExistingDir, testUrl.Replace(".", "") + ".txt", subDomains);

            return(subDomains);
        }
Exemplo n.º 7
0
        private static void ExportData <T>(bool confirmExport)
        {
            if (!confirmExport)
            {
                return;
            }

            string prefix = typeof(T).Name;

            ILogger logger = new TextFileLogger(prefix, 10000000, true);

            if (prefix == "Bar")
            {
                logger.Log("<TICKER>,<PER>,<DATE>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>");

                foreach (Bar item in TradingData.Instance.Get <IEnumerable <Bar> >().OrderBy(i => i.DateTime))
                {
                    logger.Log(item.ToFinamString());
                }
            }
            else
            {
                foreach (T item in TradingData.Instance.Get <IEnumerable <T> >())
                {
                    logger.Log(item.ToString());
                }
            }
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            ///////////////////////////////////////////////
            //Local Variables

            string path     = Environment.CurrentDirectory;
            string fileName = "ExceptionLog.txt";

            int inputLength = 4;
            int maxGuesses  = 10;

            List <int> validNumbers = new List <int> {
                1, 2, 3, 4, 5, 6
            };

            Game game;

            TextFileLogger logger;

            ///////////////////////////////////////////////

            logger = new TextFileLogger(path, fileName);

            game = new Game(logger);

            game.InitializeGame(inputLength, maxGuesses, validNumbers);
            game.StartGameLoop();

            Console.Write("\n\nPress any key to close the console.  Thank you for playing!  :)");
            Console.ReadKey(true);
        }
Exemplo n.º 9
0
        public void WriteLogFileTest()
        {
            String lCompareTextFromFile;
            String lCompareText;
            String lDate = System.DateTime.Today.Year.ToString() +
                           System.DateTime.Today.Month.ToString() +
                           System.DateTime.Today.Day.ToString();
            String lFile    = "TextFileLoggerTest-" + lDate;
            String lMethod  = "WriteLogFileTest";
            String lMessage = "";
            String lTime    = System.DateTime.Now.ToString();

            lMessage  = "Datos para grabar.";
            lMessage += "\r\n" + "Segunda linea con datos.";
            lMessage += "\r\n" + "Tercera linea con datos.";
            //lMessage += "\n" + "";
            TextFileLogger lTextFileLogger = new TextFileLogger();

            lCompareText  = ((((lTime + " - ") + lFile + " - ") + lMethod + " - ") + lMessage + "\r\n");
            lCompareText += "\n";
            lCompareText += "---------------------------------------- \n";
            lTextFileLogger.WriteLogFile(lFile, lMethod, lMessage, lTime);

            lCompareTextFromFile = lTextFileLogger.ReadLogFile();

            Assert.AreEqual(lCompareText, lCompareTextFromFile);
        }
        public void TextFileLoggerCanLog()
        {
            string msgText  = "text file logger test";
            string expected = String.Empty;
            string actual   = String.Empty;

            Message         msg         = new GeneralMessage(msgText);
            StubFileFactory fileFactory = new StubFileFactory("dummy.txt");
            TextFileLogger  txtlogger   = new TextFileLogger(fileFactory);

            using (MemoryStream ms = fileFactory.MemoryStream)
            {
                txtlogger.Log(msg);

                ms.Position = 0;
                using (StreamReader reader = new StreamReader(ms, Encoding.UTF8))
                {
                    actual = reader.ReadToEnd();
                }
            }

            expected = DateTime.Now.ToShortDateString() + " " + msgText + Environment.NewLine;

            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 11
0
        static void Main()
        {
            //-------------------------
            // 2번 실행 안 되도록
            string strExe = "KMC_S2_CHT.exe";

            if (!AUtil.IsAppFirstRun(strExe))
            {
                MessageBox.Show("Program(" + strExe + ") is running!", "Program execution", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            //-------------------------

            // 2016.06.18
            // license check
            AVisionProBuild.CheckLicense("VisionPro.PatMax");
            ExceptionLogger logger    = new ExceptionLogger();
            TextFileLogger  txtLogger = new TextFileLogger();

            logger.AddLogger(txtLogger);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmMain());
        }
Exemplo n.º 12
0
        protected override void OnStartup(StartupEventArgs e)
        {
            try
            {
                var         config     = ApplicationConfiguration.FromJsonFile(_configFilename);
                IEyeTracker eyeTracker = null;
                switch (config.EyeTrackerName.ToUpper())
                {
                case "TOBII4C":
                    eyeTracker = new TobiiEyeTracker4C();
                    break;

                default:
                    throw new NotImplementedException($"Eye tracker {config.EyeTrackerName} not supported");
                }
                var logger = new TextFileLogger();
                App.Current.DispatcherUnhandledException += (sender, ev) =>
                {
#if DEBUG
                    ev.Handled = true;
#endif
                    logger.Log(ev.Exception);
                };
                var overlays = new List <IOverlay>();
                overlays.Add(new PositionOverlay());
                var window = new MainWindow(config, eyeTracker, logger, overlays);
                window.Show();
            }
            catch (Exception exception)
            {
                throw new StartupException("Initialization error", exception);
            }
        }
Exemplo n.º 13
0
 private void LogLinks(string log)
 {
     if (String.IsNullOrEmpty(log))
     {
         return;
     }
     TextFileLogger.Log(Settings.InterstingURLs, DateTime.Now.ToString("yyyy-MM-dd") + ".txt", log);
 }
Exemplo n.º 14
0
        public static void Main(string[] args)
        {
            var logger           = new TextFileLogger("log.txt");
            var renamerArguments = GetArguments(args, logger);

            ProcessExecutor processExecutor = new ProcessExecutor();

            processExecutor.Execute(renamerArguments, logger);
        }
        public void TextFileCanBeCreated()
        {
            IFileFactory fileFactory = new StubFileFactory("dummy.txt");

            TextFileLogger txtLogger = new TextFileLogger(fileFactory);

            Assert.IsNotNull(txtLogger);
            Assert.IsInstanceOfType(txtLogger, typeof(ILogger));
        }
Exemplo n.º 16
0
        public void CreateProvider()
        {
            if (File.Exists(LogFilePath))
            {
                File.Delete(LogFilePath);
            }

            logger = new TextFileLogger();
        }
Exemplo n.º 17
0
Arquivo: Export.cs Projeto: w1r2p1/TRx
        public static void ExportData <T>(string prefix, IEnumerable <T> data)
        {
            //string prefix = typeof(T).Name;
            ILogger logger = new TextFileLogger(prefix, 10000000, true);

            foreach (T item in data)
            {
                logger.Log(item.ToString());
            }
        }
Exemplo n.º 18
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            var assemblyInfo  = new AssemblyInfo(typeof(App).Assembly, "Resources.LICENSE");
            var dataDirectory = new AppDataRoaming(assemblyInfo.Product);
            var logger        = new TextFileLogger(dataDirectory.GetFilePath($"{assemblyInfo.FileName}.log"));

            AppHelper.AssemblyInfo            = assemblyInfo;
            AppHelper.DataDirectory           = dataDirectory;
            AppHelper.Logger                  = logger;
            AppHelper.CatchUnhandledException = true;
            AppHelper.SetAppMutex($"Global\\{assemblyInfo.Guid}");
        }
Exemplo n.º 19
0
        public Task Execute(IJobExecutionContext context)
        {
            var          logger       = new TextFileLogger();
            var          policyConfig = new PolicyConfig();
            ITaskHandler taskHandler  = new PolicyTaskHandler(logger, policyConfig);

            taskHandler.Process();

            //logger.Log(LogLevel.Debug, "测试");

            return(Task.CompletedTask);
        }
Exemplo n.º 20
0
        public MerakiModule(TextFileLogger logger, SmartFlowContext context)
            : base("/meraki")
        {
            // Meraki will use this to validate we are the correct host
            Get["/"] = _ => Settings.Default.Validator;

            Post["/"] = _ =>
            {
                var req = this.Bind<MerakiDto>();

                // secret didnt match, return FORBIDDEN
                if (req.Secret != Settings.Default.Secret) return 403;

                // log to file (will log to database once its all working etc..)
                logger.Write(req.ToString(), Enums.LogLevel.Information);

                var floors = req.Data.ApFloors.Select(x => x.ToFloorEntity(req.Data.ApMac));

                foreach (var floor in floors)
                {
                    if (context.Floors.Any(x => x.ApMac == floor.ApMac && x.Name == floor.Name))
                    {
                        context.Floors.Attach(floor);
                    }
                    else
                    {
                        context.Floors.Add(floor);
                    }
                }

                var thisTime = DateTime.Now;
                var isDaylight = TimeZoneInfo.Local.IsDaylightSavingTime(thisTime);

                var observations = req.Data.Observations.Select(y => new Observation
                {
                    ApMac = req.Data.ApMac,
                    ClientMac = y.ClientMac,
                    Ipv4 = y.Ipv4,
                    Ipv6 = y.Ipv6,
                    Manufacturer = y.Manufacturer,
                    Os = y.Os,
                    Rssi = y.Rssi,
                    SeenTime = isDaylight ? y.SeenTime.AddHours(1) : y.SeenTime,
                    SeenEpoch = y.SeenEpoch,
                    Location = y.Location != null ? y.Location.ToLocationEntity(req.Data) : null
                });

                context.Observations.AddRange(observations);

                // return CREATED
                return 201;
            };
        }
Exemplo n.º 21
0
        public SelfContainedMigrator(string migrationName, Guid migrationId, string sourceName, string targetName)
        {
            JobQueueManager.Start(1);

            _integration = new Integration(migrationId, migrationName, Assembly.GetCallingAssembly().Location, sourceName, targetName);

            var loggingPath = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location) + @"\Logs";

            var textFileLogger = new TextFileLogger(loggingPath);

            SyncEngineLogger.RegisterLogger(textFileLogger, LoggingLevel.ErrorsWarningsInfoDebugAndTrace, -1);
        }
Exemplo n.º 22
0
        public void Instance_Get2Instances_ReturnsSameInstances()
        {
            TextFileLogger.CreateInstance("test");

            var instance1 = TextFileLogger.GetInstance();
            var instance2 = TextFileLogger.GetInstance();

            Assert.AreSame(instance1, instance2);
            instance1.TestField++;
            Assert.AreEqual(instance1.TestField, instance2.TestField);
            instance2.TestField++;
            Assert.AreEqual(instance1.TestField, instance2.TestField);
        }
Exemplo n.º 23
0
        public void RunProcessAndLogToTextFile()
        {
            TextFileLogger textFileLogger = new TextFileLogger();

            try
            {
                //Run process
            }
            catch (Exception ex)
            {
                textFileLogger.LogMessage(ex.Message);
            }
        }
Exemplo n.º 24
0
        protected override void ConfigureApplicationContainer(TinyIoCContainer container)
        {
            base.ConfigureApplicationContainer(container);

            var logger = new TextFileLogger(Settings.Default.FilePath, "Request", null, 30, "SmartFlow", "1")
            {
                MaximumLogSize = 15
            };

            container.Register(logger);
            container.Register<JsonSerializer, SmartFlowJsonSerializer>();

            logger.Write("Logging Configured", Enums.LogLevel.Information);
        }
Exemplo n.º 25
0
 public int SaveChanges()
 {
     try
     {
         int i = this.CurrentDbContext.SaveChanges();
         return(i);
     }
     catch (Exception dbEx)
     {
         TextFileLogger log = new TextFileLogger();
         log.Log(dbEx);
         return(0);
     }
 }
Exemplo n.º 26
0
 public static ILogger GetMultiTargetLogger(ILogger logger)
 {
     if (multiTargetLogger == null)
     {
         MultiTargetLogger multiLogger = new MultiTargetLogger();
         TextFileLogger    fileLogger  = new TextFileLogger();
         fileLogger.Folder = new DirectoryInfo(ContentRoot);
         multiLogger.AddLogger(fileLogger);
         multiLogger.AddLogger(logger);
         multiLogger.StartLoggingThread();
         multiTargetLogger = multiLogger;
     }
     return(multiTargetLogger);
 }
Exemplo n.º 27
0
        public override void Load()
        {
            var loggers                = new List <ILogger>();
            var consoleLogger          = new ConsoleLogger();
            var decoratedConsoleLogger = new PrependDateLogger(consoleLogger);
            var fileLogger             = new TextFileLogger();
            var decoratedFileLogger    = new PrependDateLogger(fileLogger);

            loggers.Add(consoleLogger);
            loggers.Add(decoratedConsoleLogger);
            loggers.Add(fileLogger);
            loggers.Add(decoratedFileLogger);

            this.Bind <ILogger>().To <CompositeLogger>().WithConstructorArgument(loggers);
        }
Exemplo n.º 28
0
        static public void HandleException(System.Exception ex, string message = "An errror occured in LBF Video Lib", bool ignoreException = true)
        {
            // Format the exception message.
            ExceptionFormatter formater          = new ExceptionFormatter();
            string             formatedException = formater.Format(message, ex);

            // Log error message in production category.
            // If severity is critical then it also send error to config mail address.
            TextFileLogger.Log(formatedException, ErrorLogFileName);

            if (!ignoreException)
            {
                throw ex;
            }
        }
Exemplo n.º 29
0
        public void TraceLogWritesToTextFile(LogLevel logLevel)
        {
            var mockFileSystem = new MockFileSystem();

            var logger = new TextFileLogger(LogLevel.Trace, _filePath, mockFileSystem);

            logger.Log(logLevel, _logMessage);

            var logFile      = mockFileSystem.GetFile(_filePath);
            var fileContents = logFile.TextContents.ToLower();

            Assert.IsTrue(logLevel == LogLevel.None
                ? fileContents.Contains($"{_logMessage}")
                : fileContents.Contains($"{logLevel.ToString().ToLower()}: {_logMessage}"));
        }
Exemplo n.º 30
0
        public void DeleteFileWhenInitialize()
        {
            "使用 With 初始化时,不能要求文件存在。".Test((Func <TextFileLogger, TextFileLogger> extraBuilder) =>
            {
                var testFile = PrepareNotExistFile("test21.md");

                var aLogger = extraBuilder(new TextFileLogger(new FileInfo(testFile.FullName)));
                aLogger.Message("YY");
                aLogger.Close();

                // 无异常。
            }).WithArguments(
                x => x.WithMaxFileSize(100),
                x => x.WithMaxLineCount(100),
                x => x.WithMaxLineCount(100, 50),
                x => x.WithWholeFileOverride()
                );

            "初始化时,超过大小的文件内容会清空。".Test(() =>
            {
                const string testFile = "test22.md";
                File.WriteAllText(testFile, "XXXXXXXX\n");

                var aLogger = new TextFileLogger(new FileInfo(testFile))
                              .WithMaxFileSize(4);
                aLogger.Message("YY");
                aLogger.Close();

                var lines = File.ReadAllLines(testFile);
                Assert.AreEqual(1, lines.Length);
                Assert.IsTrue(lines[0].Contains("YY"));
            });

            "初始化时,超过行数的文件前面行会删除。".Test(() =>
            {
                const string testFile = "test23.md";
                File.WriteAllText(testFile, "XXXXXXXX\n\nYYYYYYYY\nZZZZZZZZ\n");

                var aLogger = new TextFileLogger(new FileInfo(testFile))
                              .WithMaxLineCount(3, 1);
                aLogger.Message("WW");
                aLogger.Close();

                var lines = File.ReadAllLines(testFile);
                Assert.AreEqual(2, lines.Length);
                Assert.IsTrue(lines[0].Contains("ZZZZZZZZ"));
            });
        }
Exemplo n.º 31
0
        public void SubscribeShouldIncrementSubscribers()
        {
            BamServer server = CreateServer(MethodBase.GetCurrentMethod().Name);
            ILogger   logger = new TextFileLogger();

            Expect.AreEqual(0, server.Subscribers.Length);
            server.Subscribe(logger);
            Expect.AreEqual(1, server.Subscribers.Length);
            server.Subscribe(logger);
            Expect.AreEqual(1, server.Subscribers.Length); // should only get added once
            ILogger winLogger = new WindowsLogger();

            server.Subscribe(winLogger);
            Expect.AreEqual(2, server.Subscribers.Length);
            Expect.IsTrue(server.IsSubscribed(winLogger));
        }
Exemplo n.º 32
0
Arquivo: Proboy.cs Projeto: w1r2p1/TRx
        private static void ExportData <T>(bool confirmExport)
        {
            if (!confirmExport)
            {
                return;
            }

            string prefix = typeof(T).Name;

            ILogger logger = new TextFileLogger(prefix, 10000000);

            foreach (T item in TradingData.Instance.Get <IEnumerable <T> >())
            {
                logger.Log(item.ToString());
            }
        }
Exemplo n.º 33
0
        static void Main(string[] args)
        {
            ProcessLog = new TextFileLogger(Settings.Default.LogPath,
                      AssemblyName, null, Settings.Default.LogDeleteThreshold, Title, Version.ToString())
            {
                MaximumLogSize = Settings.Default.LogFileMaxSize
            };
#if DEBUG
            var service = new HostService();
            service.Start();
            Console.WriteLine("Service Running...");
            Console.ReadLine();
#else
            RunService();
#endif
        }
Exemplo n.º 34
0
        private void unlockFilesButton_Click(object sender, EventArgs e)
        {
            ToggleAllButtons(false);

            var confirmation = MessageBox.Show("Ready to start craXcel?", "Confirm", MessageBoxButtons.YesNo);

            if (confirmation == DialogResult.No || fileListBox.Items.Count == 0)
            {
                ToggleAllButtons(true);

                return;
            }

            List <string> filePaths = fileListBox.Items.OfType <string>().ToList();

            var logger = new TextFileLogger();

            int filesUnlocked = CraxcelProcessor.UnlockFiles(filePaths, logger);

            MessageBox.Show($"{filesUnlocked}/{filePaths.Count} files unlocked.", "Complete");

            // TO-DO - Possibly only works on Windows?
            try
            {
                var craxcelDir = new ProcessStartInfo(ApplicationSettings.CRAXCEL_DIR.FullName)
                {
                    UseShellExecute = true,
                    Verb            = "open"
                };

                var logFile = new ProcessStartInfo(logger.LogFile.FullName)
                {
                    UseShellExecute = true,
                    Verb            = "open"
                };

                Process.Start(craxcelDir);
                Process.Start(logFile);
            }
            catch
            {
            }

            ResetForm();

            ToggleAllButtons(true);
        }