/// <summary>
        /// Reads the Menu.sort file and creates a MenuSortItem containg the information read
        /// </summary>
        /// <param name="path">Path to the Menu.sort file</param>
        /// <returns>A MenuSOrtItem containg the information from the Menu.sort file</returns>
        /// <remarks>
        /// If the alias file do not have a language specified in the name then the
        /// default language specified in the settings will be used
        /// </remarks>
        public object Handle(string path, DatabaseLogger logger)
        {
            string fileName = System.IO.Path.GetFileName(path);
            int splittIndex = fileName.LastIndexOf('.');

            MenuSortItem sort = new MenuSortItem();

            if (splittIndex == 4)
            {
                sort.Language = _defaultLanguage;
            }
            else
            {
                sort.Language = fileName.Substring(5, splittIndex - 5);
            }
            try
            {
                sort.SortString = ReadAll(path);
            }
            catch (System.IO.IOException ex)
            {
                logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Error, Message = "Could not read file " + path });
                _logger.Warn(ex.ToString());
                return null;
            }

            return sort;
        }
        /// <summary>
        /// Reads the metadata part of a px file.
        /// </summary>
        /// <param name="path">The path to the file</param>
        /// <returns>
        /// Return a PCAxis.Paxiom.PXMeta object containing the metadata 
        /// read from path
        /// </returns>
        public object Handle(string path, DatabaseLogger logger)
        {
            try
            {
                PCAxis.Paxiom.IPXModelBuilder builder = new PXFileBuilder();
                builder.SetPath(path);
                builder.BuildForSelection();
                if (builder.Errors.Count > 0)
                {
                    for (int i = 0; i < builder.Errors.Count; i++)
                    {
                        logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Error, Message = "PX file is corrupted " + path + " "  + builder.Errors[i].Code });
                    }
                    return null;
                }
                if (builder.Warnings.Count > 0)
                {
                    for (int i = 0; i < builder.Warnings.Count; i++)
                    {
                        logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Warning, Message = "PX file " + path + " " + builder.Warnings[i].Code });
                    }
                    return null;
                }
                return builder.Model.Meta;
            }
            catch (PCAxis.Paxiom.PXException ex)
            {
                logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Error, Message = ex.ToString() });
            }

            return null;
        }
        /// <summary>
        /// Reads the Alias file and creates a AliasItem containg the information read
        /// </summary>
        /// <param name="path">Path to the Alias file</param>
        /// <returns>A AliasItem containg the information from the Alias file</returns>
        /// <remarks>
        /// If the alias file do not have a language specified in the name then the 
        /// default language specified in the settings will be used
        /// </remarks>
        public object Handle(string path, DatabaseLogger logger)
        {
            string fileName = System.IO.Path.GetFileNameWithoutExtension(path);
            int splittIndex = fileName.IndexOf('_');

            AliasItem alias = new AliasItem();

            if (splittIndex < 0)
            {
                //No underscore in the file name use the default language
                alias.Language = _defaultLanguage;
            }
            else
            {
                alias.Language = fileName.Substring(splittIndex + 1);
            }
            try
            {
                alias.Alias = ReadAll(path);
            }
            catch (System.IO.IOException ex)
            {
                logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Error, Message = "Could not read file " + path });
                _logger.Warn(ex.ToString());
                return null;
            }

            return alias;
        }
Exemple #4
0
 public SkyFireMySqlDatabaseProvider(IWorldDatabaseSettingsProvider settings,
                                     IAuthDatabaseSettingsProvider authSettings,
                                     DatabaseLogger databaseLogger,
                                     ICurrentCoreVersion currentCoreVersion)
 {
     this.currentCoreVersion = currentCoreVersion;
     DataConnection.TurnTraceSwitchOn();
     DataConnection.WriteTraceLine  = databaseLogger.Log;
     DataConnection.DefaultSettings = new MySqlWorldSettings(settings.Settings, authSettings.Settings);
 }
        public TrinityMySqlDatabaseProvider(IConnectionSettingsProvider settings,
                                            DatabaseLogger databaseLogger,
                                            ICurrentCoreVersion currentCoreVersion)
        {
            this.currentCoreVersion = currentCoreVersion;
            string?host = settings.GetSettings().Host;

            DataConnection.TurnTraceSwitchOn();
            DataConnection.WriteTraceLine  = databaseLogger.Log;
            DataConnection.DefaultSettings = new MySqlSettings(settings.GetSettings());
        }
        public override ILogger CreateLogger()
        {
            //连接数据库,代码省略

            //创建数据库日志记录器对象

            ILogger logger = new DatabaseLogger();

            //初始化数据库日志记录器 代码省略

            return(logger);
        }
