Exemple #1
0
        /// <summary>
        /// Handles the Click event of the cmdChangePassword control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void CmdChangePasswordClick(object sender, EventArgs e)
        {
            if (!cvPasswords.IsValid)
            {
                return;
            }

            GetMembershipData(UserId);

            if (MembershipData == null)
            {
                return;
            }

            try
            {
                MembershipData.ChangePassword(MembershipData.ResetPassword(), NewPassword.Text);
                ActionMessage.ShowSuccessMessage(GetLocalResourceObject("PasswordChangeSuccess").ToString());
                GetMembershipData(UserId);
                DataBind();
            }
            catch (Exception ex)
            {
                if (Log.IsErrorEnabled)
                {
                    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        MDC.Set("user", HttpContext.Current.User.Identity.Name);
                    }

                    Log.Error(LoggingManager.GetErrorMessageResource("PasswordChangeError"), ex);
                }
                ActionMessage.ShowErrorMessage(LoggingManager.GetErrorMessageResource("PasswordChangeError"));
            }
        }
Exemple #2
0
 public void RegisterEventLogError(Exception exception, string applicationName, string machineName, string methodName)
 {
     MDC.Set("Application", applicationName);
     MDC.Set("Machine", machineName);
     MDC.Set("Method", methodName);
     this.log.Error(this.GetMessageLog(exception), exception);
 }
Exemple #3
0
        /// <summary>
        /// Inserts a fatal message
        /// </summary>
        /// <param name="message">Log message</param>
        /// <param name="exception">Exception instance</param>
        public void Fatal(string message, Exception exception = null)
        {
            if (!this.logInstance.IsFatalEnabled)
            {
                return;
            }

            ThreadContext.Properties["AppId"] = SystemSettings.ApplicationId;
            if (!HttpContext.Current.User.IsNull() &&
                HttpContext.Current.User.Identity.IsAuthenticated)
            {
                MDC.Set("user", HttpContext.Current.User.Identity.Name);
            }

            MDC.Set("ipaddress", WebHelper.GetUserHostAddress());
            MDC.Set("pageurl", WebHelper.GetThisPageUrl(true));
            MDC.Set("referrerurl", WebHelper.GetUrlReferrer());

            if (exception.IsNull())
            {
                this.logInstance.Fatal(message);
            }
            else
            {
                this.logInstance.Fatal(message, exception);
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            int totalThreads        = 50;
            TaskCreationOptions tco = TaskCreationOptions.None;
            Task task = null;

            logger.Info("Enter Main");

            Task[] allTasks = new Task[totalThreads];
            for (int i = 0; i < totalThreads; i++)
            {
                int ii = i;
                task = Task.Factory.StartNew(() =>
                {
                    Logger innerLogger = LogManager.GetLogger(ii.ToString());
                    MDC.Set("id", "_" + ii.ToString() + "_");
                    innerLogger.Info("Enter delegate.  i = {0}", ii);
                    innerLogger.Info("Hello! from delegate.  i = {0}", ii);
                    innerLogger.Info("Exit delegate.  i = {0}", ii);
                    MDC.Remove("id");
                });

                allTasks[i] = task;
            }

            logger.Info("Wait on tasks");

            Task.WaitAll(allTasks);

            logger.Info("Tasks finished");

            logger.Info("Exit Main");
        }
Exemple #5
0
        /// <summary>
        /// Handles the Click event of the SaveCustomizeSettings control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void SaveCustomSettings_Click(object sender, EventArgs e)
        {
            WebProfile.Current.IssuesPageSize            = Convert.ToInt32(IssueListItems.SelectedValue);
            WebProfile.Current.PreferredLocale           = ddlPreferredLocale.SelectedValue;
            WebProfile.Current.ReceiveEmailNotifications = AllowNotifications.Checked;

            try
            {
                WebProfile.Current.Save();
                Message3.ShowSuccessMessage(GetLocalResourceObject("CustomSettingsSaved").ToString());

                if (Log.IsInfoEnabled)
                {
                    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        MDC.Set("user", HttpContext.Current.User.Identity.Name);
                    }
                    Log.Info("Profile updated");
                }
            }
            catch (Exception ex)
            {
                if (Log.IsErrorEnabled)
                {
                    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        MDC.Set("user", HttpContext.Current.User.Identity.Name);
                    }
                    Log.Error("Profile update error", ex);
                }
                Message3.ShowErrorMessage(GetLocalResourceObject("CustomSettingsUpdateError").ToString());
            }
        }
        protected override void Append(LoggingEvent loggingEvent)
        {
            MDC.Set("StateID", StateManager.currentState.ToString());
            var message = RenderLoggingEvent(loggingEvent);

            switch (loggingEvent.Level.Name)
            {
            case "DEBUG":
            case "INFO":
                Debug.Log(message);
                break;

            case "WARN":
                Debug.LogWarning(message);
                break;

            case "ERROR":
                Debug.LogError(message);
                break;

            default:
                break;
            }
            MDC.Clear();
        }
