예제 #1
0
        public static void StartBackgroundScheduling()
        {
            ILogger _logger = new DatabaseLogger("name=LoggerDataContext", Type.GetType(string.Empty), (Func <DateTime>)(() => DateTime.UtcNow), string.Empty);

            _logger.Log("HangfirConfig-StartBackgroundScheduling");
            try
            {
                _logger.Log("HangfirConfig-StartBackgroundScheduling-try");

                //Adding job for monthly awards
                //RecurringJob.AddOrUpdate<EncourageEventProcessor>("UnLockMonthlyNomination", processor => processor.Process(EventType.UnLockNominations, EventProcess.UnLockEvent, FrequencyCode.MON),  ConfigurationManager.AppSettings["CronExpressionForNominationMailMonthly"]);
                //RecurringJob.AddOrUpdate<EncourageEventProcessor>("LockMonthlyNomination", processor => processor.Process(EventType.LockNomination, EventProcess.LockEvent, FrequencyCode.MON), () => ConfigurationManager.AppSettings["CronExpressionForNominationLockMailMonthly"]);
                //RecurringJob.AddOrUpdate<EncourageEventProcessor>("LockMonthlyReview", processor => processor.Process(EventType.LockReview, EventProcess.LockEvent, FrequencyCode.MON), () => ConfigurationManager.AppSettings["CronExpressionForReviewLockMailMonthly"]);

                //Adding job for yearly awards
                RecurringJob.AddOrUpdate <EncourageEventProcessor>("UnLockYearlyNomination", processor => processor.Process(EventType.UnLockNominations, EventProcess.UnLockEvent, Award.Pinnacle.ToString()), () => ConfigurationManager.AppSettings["NominationMailCronForPinnacle"]);
                RecurringJob.AddOrUpdate <EncourageEventProcessor>("LockYearlyNomination", processor => processor.Process(EventType.LockNomination, EventProcess.LockEvent, Award.Pinnacle.ToString()), () => ConfigurationManager.AppSettings["NominationLockMailCronForPinnacle"]);
                RecurringJob.AddOrUpdate <EncourageEventProcessor>("LockYearlyReview", processor => processor.Process(EventType.LockReview, EventProcess.LockEvent, Award.Pinnacle.ToString()), () => ConfigurationManager.AppSettings["ReviewLockMailCronForPinnacle"]);
                _logger.Log("HangfirConfig-StartBackgroundScheduling-done");
            }
            catch (Exception ex)
            {
                _logger.Log("HangfirConfig-StartBackgroundScheduling-catch-" + ex.Message);
                throw ex;
            }
        }
예제 #2
0
        public async Task ExecuteSql(string query)
        {
            if (string.IsNullOrWhiteSpace(query) || !IsConnected)
            {
                return;
            }

            databaseLogger.Log(query, null, TraceLevel.Info);

            using var writeLock = await DatabaseLock.WriteLock();

            MySqlConnection  conn = new(worldConnectionString.ConnectionString);
            MySqlTransaction transaction;

            try
            {
                conn.Open();
                transaction = await conn.BeginTransactionAsync();
            }
            catch (Exception e)
            {
                throw new IMySqlExecutor.CannotConnectToDatabaseException(e);
            }

            try
            {
                MySqlCommand cmd = new(query, conn, transaction);
                await cmd.ExecuteNonQueryAsync();

                await transaction.CommitAsync();
            }
            catch (MySqlConnector.MySqlException e)
            {
                await transaction.RollbackAsync();

                await conn.CloseAsync();

                throw new IMySqlExecutor.QueryFailedDatabaseException(e.Message, e);
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();

                await conn.CloseAsync();

                throw new IMySqlExecutor.QueryFailedDatabaseException(ex);
            }
            await conn.CloseAsync();

            foreach (var tableName in queryEvaluator.Extract(query).Select(q => q.TableName).Distinct())
            {
                mainThread.Dispatch(() =>
                                    eventAggregator.GetEvent <DatabaseTableChanged>().Publish(tableName));
            }
        }
예제 #3
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;
                }
            }
        }
예제 #4
0
        public void Log_WithValidMessage_ShouldLogMessage()
        {
            var logger = new DatabaseLogger(ConfigurationHelper.DatabaseLoggerConnectionString);

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

            logger.Log(message);

            var connection = new SQLiteConnection(ConfigurationHelper.DatabaseLoggerConnectionString);

            connection.Open();

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

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

                Assert.AreEqual(message.Id.ToString(), logId);
                Assert.AreEqual(message.Date.ToString(), logDate);
                Assert.AreEqual(message.LogLevel.ToString(), logLevel);
                Assert.AreEqual(message.LogMessage, logMessage);
            }

            connection.Close();
        }