Exemple #7
0
        protected void Application_Start()
        {
            var logger = new DatabaseLogger(
                ConfigurationManager.ConnectionStrings["LoggerDataContext"].ToString(),
                this.GetType());

            logger.Log("Application_Start");
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Exemple #8
0
        static void Main(string[] args)
        {
            FileLogger fileLogger = new FileLogger();

            fileLogger.Log("Mesaj dosyaya loglandı.");

            DatabaseLogger databaseLogger = new DatabaseLogger();

            databaseLogger.Log("Mesaj veritabanına loglandı.");

            Console.ReadKey();
        }
        /// <summary>
        /// Reads the link file and creates a LinkItem object representing the link
        /// </summary>
        /// <param name="path">The path to the link file</param>
        /// <returns>A LinkItem</returns>
        /// <remarks>
        /// If the link file do not have a language specified in the name then the 
        /// default language specified in the settings will be used
        /// </remarks>
        public object Handle(string path, DatabaseLogger logger)
        {
            string fileName = System.IO.Path.GetFileNameWithoutExtension(path);
            int splittIndex = fileName.IndexOf('_');

            LinkItem link = new LinkItem();
            if (splittIndex < 0)
            {
                //No underscore in the file name use the default language
                link.Language = _defaultLanguage;
            }
            else
            {
                link.Language = fileName.Substring(splittIndex + 1);
            }

            string linkData;
            try
            {
                linkData = ReadAll(path);
            }
            catch (System.IO.IOException ex)
            {
                logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Error, Message = "Could not read file " + path });
                _logger.Warn(ex.ToString());
                return null;
            }

            //Find the second "
            splittIndex = linkData.IndexOf('"', 1);

            //No second " corrupted link file
            if (splittIndex < 0)
            {
                logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Warning, Message = "Corrupt link file " + path });
                return null;
            }

            //Find the real splittIndex 
            splittIndex = linkData.IndexOf(',', splittIndex);

            //No , after the second " corrupted link file
            if (splittIndex < 0)
            {
                logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Warning, Message = "Corrupt link file " + path });
                return null;
            }

            link.Text = TidyString(linkData.Substring(0, splittIndex)).Trim('"');
            link.Location = TidyString(linkData.Substring(splittIndex + 1)).Trim('"');

            return link;
        }
    static void Main(string[] args)
    {
        FileLogger fileLogger = new FileLogger();

        fileLogger.Log("Message to Log in File.");
        WriteLine();
        EmailLogger emailLogger = new EmailLogger();

        emailLogger.Log("Message to Log via Email.");
        WriteLine();
        DatabaseLogger databaseLogger = new DatabaseLogger();

        databaseLogger.Log("Message to Log in DB.");
    }
        // While accessing the loggers, creating an object will be arranged by putting in with Singleton Pattern
        // - Loggerlar'a ulaşırken, Singleton Pattern ile araya girilip nesne üretme işlemi düzenlenecek

        public static DatabaseLogger DatabaseLogManager()
        {
            if (_databaseLogger == null) // Double checked locking, singleton
            {
                lock (_lock)             // thread safe, singleton
                {
                    if (_databaseLogger == null)
                    {
                        _databaseLogger = new DatabaseLogger();
                    }
                }
            }
            return(_databaseLogger);
        }
Exemple #12
0
 public MySqlExecutor(IMySqlWorldConnectionStringProvider worldConnectionString,
                      IDatabaseProvider databaseProvider,
                      IQueryEvaluator queryEvaluator,
                      IEventAggregator eventAggregator,
                      IMainThread mainThread,
                      DatabaseLogger databaseLogger)
 {
     this.worldConnectionString = worldConnectionString;
     this.databaseProvider      = databaseProvider;
     this.queryEvaluator        = queryEvaluator;
     this.eventAggregator       = eventAggregator;
     this.mainThread            = mainThread;
     this.databaseLogger        = databaseLogger;
 }