Exemple #7
0
        public static void LogActivity(ActivityType activityType, string searchCriteria, string message, LogType Type)
        {
            if (System.Web.HttpContext.Current.User != null && System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                MDC.Set("userName", System.Web.HttpContext.Current.User.Identity.Name);
            }
            MDC.Set("activityType", activityType.ToString());
            MDC.Set("searchCriteria", searchCriteria);
            string hostName  = Dns.GetHostName();
            string ipaddress = Dns.GetHostByName(hostName).AddressList[0].ToString();

            MDC.Set("ipAddress", ipaddress);

            switch (Type)
            {
            case LogType.ERROR:
                logger.Error(message);
                break;

            case LogType.FATAL:
                logger.Fatal(message);
                break;

            case LogType.WARN:
                logger.Warn(message);
                break;

            default:
                logger.Info(message);
                break;
            }
        }
Exemple #8
0
 private static void SetMDC(TraceContextDetail result)
 {
     MDC.Set("user", result.AuditId);
     MDC.Set("ApplicationId", result.ApplicationId);
     MDC.Set("StackTrace", result.StackTrace);
     MDC.Set("Computer", result.Computer);
     MDC.Set("ConnectionKey", result.ConnectionKey);
 }
Exemple #9
0
 private static void SetOptionalParametersOnLogger(IPrincipal user, Uri url)
 {
     if (user != null && user.Identity.IsAuthenticated)
     {
         MDC.Set("user", user.Identity.Name);
     }
     MDC.Set("url", url.ToString());
 }
Exemple #10
0
        public void MDCTest2()
        {
            List <Exception> exceptions = new List <Exception>();
            ManualResetEvent mre        = new ManualResetEvent(false);
            int counter   = 500;
            int remaining = counter;

            for (int i = 0; i < counter; ++i)
            {
                ThreadPool.QueueUserWorkItem(
                    s =>
                {
                    try
                    {
                        MDC.Clear();
                        Assert.IsFalse(MDC.Contains("foo"));
                        Assert.AreEqual(string.Empty, MDC.Get("foo"));
                        Assert.IsFalse(MDC.Contains("foo2"));
                        Assert.AreEqual(string.Empty, MDC.Get("foo2"));

                        MDC.Set("foo", "bar");
                        MDC.Set("foo2", "bar2");

                        Assert.IsTrue(MDC.Contains("foo"));
                        Assert.AreEqual("bar", MDC.Get("foo"));

                        MDC.Remove("foo");
                        Assert.IsFalse(MDC.Contains("foo"));
                        Assert.AreEqual(string.Empty, MDC.Get("foo"));

                        Assert.IsTrue(MDC.Contains("foo2"));
                        Assert.AreEqual("bar2", MDC.Get("foo2"));
                    }
                    catch (Exception ex)
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                        }
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            mre.Set();
                        }
                    }
                });
            }

            mre.WaitOne();
            if (exceptions.Count != 0)
            {
                Assert.Fail(exceptions[0].ToString());
            }
        }