예제 #5
0
        public void Log_WithValidMessage_InvalidConnectionString_ShouldThrowAnException()
        {
            var logger  = new DatabaseLogger("Data Source=FakeLoggerDB.db;");
            var message = new Message("This is the message");

            logger.Log(message);
        }
예제 #6
0
            public ILogger CreateLogger()
            {
                DatabaseLogger databaseLogger = new DatabaseLogger();

                databaseLogger.Log();
                return(databaseLogger);
            }
예제 #7
0
        protected void Application_Error(object sender, EventArgs e)
        {
            var     exception = Server.GetLastError();
            ILogger _logger   = new DatabaseLogger("name=LoggerDataContext", Type.GetType(string.Empty), (Func <DateTime>)(() => DateTime.UtcNow), string.Empty);

            _logger.Log("Application_error-" + exception);
            Server.ClearError();
            Response.Redirect("/Home/Error");
        }
예제 #8
0
        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();
        }
예제 #9
0
        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");
                }
            }
        }
예제 #10
0
        public async Task ExecuteSql(string query)
        {
            if (string.IsNullOrEmpty(query) || !IsConnected)
            {
                return;
            }

            databaseLogger.Log(query, null, TraceLevel.Info);

            using var writeLock = await DatabaseLock.WriteLock();

            MySqlConnection  conn = new(connectionString.ConnectionString);
            MySqlTransaction transaction;

            try
            {
                conn.Open();
                transaction = await conn.BeginTransactionAsync();
            }
            catch (Exception e)
            {
                throw new IMySqlExecutor.CannotConnectToDatabaseException(e);
            }

            try
            {
                MySqlCommand cmd = new(query, conn, transaction);
                await cmd.ExecuteNonQueryAsync();

                await transaction.CommitAsync();
            }
            catch (Exception ex)
            {
                await transaction.RollbackAsync();

                await conn.CloseAsync();

                throw new IMySqlExecutor.QueryFailedDatabaseException(ex);
            }
            await conn.CloseAsync();
        }
예제 #11
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);
        }
예제 #12
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();
        }
    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.");
    }
예제 #14
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.");
        }
예제 #15
0
        public ActionResult AddUser(string _username, string _password)
        {
            try
            {
                if (_username == "" || _password == "")
                {
                    return(Json(new ResultJson {
                        Success = false, Message = "Lütfen tüm alanları doldurunuz!"
                    }));
                }

                User user = new User();
                user.UserName = _username;
                user.Password = Crypto.HashPassword(_password);

                var username = diyaPMContext.Users.FirstOrDefault(x => x.UserName == _username);
                if (username != null)
                {
                    return(Json(new ResultJson {
                        Success = false, Message = "Böyle bir kullanıcı zaten mevcut!"
                    }));
                }

                diyaPMContext.Users.Add(user);
                diyaPMContext.SaveChanges();
                return(Json(new ResultJson {
                    Success = true, Message = "Kullanıcı ekleme işlemi tamamlandı.."
                }));
            }
            catch (Exception ex)
            {
                databaseLogger.Log(ex.ToString(), User.Identity.Name);
                return(Json(new ResultJson {
                    Success = false, Message = ex.ToString()
                }));
            }
        }
예제 #16
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);
        }
예제 #17
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 + "");
        }
예제 #18
0
        protected void Application_Start()
        {
            var logger = new DatabaseLogger(
                ConfigurationManager.ConnectionStrings["SilicusLoggerDataContext"].ToString(),
                this.GetType());

            logger.Log("Application_Start");
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AutoMapperConfiguration.Configure();
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
            // For email template caching
            foreach (string templateName in Directory.EnumerateFiles(Path.Combine(HttpRuntime.AppDomainAppPath, "EmailTemplates"), "*.cshtml"))
            {
                var template = System.IO.File.ReadAllText(templateName);
                RazorEngine.Razor.Compile(template, Path.GetFileNameWithoutExtension(templateName));
            }
        }
        public void Database()
        {
            DatabaseLogger databaseLogger = new DatabaseLogger();

            databaseLogger.Log();
        }
예제 #20
0
	    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));
	    }
예제 #21
0
        public void TestLoggingWorking()
        {
            ILogger logger = new DatabaseLogger();

            logger.Log(new MessageStructure("test", "testOrigin", "testFilename", 3));
        }
예제 #22
0
        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));
        }