Exemple #13
0
        public static void Execute()
        {
            var fileLogger = new FileLogger();

            fileLogger.Log("Message to Log in File.");
            Console.WriteLine();
            var emailLogger = new EmailLogger();

            emailLogger.Log("Message to Log via Email.");
            Console.WriteLine();
            var databaseLogger = new DatabaseLogger();

            databaseLogger.Log("Message to Log in DB.");
        }
Exemple #14
0
        static void Main(string[] args)
        {
            IList <ILogger> loggers = new List <ILogger>();

            ILogger consoleLogger  = new ConsoleLogger();
            ILogger databaseLogger = new DatabaseLogger();
            ILogger windowLogger   = new WindowLogger();

            loggers.Add(consoleLogger);
            loggers.Add(databaseLogger);
            loggers.Add(windowLogger);

            Loguear(loggers);
        }
Exemple #15
0
        public void SendEmail(string emailViewPath, List <string> ToEmailAddresses, string emailSubject)
        {
            ILogger _logger = new DatabaseLogger("name=LoggerDataContext", Type.GetType(string.Empty), (Func <DateTime>)(() => DateTime.UtcNow), string.Empty);

            _logger.Log("EmailService-SendEmail");

            var    fromAddress = new MailAddress(ConfigurationManager.AppSettings["UserName"], "Silicus Rewards and Recognition Team");
            string subject     = emailSubject;
            string body        = string.Empty;

            //using ( StreamReader reader = new StreamReader(emailViewPath))
            //{
            //    body = reader.ReadToEnd();
            //}
            body = emailViewPath;
            var smtp = new SmtpClient
            {
                Host           = "smtp.gmail.com",
                Port           = 587,
                EnableSsl      = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials    = new NetworkCredential(ConfigurationManager.AppSettings["UserName"], ConfigurationManager.AppSettings["Password"])
            };

            using (var message = new MailMessage()
            {
                Subject = subject, Body = body
            })
            {
                message.From = fromAddress;

                foreach (string email in ToEmailAddresses)
                {
                    // message.To.Add("*****@*****.**");
                    message.To.Add(email);
                }
                message.IsBodyHtml = true;
                try
                {
                    _logger.Log("EmailService-SendEmail-try");
                    smtp.Send(message);
                }
                catch (Exception ex)
                {
                    _logger.Log("EmailService-SendEmail-" + ex.Message);
                    var errorMessage = ex.Message;
                }
            }
        }
        public void DefaultConstructorShouldLogAllKindOfMessages()
        {
            var logger = new DatabaseLogger(dbHelper.ConnectionString);

            logger.LogMessage("Error Message", LogMessageType.Error);
            logger.LogMessage("Warning Message", LogMessageType.Warning);
            logger.LogMessage("Info Message", LogMessageType.Message);

            var logRecords = dbHelper.GetLogContent();

            Assert.AreEqual(logRecords.Count(), 3);
            Assert.IsTrue(logRecords.Any(r => r.Type == LogMessageType.Error));
            Assert.IsTrue(logRecords.Any(r => r.Type == LogMessageType.Warning));
            Assert.IsTrue(logRecords.Any(r => r.Type == LogMessageType.Message));
        }
