Exemple #1
0
        public bool Check()
        {
            var logger = new TextLogger(LogSeverity.Warning);

            logger.PutLine("*** Control d’intégrité ***");
            logger.PutLine($"Table: {AppContext.TableManager.Incoterms.Name}");
            logger.PutLine("La contrainte d’intégrité n° 16 est violée par les éléments suivants :");

            bool err = false;

            foreach (uint prodID in m_ndxerLabelProdNbers.Attributes)
            {
                if (m_ndxerMappingProdNbers.Get(prodID).Any())
                {
                    logger.PutLine(m_ndxerLabelProdNbers.Get(prodID).First().ToString());

                    logger.PutLine();
                    err = true;
                }
            }


            if (err)
            {
                logger.Flush();
            }

            return(!err);
        }
        /// <summary>
        /// Trae todos los datos de los clientes
        /// </summary>
        /// <returns>Data Table con los datos de los clientes</returns>
        public ListParametro GetManyParametro(String tipoParametro)
        {
            ListParametro listParametro;

            try
            {
                var       conector  = new ConectorParametro();
                DataTable dtCliente = conector.GetManyParametro(tipoParametro);
                listParametro = new ListParametro {
                    success = true, message = String.Empty
                };
                listParametro.listParametro = new List <Parametro>();
                foreach (DataRow row in dtCliente.Rows)
                {
                    var item = new Parametro();
                    item.parametroId         = Convert.ToInt32(row["PARAMETRO_ID_IN"]);
                    item.parametroCodigo     = Convert.ToInt32(row["PARAMETRO_CODIGO_IN"]);
                    item.tipoParametro       = Convert.ToString(row["TIPO_PARAMETRO_NV"]);
                    item.valorParametroCorto = Convert.ToString(row["VALOR_DE_CORTO_NV"]);
                    item.valorParametro      = Convert.ToString(row["VALOR_DES_LARGA_NV"]);
                    listParametro.listParametro.Add(item);
                }
            }
            catch (Exception ex)
            {
                listParametro = new ListParametro {
                    success = false, message = ex.Message
                };
                TextLogger.LogError(LogManager.GetCurrentClassLogger(), ex, "Error En el metodo: getManyParametro");
            }
            return(listParametro);
        }
Exemple #3
0
        public bool Check()
        {
            var logger = new TextLogger(LogSeverity.Warning);

            logger.PutLine("*** Control d’intégrité ***");
            logger.PutLine($"Table: {AppContext.TableManager.Suppiers.Name}");
            logger.PutLine("La contrainte d’intégrité n° 6 est violée par les éléments suivants :");


            bool anyErr = false;

            using (var ndxer = new AttrIndexer <string>(m_srcSuppmiers, d => (d as DataSupplier).Name,
                                                        StringComparer.CurrentCultureIgnoreCase))
            {
                ndxer.Connect();

                foreach (string name in ndxer.Attributes)
                {
                    if (ndxer.Get(name).Count() != 1)
                    {
                        logger.PutLine("Les éléments suivant sont identiques:");
                        foreach (var item in ndxer.Get(name))
                        {
                            logger.PutLine(item);
                        }

                        logger.PutLine();
                        anyErr = true;
                    }
                }
            }

            return(!anyErr);
        }