Exemple #11
0
 private static void SetOptionalParametersOnLogger(IPrincipal user, Uri url)
 {
     //set user to log4net context, so we can use %X{user} in the appenders
     if ((user != null) && user.Identity.IsAuthenticated)
     {
         MDC.Set("user", user.Identity.Name);
     }
     //set url to log4net context, so we can use %X{url} in the appenders
     MDC.Set("url", url.ToString());
 }
        /// <summary>
        /// Handles the Error event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void Application_Error(Object sender, EventArgs e)
        {
            //set user to log4net context, so we can use %X{user} in the appenders
            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                MDC.Set("user", HttpContext.Current.User.Identity.Name);
            }

            Log.Error("Application Error", Server.GetLastError());
        }
Exemple #13
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            //Add state ID to any
            MDC.Set(STATE_ID, StateManager.currentState.ToString());

            //Remove rich text for file logging
            string logMessage = Regex.Replace(RenderLoggingEvent(loggingEvent), MARKDOWN_REGEX, String.Empty);

            File.AppendAllText(LOG_FILE, logMessage);

            MDC.Clear();
        }
        /// <summary>
        /// Handles the Click event of the cmdClearLog control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        protected void cmdClearLog_Click(object sender, EventArgs e)
        {
            ApplicationLogManager.ClearLog();

            if (System.Web.HttpContext.Current.User != null && System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                MDC.Set("user", System.Web.HttpContext.Current.User.Identity.Name);
            }

            Log.Info("The error log was cleared.");
            BindData();
        }
Exemple #15
0
        private void SetCustomProperties <TRequest>(TRequest request)
        {
            PropertyInfo[] properties = request.GetType().GetProperties();

            foreach (PropertyInfo property in properties)
            {
                if (property.PropertyType == typeof(string) && property.GetValue(request) != null)
                {
                    MDC.Set(property.Name, property.GetValue(request) as String);
                }
            }
        }
Exemple #16
0
        private void SetMdcProperties()
        {
            if (!string.IsNullOrEmpty(ApplicationId))
            {
                MDC.Set(APP_ID, ApplicationId);
            }

            MDC.Set(YEAR, DateTime.Now.ToString("yyyy"));
            MDC.Set(MONTH, DateTime.Now.ToString("MM"));
            MDC.Set(DAY, DateTime.Now.ToString("dd"));
            MDC.Set(HOUR, DateTime.Now.ToString("HH"));
        }
        /// <summary>
        /// Processes the exception by logging and throwing a wrapper exception with non-sensitive data.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <returns>New exception to wrap the thrown one.</returns>
        private static void ProcessException(Exception ex)
        {
            //set user to log4net context, so we can use %X{user} in the appenders
            if (HttpContext.Current != null && HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                MDC.Set("user", HttpContext.Current.User.Identity.Name);
            }

            if (Log.IsErrorEnabled)
            {
                Log.Error("Email Notification Error", ex);
            }
        }
Exemple #18
0
        /// <summary>
        /// Processes the exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <returns></returns>
        public override DataAccessException ProcessException(Exception ex)
        {
            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                MDC.Set("user", HttpContext.Current.User.Identity.Name);
            }

            if (Log.IsErrorEnabled)
            {
                Log.Error(ex.Message, ex);
            }

            return(new DataAccessException("Database Error", ex));
        }
Exemple #19
0
        public static void LogError(string message, string logger, int applicationId, Exception ex, string connectionKey = "")
        {
            try
            {
                MDC.Set("user", GetParamValue("@auditid", message));
                MDC.Set("ApplicationId", Convert.ToString(applicationId));
                MDC.Set("StackTrace", Environment.StackTrace);
                MDC.Set("Computer", SetupConfiguration.UserMachineName);
                MDC.Set("ConnectionKey", connectionKey);

                var log = LogManager.GetLogger(logger);
                log.Error(message, ex);
            }
            catch { }
        }