Exemple #17
0
        public void LogMessage_MessageTypeMessageAllowed_MethodToSaveInDBCalled()
        {
            // Arrange
            _levelLoggerMock.Setup(x => x.GetAllowedLevels()).Returns(new List <MessageType> {
                MessageType.Message
            });

            // Act
            var consoleLogger = new DatabaseLogger(_levelLoggerMock.Object, _databaseLoggerHelperMock.Object);

            consoleLogger.LogMessage(MessageType.Message, "message");

            //Assert
            _databaseLoggerHelperMock.Verify(x => x.SaveLog(MessageType.Message, "message"), Times.Exactly(1));
        }
        public void WhenSpecifingToOnlyLogMessagesShouldOnlyLogMessages()
        {
            var logger = new DatabaseLogger(dbHelper.ConnectionString, LogMessageType.Message);

            logger.LogMessage("Error Message", LogMessageType.Error);
            logger.LogMessage("Warning Message", LogMessageType.Warning);
            logger.LogMessage("Info Message", LogMessageType.Message);

            var logRecords = dbHelper.GetLogContent();

            Assert.AreEqual(logRecords.Count(), 1);
            Assert.IsFalse(logRecords.Any(r => r.Type == LogMessageType.Error));
            Assert.IsFalse(logRecords.Any(r => r.Type == LogMessageType.Warning));
            Assert.IsTrue(logRecords.Any(r => r.Type == LogMessageType.Message));
        }
        public void WithDatabaseShouldOnlyLogToTheDatabase()
        {
            var db     = new DatabaseLogger(dbHelper.ConnectionString);
            var logger = new ComposedLogger(db);

            logger.LogMessage("This is a test message", LogMessageType.Message);

            var consoleContent = ConsoleHelper.ReadOutput();
            var dbRecords      = dbHelper.GetLogContent();
            var fileContent    = fileHelper.GetLogFileContent();

            Assert.IsFalse(consoleContent.Any());
            Assert.IsTrue(dbRecords.Any());
            Assert.IsFalse(fileContent.Any());
        }
Exemple #20
0
        public void Log_Appear_in_Db()
        {
            if (File.Exists("local.db"))
            {
                File.Delete("local.db");
            }
            string lineToLog = "Test Db logger";
            var    dbLogger  = new DatabaseLogger(ConnectionString, Enums.LogLevel.Error);

            dbLogger.Log(lineToLog);
            var db  = new DbRepository(ConnectionString);
            var row = db.GetFirstLog();

            Assert.NotNull(row);
            Assert.Contains(lineToLog, row.Message);
        }
Exemple #21
0
        static int Main()
        {
            IReport report = new ConsoleLogger();

            StatusMessages.GermanLanguage = true;
            TestBatteryCondition consoleLogger = new TestBatteryCondition(report);

            consoleLogger.CheckBatteryStatus(40, 84, 0.4f);
            consoleLogger.CheckBatteryStatus(-1, 20, 0.3f);

            StatusMessages.GermanLanguage = false;
            report = new DatabaseLogger();
            TestBatteryCondition dbLogger = new TestBatteryCondition(report);

            dbLogger.CheckBatteryStatus(100, -20, 0.1f);
            return(0);
        }
Exemple #22
0
    public static ILogger GetLogger()
    {
        // Here, use any sophisticated logic you like
        // to determine the right logger to instantiate.

        ILogger logger = null;

        if (UseDatabaseLogger)
        {
            logger = new DatabaseLogger();
        }
        else
        {
            logger = new FileLogger();
        }
        return(logger);
    }
Exemple #23
0
 public static Logger createLogger(String args)
 {
     if (args.equalsIgnoreCase("db"))
     {
         Logger logger = new DatabaseLogger();
         return(logger);
     }
     else if (args.equalsIgnoreCase("file"))
     {
         Logger logger = new FileLogger();
         reurn  logger;
     }
     else
     {
         reurn null;
     }
 }