Exemple #4
0
        static void DeleteFuzzyData(IDatumProvider dp, int[] indices)
        {
            if (MessageBox.Show(ASK_DELETE, "Confirmation requise",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                int nbDeleted = 0;

                try
                {
                    for (int i = indices.Length - 1; i >= 0; --i)
                    {
                        int    ndx   = indices[i];
                        IDatum datum = dp.Get(ndx);
                        var    item  = datum as ITaggedRow;
                        item.Disabled = true;
                        dp.Replace(ndx, datum);
                        ++nbDeleted;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                TextLogger.Info(string.Format("{0} élément(s) supprimé(s).", nbDeleted));
            }
        }
Exemple #5
0
        public Boolean InsertPunto(Punto punto)
        {
            Boolean resultado;

            try
            {
                string conexionString = Conexion.ConexionGmaps();
                var    storeProcedure = new StoreProcedure("[dbo].[SP_PUNTO_INSERT]");
                storeProcedure.AddParameter("@NOMBRE_NV", punto.Nombre, DirectionValues.Input);
                storeProcedure.AddParameter("@TIPO_PUNTO_ID_IN", punto.TipoPuntoId, DirectionValues.Input);
                storeProcedure.AddParameter("@DEPARTAMENTO_ID_IN", punto.DepartamentoId, DirectionValues.Input);
                storeProcedure.AddParameter("@LATITUD_DC", punto.Latitud, DirectionValues.Input);
                storeProcedure.AddParameter("@LONGITUD_DC", punto.Longitud, DirectionValues.Input);
                storeProcedure.AddParameter("@DIRECCION_NV", punto.Direccion, DirectionValues.Input);
                resultado = storeProcedure.ExecuteStoredProcedure(conexionString);
                if (storeProcedure.ErrorMessage != String.Empty)
                {
                    throw new Exception("Procedimiento Almacenado :[dbo].[SP_PUNTO_INSERT] Descripcion:" + storeProcedure.ErrorMessage.Trim());
                }
            }
            catch (Exception ex)
            {
                TextLogger.LogError(LogManager.GetCurrentClassLogger(), ex, "Error En el metodo: InsertDireccionCliente");
                throw new Exception("Procedimiento Almacenado :[dbo].[SP_PUNTO_INSERT]" + ex);
            }
            return(resultado);
        }
Exemple #6
0
        protected override void RegisterRequiredTypes(IContainerRegistry containerRegistry)
        {
            RegisterRequiredTypesCalled = true;

            base.RegisterRequiredTypes(containerRegistry);

            var logger = new TextLogger();

            MockContainer.Setup(x => x.Resolve(typeof(ILoggerFacade))).Returns(logger);

            var moduleInitializer = new ModuleInitializer(MockContainer.Object, logger);

            MockContainer.Setup(x => x.Resolve(typeof(IModuleInitializer))).Returns(moduleInitializer);
            MockContainer.Setup(x => x.Resolve(typeof(IModuleManager))).Returns(new ModuleManager(moduleInitializer, DefaultModuleCatalog, logger));
            MockContainer.Setup(x => x.Resolve(typeof(IRegionBehaviorFactory))).Returns(new RegionBehaviorFactory(MockContainer.Object));

            var regionBehaviorFactory = new RegionBehaviorFactory(MockContainer.Object);

            MockContainer.Setup(x => x.Resolve(typeof(IRegionBehaviorFactory))).Returns(regionBehaviorFactory);

            MockContainer.Setup(x => x.Resolve(typeof(RegionAdapterMappings))).Returns(new RegionAdapterMappings());
            MockContainer.Setup(x => x.Resolve(typeof(SelectorRegionAdapter))).Returns(new SelectorRegionAdapter(regionBehaviorFactory));
            MockContainer.Setup(x => x.Resolve(typeof(ItemsControlRegionAdapter))).Returns(new ItemsControlRegionAdapter(regionBehaviorFactory));
            MockContainer.Setup(x => x.Resolve(typeof(ContentControlRegionAdapter))).Returns(new ContentControlRegionAdapter(regionBehaviorFactory));
        }
Exemple #7
0
        public bool Check()
        {
            var logger = new TextLogger(LogSeverity.Warning);

            logger.PutLine("*** Control d’intégrité ***");
            logger.PutLine($"Table: {AppContext.TableManager.Countries.Name}");
            logger.PutLine("Les élemnets suivants ont un numerà de géneration invalide:");

            using (IDatumProvider dp = AppContext.TableManager.TablesGeneration.DataProvider)
            {
                dp.Connect();

                bool anyErr = false;

                if (dp.Count > 0)
                {
                    foreach (FileGeneration d in dp.Enumerate())
                    {
                        if (d.Generation == 0)
                        {
                            logger.PutLine(d.ToString());
                            anyErr = true;
                        }
                    }
                }

                if (anyErr)
                {
                    logger.Flush();
                }

                return(!anyErr);
            }
        }
        void PerformanceTestRL()
        {
            // create a lox for release logging
            Lox          lox       = new Lox("ReleaseLox");
            TextLogger   relLogger = Lox.CreateConsoleLogger();
            MemoryLogger ml        = new MemoryLogger();


            lox.SetVerbosity(relLogger, Verbosity.Verbose, "/CON");
            lox.SetVerbosity(ml, Verbosity.Verbose, "/MEM");


            lox.Info("/CON", "Logging simple info lines into a memory logger");

            AString msgBuf   = new AString( );
            long    fastest  = long.MaxValue;
            Ticks   timer    = new Ticks();
            int     qtyLines = 1000;
            int     qtyLoops = 2000; //1000

            if (System.Diagnostics.Debugger.IsAttached)
            {
                qtyLines = qtyLoops = 10;
            }

            for (int i = 0; i < qtyLoops; i++)
            {
            #if ALOX_DBG_LOG || ALOX_REL_LOG
                ml.MemoryLog.Clear();
            #endif

                timer.Set();
                for (int ii = 0; ii < qtyLines; ii++)
                {
                    lox.Info("/MEM", "Test Line");
                    if (i == 0 && ii == 0)
                    {
                        Console.WriteLine(ml.MemoryLog.ToString());
                    }
                }
                long t = timer.Age().Raw();

                if (fastest > t)
                {
                    fastest = t;
                    lox.Info("/CON", msgBuf.Clear()._("Pass ")._(i, 3)._(" is new fastest:  ")
                             ._((int)(new Ticks(fastest)).InMicros(), 0)
                             ._(" micros per ")._(qtyLines)._(" logs."));
                }
            }

            double microsPerLog  = ((double)(new Ticks(fastest)).InMicros()) / qtyLines;
            int    logsPerSecond = (int)(1000000.0 / microsPerLog);
            lox.Info("/CON", msgBuf._()._("  ")._(ESC.MAGENTA)._("Fastest Release Logging: ")
                     ._(microsPerLog)._(" micros per log (resp ")
                     ._(logsPerSecond)._(" logs per second) "));

            lox.RemoveLogger(ml);
            lox.RemoveLogger(relLogger);
        }
Exemple #9
0
        private void Application_OnError(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;
            HttpContext     context         = httpApplication.Context;
            Exception       ex = context.Server.GetLastError();

            if (ex is HttpException)
            {
                HttpException ex2 = ex as HttpException;
                if (ex2.GetHttpCode() == 404)
                {
                    string physicalPath = httpApplication.Request.PhysicalPath;
                    TextLogger.Write(string.Format("文件不存在:{0}", httpApplication.Request.Url.AbsoluteUri));
                    return;
                }
            }
            if (ex.InnerException != null)
            {
                ex = ex.InnerException;
            }
            StringBuilder stringBuilder = new StringBuilder().AppendFormat("访问路径:{0}", GameRequest.GetRawUrl()).AppendLine().AppendFormat("{0} thrown {1}", ex.Source, ex.GetType().ToString())
                                          .AppendLine()
                                          .Append(ex.Message)
                                          .Append(ex.StackTrace);

            TextLogger.Write(stringBuilder.ToString());
        }
Exemple #10
0
        //protected:
        protected override void OnLoad(EventArgs e)
        {
            Opts.WindowPlacement wp = AppContext.Settings.UserSettings.WindowPlacement[OPT_KEY];

            if (wp != null)
            {
                Location = new Point(wp.Left, wp.Top);
            }
            else
            {
                int ScreenWidth = Screen.GetWorkingArea(this).Width;
                int x           = (ScreenWidth - Width) >> 1;

                Left = x > 0 ? x : 0;
                Top  = 0;
            }

            if (!AppContext.Settings.UserSettings.LogWindowHidden)
            {
                m_logWindow.Show(this);
            }

            TextLogger.Info($"Hub Governor version: {Assembly.GetExecutingAssembly().GetName().Version}");
            TextLogger.Info($"Version des données: {AppContext.Settings.AppSettings.DataGeneration}");

            base.OnLoad(e);
        }
Exemple #11
0
 void Awake()
 {
     if (Instance == null)
     {
         Instance = this;
     }
 }
Exemple #12
0
        public void Run()
        {
            Assert(!IsDisposed);


            m_pendingData.Clear();
            m_ignoredRows.Clear();

            foreach (List <IDataRow> lst in m_importedData.Values)
            {
                lst.Clear();
            }

            SetupSupplier();

            var logger = new TextLogger(LogSeverity.Error);

            for (int i = 0; i < m_srcData.Length; ++i)
            {
                if (ParseSpotValue(i) == null)
                {
                    m_ignoredRows.Add(i);
                    logger.PutLine($"La ligne N° {i + 1} a été ignorée.");
                }
                else
                {
                    foreach (uint idTable in m_pendingData.Keys)
                    {
                        m_importedData[idTable].Add(m_pendingData[idTable]);
                    }
                }

                m_pendingData.Clear();
            }
        }
Exemple #13
0
        static void Main(string[] args)
        {
            UnityContainer container = new UnityContainer();

            container.RegisterInstance <IServiceLocator>(new UnityServiceLocatorAdapter(container));

            container.RegisterType <IModuleInitializer, ModuleInitializer>();

            TextLogger logger = new TextLogger();

            container.RegisterInstance <ILoggerFacade>(logger);

            IEventAggregator eventAggregator = new EventAggregator();

            container.RegisterInstance <IEventAggregator>(eventAggregator);

            ModuleCatalog catalog = new ModuleCatalog();

            //catalog.AddModule(typeof(RFID.RFIDModule));
            catalog.AddModule(typeof(BookInformation.BookInformationModule));
            catalog.AddModule(typeof(BookLocation.BookLocationModule));
            container.RegisterInstance <IModuleCatalog>(catalog);

            container.RegisterType <IModuleManager, ModuleManager>();
            IModuleManager manager = container.Resolve <IModuleManager>();

            manager.Run();
            //测试RFID服务模块的功能
            //RFIDUnitTest.testRFID(container);
            /******/
            //测试串口服务的功能
            //SerialUnitTest.testSerial(container);
            //测试数据库功能
            DatabaseUnitTest.testAllDatabase(container);
        }
Exemple #14
0
 private void Send(object email)
 {
     try
     {
         SmtpClient smtpClient = new SmtpClient(this.SmtpServer)
         {
             UseDefaultCredentials = false,
             DeliveryMethod        = SmtpDeliveryMethod.Network,
             Credentials           = new NetworkCredential(this.Accounts, this.Password)
         };
         MailMessage mailMessage = new MailMessage(this.SmtpSenderEmail, email.ToString(), this.Subject, this.Content)
         {
             IsBodyHtml   = true,
             BodyEncoding = System.Text.Encoding.GetEncoding("gb2312")
         };
         if (this.Port != 25)
         {
             smtpClient.EnableSsl = true;
         }
         smtpClient.Send(mailMessage);
         mailMessage.Dispose();
     }
     catch (System.Exception ex)
     {
         TextLogger.Write(ex.ToString());
     }
 }
 public UserRegistersMonitor()
 {
     InitializeComponent();
     _currentValues = new ObservableCollection<DeviceUserRegister>();
     _logger = new TextLogger();
     _logger.LogFilePath = AppDomain.CurrentDomain.BaseDirectory + "UserRegs_Monitor_LOG.txt";
 }
        /// <summary>
        /// Creates a new instance of the ZvtEcrCommunication.
        /// </summary>
        /// <param name="portSettings">Specifies the serial port where the payment terminal is connected.</param>
        /// <param name="logger">Specifies where logging information should be written to.</param>
        /// <param name="logLevel">Specifies the log verbosity.</param>
        public ZvtCommunication(ZvtSerialPortSettings portSettings, TextWriter logger, LogLevel logLevel = LogLevel.Everything)
        {
            KeepConnectionOpen = false;

            var textLogger = new TextLogger(null, logLevel, @"ZVTCommandEnvironment", logger);

            LogManager.Global = new LogManager(true, textLogger);

            XElement el = new XElement("Config",
                                       new XElement("Transport", "Serial"),
                                       new XElement("TransportSettings",
                                                    new XElement("Port", portSettings.Port),
                                                    new XElement("BaudRate", portSettings.Baud),
                                                    new XElement("StopBits", portSettings.StopBits),
                                                    new XElement("Parity", portSettings.Parity)
                                                    )
                                       );

            _ZvtEnvironment = new ZVTCommandEnvironment(el.ToXmlElement());
            _ZvtEnvironment.StatusReceived += ZvtEnvironmentOnStatusReceived;

            // keep COM port open
            _ZvtEnvironment.OpenConnection  += () => true;
            _ZvtEnvironment.CloseConnection += () => !KeepConnectionOpen;
        }
Exemple #17
0
        private static void DependencyInversion()
        {
            var processorNotDI = new ProcessorNotDI();

            var textLogger = new TextLogger();
            var processore = new Processor(textLogger);
        }
Exemple #18
0
 public ModuleDIMonitor()
 {
     InitializeComponent();
     _currentStatus = new DeviceDIModule();
     _logger = new TextLogger();
     _logger.LogFilePath = AppDomain.CurrentDomain.BaseDirectory + "TS_ModuleMonitor_LOG.txt";
 }
Exemple #19
0
        public void SimpleWrite()
        {
            TextLogger logger = new TextLogger();

            logger.Write("Foo");
            logger.ToString().Should().Be("Foo");
        }
Exemple #20
0
        public void Test2()
        {
            var now = new DateTime(2015, 2, 1);
            StreamTextWriterFactory writerFactory = new StreamTextWriterFactory(new DayLogPathFactory());
            TextLogger logger = new TextLogger(writerFactory, new LogDescriptor());

            writerFactory.NowGetter = () => now;
            logger.Write(new LogItem()
            {
                Time    = now,
                Message = "测试内容。",
                Type    = LogType.Info
            });
            System.Threading.Thread.Sleep(1001);
            var path = GA.FullPath(LogFolder, "2015年02月", "01.log");

            try
            {
                Assert.Equal(now.ToString("HH:mm:ss.ffff") + " [消息] 测试内容。\r\n", GA.IO.ShareReadAllText(path, Encoding.UTF8));
            }
            catch (UnauthorizedAccessException)
            {
                //....
            }
        }
Exemple #21
0
        public void SimpleWriteClipboardData()
        {
            TextLogger logger = new TextLogger();

            logger.Write("Foo");
            logger.GetClipboardData().Data.Should().Be("Foo");
        }
    private void TrySearchObject()
    {
        if (Interlocked.CompareExchange(ref _detectionCompleted, 0, 1) == 1)
        {
            if (_cachedCameraMain == null)
            {
                _cachedCameraMain = Camera.main;
            }

            var cameraLocation = new ObjectAnchorsLocation
            {
                Position    = _cachedCameraMain.transform.position,
                Orientation = _cachedCameraMain.transform.rotation,
            };

            var coordinateSystem = ObjectAnchorsWorldManager.GlobalCoordinateSystem;

            Task.Run(async() =>
            {
                try
                {
                    await DetectObjectAsync(coordinateSystem, cameraLocation);
                }
                catch (Exception ex)
                {
                    UnityEngine.WSA.Application.InvokeOnAppThread(() =>
                    {
                        TextLogger.Log($"Detection failed. Exception message: {ex.ToString()}");
                    }, false);
                }

                Interlocked.CompareExchange(ref _detectionCompleted, 1, 0);
            });
        }
    }
Exemple #23
0
        public void SimpleUnderline()
        {
            TextLogger logger = new TextLogger();

            logger.Write(WriteStyle.Underline, "Foo");
            logger.ToString().Should().Be("Foo\r\n---");
        }
Exemple #24
0
        /// <summary>
        /// Inserta nuevo cajero automatico
        /// </summary>
        /// <param name="cajerAutomatico">entidad cajero automatico</param>
        /// <returns>devuelve un booleano true o false</returns>
        public Boolean InsertCajeroAutomatico(CajerAutomatico cajerAutomatico)
        {
            Boolean resultado;

            try
            {
                var spInsertCajero = new StoreProcedure("[dbo].[SP_CAJERO_AUTOMATICO_INSERT]");
                spInsertCajero.AddParameter("@NOMBRE_NV", cajerAutomatico.Nombre, DirectionValues.Input);
                spInsertCajero.AddParameter("@TIPO_PUNTO_ID_IN", cajerAutomatico.TipoPuntoId, DirectionValues.Input);
                spInsertCajero.AddParameter("@DEPARTAMENTO_ID_IN", cajerAutomatico.DepartamentoId, DirectionValues.Input);
                spInsertCajero.AddParameter("@LATITUD_DC", cajerAutomatico.Latitud, DirectionValues.Input);
                spInsertCajero.AddParameter("@LONGITUD_DC", cajerAutomatico.Longitud, DirectionValues.Input);
                spInsertCajero.AddParameter("@DIRECCION_NV", cajerAutomatico.Direccion, DirectionValues.Input);
                spInsertCajero.AddParameter("@FLAG_MINUSVALIDO", cajerAutomatico.FlagMinusvalido, DirectionValues.Input);
                spInsertCajero.AddParameter("@MONEDA_ID_IN", cajerAutomatico.MonedaId, DirectionValues.Input);
                resultado = spInsertCajero.ExecuteStoredProcedure(ConexionString);
                if (spInsertCajero.ErrorMessage != String.Empty)
                {
                    throw new Exception("Procedimiento Almacenado :[dbo].[SP_CAJERO_AUTOMATICO_INSERT] Descripcion:" + spInsertCajero.ErrorMessage.Trim());
                }
            }
            catch (Exception ex)
            {
                TextLogger.LogError(LogManager.GetCurrentClassLogger(), ex, "Error En el metodo: InsertCajeroAutomatico");
                throw new Exception("Procedimiento Almacenado :[dbo].[SP_CAJERO_AUTOMATICO_INSERT]" + ex);
            }
            return(resultado);
        }
Exemple #25
0
        static void Main(string[] args)
        {
            ILogger logger;

            string loggerType = "text";

            switch (loggerType)
            {
            case "DataBase":
                logger = new DBlogger();
                break;

            default:
                logger = new TextLogger();
                break;
            }
            LogManager manager = new LogManager(logger);

            try
            {
                throw new Exception("Exception throwed");
            }
            catch (Exception e)
            {
                manager.log(e.Message);
                Console.ReadKey();
            }
        }
 public DeviceStatusesWindow()
 {
     InitializeComponent();
     _currentStatuses = new DeviceStatuses();
     _logger = new TextLogger();
     _logger.LogFilePath = AppDomain.CurrentDomain.BaseDirectory + "DeviceStatuses_Log.txt";
 }
        /// <summary>
        /// Entry point.
        /// </summary>
        /// <param name="args">Program arguments.</param>
        public static void Main(string[] args)
        {
            ProximaCore.Init();

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            _textLogger     = new TextLogger(LogsDirectory);
            _consoleManager = new ColorfulConsoleManager(ApplicationName);
            _configManager  = new ConfigManager(ConfigFilename);
            _ficsCore       = new FICSCore(_consoleManager, _configManager, _textLogger);

            _ficsCore.Run();

            while (true)
            {
                var text = Console.ReadLine();
                if (text != null)
                {
                    if (text.Contains("quit"))
                    {
                        break;
                    }

                    _ficsCore.Send(text);
                }
            }
        }
        public void TestTextLogger()
        {
            ILogger logger = new TextLogger();

            (new MyTask(logger)).Run();
            Assert.True(true);
        }
    void OnApplicationFocus(bool focus)
    {
        var service = ObjectAnchorsService.GetService();

        if (focus)
        {
            service.Resume();

            if (GetComponent <ObjectSearch>().IsDiagnosticsCaptureEnabled)
            {
                TextLogger.Log("Start capture diagnostics.");

                service.StartDiagnosticsSession();
            }
        }
        else
        {
            // Pause could block the UI for a very short time, application can put it
            // into a coroutine or background task.
            service.Pause();

            // This method can run asynchronously if the Unity app supports background running.
            // Here we wait until the diagnostics data has been fully committed to the storage since this app
            // doesn't support background running.
            service.StopDiagnosticsSessionAsync().Wait();
        }
    }
Exemple #30
0
        internal ITransaction GetTransactionRepository()
        {
            ITransaction result = null;

            switch (_config.LoggerType)
            {
            case LoggingTypeModel.LogOutputType.TextFile:
                result = new TextLogger
                {
                    LogOutputFileLocation = _config.Text.FileInformation.LogFileLocation,
                    LogOutputFileName     = _config.Text.FileInformation.LogFileName
                };
                break;

            case LoggingTypeModel.LogOutputType.SQL:
                result = new SqlLogger();
                break;

            case LoggingTypeModel.LogOutputType.SQLite:
                result = new SqliteLogger();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
            return(result);
        }
Exemple #31
0
        static void Execute(string solution, string config, bool log = false)
        {
            var fileSystem       = new FileSystem();
            var collectionLogger = new CollectionLogger();

            try
            {
                var launcher = new Launcher(fileSystem, collectionLogger);
                launcher.Launch(solution, config);

                if (log)
                {
                    var textLogger = new TextLogger(fileSystem);
                    textLogger.WriteMany(collectionLogger.Records);
                    Console.WriteLine($"Log file: {textLogger.InitializedFilePath}");
                }
            }
            catch (Exception ex)
            {
                if (collectionLogger.Records.Count == 0 || collectionLogger.Records[collectionLogger.Records.Count - 1].Severity != MessageSeverity.Error)
                {
                    collectionLogger.Write(new ErrorLogRecord("Error occurred.", ex));
                }

                var textLogger = new TextLogger(fileSystem);
                textLogger.WriteMany(collectionLogger.Records);
                Console.WriteLine($"Error occurred: {ex.Message}, more details in log file: {textLogger.InitializedFilePath}");
            }
        }
Exemple #32
0
        public override Response Execute()
        {
            // If we're already initialized (Test path)
            if (this.postInstallService != null)
            {
                return(this.ExecutePdb());
            }

            var logger              = new TextLogger();
            var connectionFactory   = new HelperConnectionFactory(this.Helper);
            var agentRepository     = new AgentRepository(connectionFactory);
            var agentManager        = this.Helper.GetServicesManager().CreateProxy <IAgentManager>(ExecutionIdentity.System);
            var agentManagerService = new AgentManagerService(agentManager, agentRepository, logger);

            var textLogger = new TextLogger();
            var resourceServerRepository = new ResourceServerRepository(connectionFactory);
            var refreshServerService     = new RefreshServerService(textLogger, resourceServerRepository);
            var serverRepository         = new ServerRepository(connectionFactory);
            var configurationRepository  = new ConfigurationRepository(connectionFactory);

            this.postInstallService = new PostInstallService(agentManagerService, refreshServerService, serverRepository, configurationRepository, logger);

            var response = this.ExecutePdb();

            agentManager?.Dispose();
            return(response);
        }
 private void Send(object email)
 {
     try
     {
         SmtpClient smtpClient = new SmtpClient(SmtpServer);
         smtpClient.UseDefaultCredentials = false;
         smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
         smtpClient.Credentials           = new NetworkCredential(Accounts, Password);
         SmtpClient  smtpClient2 = smtpClient;
         MailMessage mailMessage = new MailMessage(SmtpSenderEmail, email.ToString(), Subject, Content);
         mailMessage.IsBodyHtml   = true;
         mailMessage.BodyEncoding = Encoding.GetEncoding("gb2312");
         MailMessage mailMessage2 = mailMessage;
         if (Port != 25)
         {
             smtpClient2.EnableSsl = true;
         }
         smtpClient2.Send(mailMessage2);
         mailMessage2.Dispose();
     }
     catch (Exception ex)
     {
         TextLogger.Write(ex.ToString());
     }
 }
		public void LogError()
		{
			using (var logger = new TextLogger())
			{
				Logger.Error(new TestError(""));
				Assert.IsTrue(logger.Log.Contains(typeof(TestError).ToString()), logger.Log);
			}
		}
		public void LogWarning()
		{
			using (var logger = new TextLogger())
			{
				Logger.Warning("Warning");
				Logger.Warning(new WarningException(""));
				Assert.IsTrue(logger.Log.EndsWith(typeof(WarningException).ToString()), logger.Log);
			}
		}
Exemple #36
0
 public ModuleDOMonitor()
 {
     InitializeComponent();
     _currentStatus = new DeviceDOModule();
     _needToForceCoil = false;
     _coilState = false;
     _coilAddress = 0;
     _logger = new TextLogger();
     _logger.LogFilePath = AppDomain.CurrentDomain.BaseDirectory + "TU_ModuleMonitor_LOG.txt";
 }
		public void LogInfo()
		{
			using (var logger = new TextLogger())
			{
				bool newLogMessageArrived = false;
				logger.NewLogMessage += () => newLogMessageArrived = true;
				Assert.IsFalse(newLogMessageArrived);
				Logger.Info("Message");
				Assert.IsTrue(newLogMessageArrived);
				Assert.IsTrue(logger.Log.EndsWith("Message"), logger.Log);
			}
		}
Exemple #38
0
        public Computer(NesFile file, TextLogger logger)
        {
            if (file.Version != 0)
            {
                throw new System.Exception(string.Format("Version {0} not implemented", file.Version));
            }

            if(file.BatteryRAM)
            {
                throw new System.Exception("Battery backed RAM not implemented");
            }

            if (file.HasTrainer)
            {
                throw new System.Exception("Trainer not implemented");
            }

            switch (file.Mapper)
            {
                case 0x00: // NROM

                    //CPU $6000 -$7FFF: Family Basic only: PRG RAM, mirrored as necessary to fill entire 8 KiB window, write protectable with an external switch
                    //CPU $8000 -$BFFF: First 16 KB of ROM.
                    //CPU $C000 -$FFFF: Last 16 KB of ROM(NROM - 256) or mirror of $8000 -$BFFF(NROM - 128).

                    break;

                default:
                    throw new System.Exception(string.Format("Mapper {0} not implemented", file.Mapper));
            }

            if (file.VSUnisystem)
            {
                throw new System.Exception("VSUnisystem not implemented");
            }

            if (file.PlayChoice10)
            {
                throw new System.Exception("PlayChoice10 not implemented");
            }

            PpuMap = new PpuMap(new Ram(0x2000), new Rom(file.chr_rom), file.VRAMLayout);

            Ppu = new Ppu(PpuMap);
            Ppu.Logger = logger;

            CpuMap = new CpuMap(new Ram(0x0800), new Rom(file.prg_rom), Ppu);

            Cpu = new Cpu(CpuMap);
            Cpu.Logger = logger;
        }
        static void Main(string[] args)
        {
            ILogger mylogger = new TextLogger();

            int i = 15;
            int d = 0;

            try
            {
                int rs = i / d;
            }
            catch (Exception ex)
            {
                mylogger.Error(ex);
            }
        }
        public void Test2()
        {
            var now = new DateTime(2015, 2, 1);
            StreamTextWriterFactory writerFactory = new StreamTextWriterFactory(new DayLogPathFactory());
            TextLogger logger = new TextLogger(writerFactory, new LogDescriptor());
            writerFactory.NowGetter = () => now;
            logger.Write(new LogItem()
            {
                Time = now,
                Message = "测试内容。",
                Type = LogType.Info
            });
            System.Threading.Thread.Sleep(1001);

            var path = GA.FullPath(LogFolder, "2015年02月", "01.log");
            Assert.Equal(now.ToString("HH:mm:ss.ffff") + " [消息] 测试内容。\r\n", GA.IO.ShareReadAllText(path, Encoding.UTF8));
        }