Exemple #20
0
        public void RegistrarEnBitacora(Usuario usu)
        {
            if (usu.Email != null)
            {
                MDC.Set("usuario", DES.Decrypt(usu.Email, Key, Iv));
            }
            else
            {
                MDC.Set("usuario", "Sistema");
            }

            var digitoVH = bitacoraDAL.GenerarDVH(usu);

            GlobalContext.Properties["dvh"] = digitoVH;
        }
        public GeneradorLog(string usuario, string idIdentificador, string idIdTansaccion, string archivo)
        {
            _loggerManager  = LogManager.GetLogger(Constantes.NombrePagina);
            idIdentificador = Guid.NewGuid().ToString();
            var stackFrames  = new StackTrace().GetFrames();
            var callingframe = stackFrames.ElementAt(1);
            var method       = callingframe.GetMethod().Name;

            usuario = Convert.ToString(HttpContext.Current.Session["Usuario"]);
            MDC.Set("HostName", Environment.MachineName);
            LogicalThreadContext.Properties["Usuario"]         = usuario;
            LogicalThreadContext.Properties["Identificador"]   = idIdentificador;
            LogicalThreadContext.Properties["MethodName"]      = method;
            LogicalThreadContext.Properties["ApplicationName"] = ConfigurationManager.AppSettings["ApplicationName"];
        }
Exemple #22
0
        public void LogInfo(string message)
        {
            //get logger
            ILog logger = LogManager.GetLogger(typeof(BluePumpkin));

            //set user to log4net context, so we can use %X{user} in the appenders
            if (Username != string.Empty)
            {
                MDC.Set("username", Username);
            }

            if (logger.IsInfoEnabled)
            {
                logger.Info(message); //now log error
            }
        }
Exemple #23
0
        public void LogError(string message, System.Exception e)
        {
            //get logger
            ILog logger = LogManager.GetLogger(typeof(Outlook));

            //set user to log4net context, so we can use %X{user} in the appenders
            if (Username != string.Empty)
            {
                MDC.Set("username", Username);
            }

            if (logger.IsErrorEnabled)
            {
                logger.Error(message, e); //now log error
            }
        }
Exemple #24
0
        public MDCSet(IHttpRouteData routeData)
        {
            fullAction = null;
            try {
                ClaimsPrincipal principal = HttpContext.Current.User as ClaimsPrincipal;
                var             userName  = this.getUserName(principal);
                var             userIP    = this.getIP(principal);
                MDC.Set("userName", userName); //usuario que se logea
                MDC.Set("ip", userIP);
                string actionName  = routeData.Values["action"].ToString();
                string controller  = routeData.Values["controller"].ToString();
                string requestType = HttpContext.Current.Request.RequestType;

                fullAction = String.Concat(requestType, "-", controller, "-", actionName);
                MDC.Set("fullAction", fullAction);
            }
            catch (Exception e) {}
        }
Exemple #25
0
        //Write and entry to the log table (for use when an HttpContext is not available...)
        public void createLogEntry(string sessionId, string userIpAddress, string domainName, DateTime occurrenceDtUtc, string methodName, Exception exception, string exceptionMessage)
        {
            //Validate/initialize input parameters...
            if (String.IsNullOrWhiteSpace(sessionId) ||
                String.IsNullOrWhiteSpace(userIpAddress) ||
                String.IsNullOrWhiteSpace(domainName) ||
                null == occurrenceDtUtc ||
                String.IsNullOrWhiteSpace(methodName) ||
                null == exception ||
                String.IsNullOrWhiteSpace(exceptionMessage))
            {
                return;                         //Invalid parameter - return early...
            }

            //Write derived and input values to MDC...
            MDC.Clear();

            MDC.Set("SessionId", sessionId);
            MDC.Set("IPAddress", userIpAddress);
            MDC.Set("Domain", domainName);
            MDC.Set("OccurrenceDateTime", occurrenceDtUtc.ToString());
            MDC.Set("MethodName", methodName);
            MDC.Set("ExceptionType", exception.GetType().ToString());
            MDC.Set("ExceptionMessage", exceptionMessage);

            //Convert parameters to JSON and write to MDC...
            //Source: http://stackoverflow.com/questions/23729477/converting-dictionary-string-string-to-json-string
            if (0 < m_dictParams.Count)
            {
                var    kvs  = m_dictParams.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Join(",", kvp.Value)));
                string json = string.Concat("{", string.Join(",", kvs), "}");

                MDC.Set("Parameters", json);
            }

            //Write to the log...
            string logMessage = "log message";                  //NOTE: Due to MDC usage and AdoNetAppender usage, this message is not logged..

            m_loggerDB.Error(logMessage);

            //Processing complete - return
            return;
        }
                                                    public async Task <IHttpActionResult> SendNotificacion(Correo correo)
                                                    {
                                                        try {
                                                            MDC.Set("extraData", "Inicio de envío de correo:" + new JavaScriptSerializer().Serialize(correo));
                                                            log.Info(new MDCSet(this.ControllerContext.RouteData));
                                                            getCorreoConfig conf   = new getCorreoConfig();
                                                            SendCorreo      send   = new SendCorreo();
                                                            var             result = await send.Send(correo, conf);

                                                            if (!result)
                                                            {
                                                                MDC.Set("extraData", "No se manda correo:" + new JavaScriptSerializer().Serialize(correo));
                                                                log.Warn(new MDCSet(this.ControllerContext.RouteData));
                                                            }

                                                            return(Ok(result));
                                                        }
                                                        catch (Exception e) { log.Error(new MDCSet(this.ControllerContext.RouteData), e);
                                                                              return(InternalServerError(e)); }
                                                    }