Exemple #24
0
        static void Main(string[] args)
        // точка входа в приложение
        //именно здесь (а именно как можно ближе к точке входа в приложение
        //происходит инстанциация инъекции.

        // очень похоже на стратегию, только в стратегии ты оборачиваешь это все в первичный выбор
        {
            ILogger logger = new DatabaseLogger();//создаем интерфейс типа ILogger - выбрали именно тот,
            //который логирует у нас в файл, а не в базу данных
            //считается, что ты его сюда засовываешь, а не создаешь
            ProductService productService = new ProductService(logger); //пробрасываем его в сервис

            //в сервисе в конструкторе создаем статичный только для чтения переменную интерфейса
            //в конструкторе этого класса мы присваиваем этой переменной переданное значение.
            //поэтому именно этот метод Log вызовется ниже
            productService.Log("Hello World!");
        }
        public void WithAllLoggersShouldLogToAllOutputs()
        {
            var file    = new FileLogger(fileHelper.FileDirectory);
            var db      = new DatabaseLogger(dbHelper.ConnectionString);
            var console = new ConsoleLogger();
            var logger  = new ComposedLogger(file, db, console);

            logger.LogMessage("This is a test message", LogMessageType.Message);

            var consoleContent = ConsoleHelper.ReadOutput();
            var dbRecords      = dbHelper.GetLogContent();
            var fileContent    = fileHelper.GetLogFileContent();

            Assert.IsTrue(consoleContent.Any());
            Assert.IsTrue(dbRecords.Any());
            Assert.IsTrue(fileContent.Any());
        }
        /// <summary>
        /// Creates all the root nodes for each language
        /// </summary>
        /// <param name="path"></param>
        public void BeginBuild(string path, DatabaseLogger logger)
        {
            _logger4Net.InfoFormat("Start building menu for {0}", path);
            _logger = logger;
            //TODO set use Date format
            _rootPath = System.IO.Path.GetDirectoryName(path) + "\\";
            _databaseName = System.IO.Path.GetFileName(path);
            _logger(new DatabaseMessage() { MessageType = DatabaseMessage.BuilderMessageType.Information, Message = "Menu build started " + DateTime.Now.ToString() });
            string folderName = System.IO.Path.GetFileNameWithoutExtension(path);
            foreach (var language in _languages)
            {
                PxMenuItem root = new PxMenuItem(null, System.IO.Path.GetDirectoryName(path), folderName, folderName, folderName, path, "");
                _languageRoots.Add(language, root);
                _currentItems.Add(language, root);
                _links.Add(root, new List<string>());
            }

        }
Exemple #27
0
        public void DatabaseLogger_can_log_to_a_file()
        {
            Assert.Contains(
                "FROM [dbo].[Products]",
                CaptureFileOutput(
                    f =>
            {
                using (var logger = new DatabaseLogger(f))
                {
                    using (var context = new SimpleModelContext())
                    {
                        logger.StartLogging();

                        context.Products.ToArray();
                    }
                }
            }));
        }
Exemple #28
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var exception = Server.GetLastError();
            var _logger   = new DatabaseLogger("name=LoggerDataContext", Type.GetType(string.Empty), (Func <DateTime>)(() => DateTime.UtcNow), string.Empty);

            _logger.Log("Application_error-" + exception);
            var action = "CustomError";

            if (exception is HttpException)
            {
                var httpEx = exception as HttpException;

                switch (httpEx.GetHttpCode())
                {
                case 400:
                    action = "BadRequest";
                    break;

                case 401:
                    action = "Unauthorized";
                    break;

                case 403:
                    action = "Forbidden";
                    break;

                case 404:
                    action = "PageNotFound";
                    break;

                default:
                    action = "CustomError";
                    break;
                }
            }
            else if (exception is AuthenticationException)
            {
                action = "Forbidden";
            }

            Server.ClearError();
            Response.Redirect("/Error/" + action + "");
        }
Exemple #29
0
        /// <summary>
        /// Creates all the root nodes for each language
        /// </summary>
        /// <param name="path"></param>
        public void BeginBuild(string path, DatabaseLogger logger)
        {
            _logger4Net.InfoFormat("Start building menu for {0}", path);
            _logger = logger;
            //TODO set use Date format
            _logger(new DatabaseMessage()
            {
                MessageType = DatabaseMessage.BuilderMessageType.Information, Message = "Menu build started " + DateTime.Now.ToString()
            });
            string folderName = System.IO.Path.GetFileNameWithoutExtension(path);

            foreach (var language in _languages)
            {
                PxMenuItem root = new PxMenuItem(null, System.IO.Path.GetDirectoryName(path), folderName, folderName, folderName, path, "");
                _languageRoots.Add(language, root);
                _currentItems.Add(language, root);
                _links.Add(root, new List <string>());
            }
        }
        public void Log_WithMultipleMessages_ShouldLogMessage()
        {
            var logger = new DatabaseLogger(ConfigurationHelper.DatabaseLoggerConnectionString);

            var message = new Message("This is the message");

            logger.Log(message);

            var message2 = new Message("This is the second message");

            logger.Log(message2);

            var connection = new SQLiteConnection(ConfigurationHelper.DatabaseLoggerConnectionString);

            connection.Open();

            var command = new SQLiteCommand("SELECT * FROM Logger", connection);
            var reader  = command.ExecuteReader();

            var messages = new List <Message>
            {
                message,
                message2
            };

            var index = 0;

            while (reader.Read())
            {
                var logId      = reader["Id"];
                var logDate    = reader["LogDate"];
                var logLevel   = reader["LogLevel"];
                var logMessage = reader["LogMessage"];

                Assert.AreEqual(messages[index].Id.ToString(), logId);
                Assert.AreEqual(messages[index].Date.ToString(), logDate);
                Assert.AreEqual(messages[index].LogLevel.ToString(), logLevel);
                Assert.AreEqual(messages[index].LogMessage, logMessage);
                index++;
            }

            connection.Close();
        }
        public string SendEmail(List <string> ToEmailAddresses, string body, string emailSubject)
        {
            ILogger _logger = new DatabaseLogger("name=LoggerDataContext", Type.GetType(string.Empty), (Func <DateTime>)(() => DateTime.UtcNow), string.Empty);

            _logger.Log("EmailService-SendEmail");

            var smtp = new SmtpClient
            {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Host           = "mail.global.frontbridge.com",
                Port           = 25,
                EnableSsl      = false,
                Timeout        = 600000
            };

            var fromAddress = new MailAddress(ConfigurationManager.AppSettings["MailUserName"], "Silicus Rewards and Recognition Team");

            using (var message = new MailMessage()
            {
                Subject = emailSubject, Body = body
            })
            {
                message.From = fromAddress;

                foreach (string email in ToEmailAddresses)
                {
                    message.Bcc.Add(email);
                }
                message.IsBodyHtml = true;
                try
                {
                    _logger.Log("EmailService-SendEmail-try");
                    smtp.Send(message);
                    return("Success");
                }
                catch (Exception ex)
                {
                    _logger.Log("EmailService-SendEmail-" + ex.Message);
                    return("Error");
                }
            }
        }
Exemple #32
0
        protected override void OnException(ExceptionContext filterContext)
        {
            Exception e      = filterContext.Exception;
            var       logger = new DatabaseLogger();

            filterContext.ExceptionHandled = true;

            if (e is NotificationException)
            {
                logger.Info(filterContext.Exception.Message);

                filterContext.Result = new ViewResult
                {
                    TempData = new TempDataDictionary
                    {
                        { string.Format("MyFramework.notifications.{0}", NotifyType.Error), e.Message }
                    },
                    ViewData = new ViewDataDictionary(filterContext.Result)
                };
            }
            else if (e is SecurityException)
            {
                logger.Error(filterContext.Exception.Message);

                filterContext.Result = new ViewResult()
                {
                    ViewName = "NoAuthorize",
                    ViewData = new ViewDataDictionary(e)
                };
            }
            else
            {
                logger.Error(filterContext.Exception.Message);

                filterContext.Result = new ViewResult()
                {
                    ViewName = "Error",
                    ViewData = new ViewDataDictionary(e)
                };
            }
        }
Exemple #33
0
        /// <summary>
        /// Reads the metadata part of a px file.
        /// </summary>
        /// <param name="path">The path to the file</param>
        /// <returns>
        /// Return a PCAxis.Paxiom.PXMeta object containing the metadata
        /// read from path
        /// </returns>
        public object Handle(string path, DatabaseLogger logger)
        {
            try
            {
                PCAxis.Paxiom.IPXModelBuilder builder = new PXFileBuilder();
                builder.SetPath(path);
                builder.BuildForSelection();
                if (builder.Errors.Count > 0)
                {
                    for (int i = 0; i < builder.Errors.Count; i++)
                    {
                        logger(new DatabaseMessage()
                        {
                            MessageType = DatabaseMessage.BuilderMessageType.Error, Message = "PX file is corrupted " + path + " " + PCAxis.Web.Core.Management.LocalizationManager.GetLocalizedString(builder.Errors[i].Code)
                        });
                    }
                    return(null);
                }
                if (builder.Warnings.Count > 0)
                {
                    for (int i = 0; i < builder.Warnings.Count; i++)
                    {
                        logger(new DatabaseMessage()
                        {
                            MessageType = DatabaseMessage.BuilderMessageType.Warning, Message = "PX file " + path + " " + PCAxis.Web.Core.Management.LocalizationManager.GetLocalizedString(builder.Warnings[i].Code)
                        });
                    }
                    return(null);
                }
                return(builder.Model.Meta);
            }
            catch (PCAxis.Paxiom.PXException ex)
            {
                logger(new DatabaseMessage()
                {
                    MessageType = DatabaseMessage.BuilderMessageType.Error, Message = ex.ToString()
                });
            }

            return(null);
        }