Exemple #27
0
        /// <summary>
        /// Handles the Click event of the SaveButton control.
        /// </summary>
        /// <param name="s">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void SaveButton_Click(object s, EventArgs e)
        {
            var membershipUser = UserManager.GetUser(User.Identity.Name);

            membershipUser.Email           = Email.Text;
            WebProfile.Current.FirstName   = FirstName.Text;
            WebProfile.Current.LastName    = LastName.Text;
            WebProfile.Current.DisplayName = FullName.Text;

            try
            {
                WebProfile.Current.Save();
                Membership.UpdateUser(membershipUser);

                Message1.ShowSuccessMessage(GetLocalResourceObject("ProfileSaved").ToString());

                if (Log.IsInfoEnabled)
                {
                    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        MDC.Set("user", HttpContext.Current.User.Identity.Name);
                    }
                    Log.Info("Profile updated");
                }
            }
            catch (Exception ex)
            {
                if (Log.IsErrorEnabled)
                {
                    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        MDC.Set("user", HttpContext.Current.User.Identity.Name);
                    }
                    Log.Error("Profile update error", ex);
                }

                Message1.ShowErrorMessage(GetLocalResourceObject("ProfileUpdateError").ToString());
            }
        }
Exemple #28
0
 protected void Application_BeginRequest(object sender, EventArgs e)
 {
     MDC.Set("addr", Request.UserHostAddress);
 }
Exemple #29
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="key"></param>
 /// <param name="value"></param>
 public void SetContextValue(string key, string value)
 {
     MDC.Set(key, value);
 }
        public void MDCTest2()
        {
            List <Exception> exceptions = new List <Exception>();
            ManualResetEvent mre        = new ManualResetEvent(false);
            int counter   = 100;
            int remaining = counter;

            for (int i = 0; i < counter; ++i)
            {
                ThreadPool.QueueUserWorkItem(
                    s =>
                {
                    try
                    {
                        MDC.Clear();
                        Assert.False(MDC.Contains("foo"));
                        Assert.Equal(string.Empty, MDC.Get("foo"));
                        Assert.False(MDC.Contains("foo2"));
                        Assert.Equal(string.Empty, MDC.Get("foo2"));

                        MDC.Set("foo", "bar");
                        MDC.Set("foo2", "bar2");

                        Assert.True(MDC.Contains("foo"));
                        Assert.Equal("bar", MDC.Get("foo"));

                        MDC.Remove("foo");
                        Assert.False(MDC.Contains("foo"));
                        Assert.Equal(string.Empty, MDC.Get("foo"));

                        Assert.True(MDC.Contains("foo2"));
                        Assert.Equal("bar2", MDC.Get("foo2"));

                        Assert.Null(MDC.GetObject("foo3"));
                    }
                    catch (Exception ex)
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(ex);
                        }
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            mre.Set();
                        }
                    }
                });
            }

            mre.WaitOne();
            StringBuilder exceptionsMessage = new StringBuilder();

            foreach (var ex in exceptions)
            {
                if (exceptionsMessage.Length > 0)
                {
                    exceptionsMessage.Append("\r\n");
                }

                exceptionsMessage.Append(ex.ToString());
            }

            Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
        }