Exemple #34
0
        public static ILog GetLogger(LoggerType loggerType)
        {
            ILog objLogger;

            switch (loggerType)
            {
            case LoggerType.DATABASE:
                objLogger = new DatabaseLogger();
                break;

            case LoggerType.FILE:
                objLogger = new FileLogger();
                break;

            default:
                objLogger = null;
                break;
            }

            return(objLogger);
        }
Exemple #35
0
        public void Dispose_stops_logging()
        {
            using (var context = new SimpleModelContext())
            {
                var output = CaptureConsoleOutput(
                    () =>
                {
                    using (var logger = new DatabaseLogger())
                    {
                        logger.StartLogging();

                        context.Categories.ToArray();
                    }

                    context.Products.ToArray();
                });

                Assert.Contains("FROM [dbo].[Categories]", output);
                Assert.DoesNotContain("FROM [dbo].[Products]", output);
            }
        }
	    protected void Application_Error(object sender, EventArgs e)
	    {
		    System.Diagnostics.Trace.WriteLine("Enter - Application_Error");

		    var logger = new DatabaseLogger(
			    ConfigurationManager.ConnectionStrings["FinderLoggerDataContext"].ToString(),
			    this.GetType());

		    var httpContext = ((MvcApplication) sender).Context;

		    var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
		    var currentController = " ";
		    var currentAction = " ";

		    if (currentRouteData != null)
		    {
			    if (currentRouteData.Values["controller"] != null &&
			        !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
			    {
				    currentController = currentRouteData.Values["controller"].ToString();
			    }

			    if (currentRouteData.Values["action"] != null &&
			        !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
			    {
				    currentAction = currentRouteData.Values["action"].ToString();
			    }
		    }

		    var ex = Server.GetLastError();

		    
            
            if (ex != null)
		    {
                logger.Log(string.Format("Server_Exception - {0}", ex.Message), LogCategory.Error);
                logger.Log(string.Format("Server_Exception - Stack Trace - {0}", ex.StackTrace), LogCategory.Error);
			    System.Diagnostics.Trace.WriteLine(ex);

			    if (ex.InnerException != null)
			    {
                    logger.Log(string.Format("Server_InnerException - {0}", ex.InnerException), LogCategory.Error);
                    logger.Log(string.Format("Server_InnerException - Stack Trace - {0}", ex.StackTrace), LogCategory.Error);
				    System.Diagnostics.Trace.WriteLine(ex.InnerException);
				    System.Diagnostics.Trace.WriteLine(ex.InnerException.Message);
			    }
		    }

		    var controller = new ErrorController();
		    var routeData = new RouteData();
		    var action = "CustomError";
		    var statusCode = 500;

		    if (ex is HttpException)
		    {
			    var httpEx = ex as HttpException;
			    statusCode = httpEx.GetHttpCode();

			    switch (httpEx.GetHttpCode())
			    {
				    case 400:
					    action = "BadRequest";
					    break;

				    case 401:
					    action = "Unauthorized";
					    break;

				    case 403:
					    action = "Forbidden";
					    break;

				    case 404:
					    action = "PageNotFound";
					    break;

				    case 500:
					    action = "CustomError";
					    break;

				    default:
					    action = "CustomError";
					    break;
			    }
		    }
		    else if (ex is AuthenticationException)
		    {
			    action = "Forbidden";
			    statusCode = 403;
		    }

		    httpContext.ClearError();
		    httpContext.Response.Clear();
		    httpContext.Response.StatusCode = statusCode;
		    httpContext.Response.TrySkipIisCustomErrors = true;
		    routeData.Values["controller"] = "Error";
		    routeData.Values["action"] = action;

		    controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
		    ((IController) controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
	    }
 public DatabaseSpider()
 {
     logger = new DatabaseLogger(LogMessage);
 }