Inheritance: ICloneable
Example #1
0
        public override string Log(EL.Error error)
        {
            CheckTableExists();

            string errorXml = EL.ErrorXml.EncodeString(error);
            string id       = Guid.NewGuid().ToString();

            ErrorRecord errorToStore = new ErrorRecord
            {
                ErrorId     = id,
                Application = this.ApplicationName,
                Host        = error.HostName,
                Type        = error.Type,
                Source      = error.Source,
                Message     = error.Message,
                User        = error.User,
                StatusCode  = error.StatusCode,
                TimeUtc     = error.Time.ToUniversalTime().ToString("s"),
                AllXml      = errorXml,
            };

            string   errorJson     = JsonConvert.SerializeObject(errorToStore);
            Document errorDocument = Document.FromJson(errorJson);

            AmazonDynamoDBClient client = new AmazonDynamoDBClient();
            Table errorTable            = Table.LoadTable(client, s_TableName);

            errorTable.PutItem(errorDocument);

            return(id);
        }
        private SendCompletedEventHandler GetOnSendCompleted(MailMessage message, SendCompletedEventHandler sendCompleted)
        {
            SendCompletedEventHandler handler = (sender, e) =>
            {
                var retryUserState = (RetryUserState)e.UserState;
                var countDown = retryUserState.CountDown;
                if (e.Error != null && --countDown > 0)
                {
                    Thread.Sleep(3000);
                    retryUserState.CountDown = countDown;
                    _decorated.Deliver(message, null, retryUserState);
                }
                else if (sendCompleted != null)
                {
                    if (e.Error != null)
                    {
                        var error = new Error(e.Error);
                        var log = ErrorLog.GetDefault(HttpContext.Current);
                        log.Log(error);
                    }

                    sendCompleted(sender, new AsyncCompletedEventArgs(e.Error, e.Cancelled, retryUserState.UserState));
                }
            };
            return handler;
        }
Example #3
0
        public static Error MapToError(this ErrorDocument errorDocument)
        {
            Log.Trace("MapToError(errorDocument)");

            var error = new Error(errorDocument.Exception)
            {
                ApplicationName = errorDocument.ApplicationName,
                Detail = errorDocument.Detail,
                HostName = errorDocument.HostName,
                Message = errorDocument.Message,
                Source = errorDocument.Source,
                StatusCode = errorDocument.StatusCode,
                Time = errorDocument.Time,
                Type = errorDocument.Type,
                User = errorDocument.User,
                WebHostHtmlMessage = errorDocument.WebHostHtmlMessage
            };

            errorDocument.Cookies.AddToNameValueCollection(error.Cookies);
            errorDocument.Form.AddToNameValueCollection(error.Form);
            errorDocument.QueryString.AddToNameValueCollection(error.QueryString);
            errorDocument.ServerVariables.AddToNameValueCollection(error.ServerVariables);

            return error;
        }
Example #4
0
 public override string Log(Error error)
 {
     var result = base.Log(error);
     #pragma warning disable 4014
     this._client.Log(new ErrorFromElmah(error,this.ApplicationName));
     #pragma warning restore 4014
     return result;
 }
Example #5
0
        public override string Log(Elmah.Error error)
        {
            var r = new XmlDocument();
            var e = r.CreateElement("error");

            e.SetAttribute("application", error.ApplicationName);
            e.SetAttribute("host", error.HostName);
            e.SetAttribute("type", error.Type);
            e.SetAttribute("message", error.Message);
            e.SetAttribute("source", error.Source);
            e.SetAttribute("detail", error.Detail);
            e.SetAttribute("time", error.Time.ToString("yyyy-MM-ddThh:mm:ss.fffffff"));
            r.AppendChild(e);
            r.SelectSingleNode("descendant::error").AppendChild(r.CreateElement("serverVariables"));
            var re = r.SelectSingleNode("descendant::serverVariables");

            foreach (var sv in error.ServerVariables.AllKeys)
            {
                XmlElement rei = r.CreateElement("item");
                rei.SetAttribute("name", sv);
                XmlElement rev = r.CreateElement("value");
                rev.SetAttribute("string", error.ServerVariables.Get(sv));
                rei.AppendChild(rev);
                re.AppendChild(rei);
            }
            r.SelectSingleNode("descendant::error").AppendChild(r.CreateElement("cookies"));
            var rc = r.SelectSingleNode("descendant::cookies");

            foreach (var sv in error.Cookies.AllKeys)
            {
                XmlElement rci = r.CreateElement("item");
                rci.SetAttribute("name", sv);
                XmlElement rcv = r.CreateElement("value");
                rcv.SetAttribute("string", error.Cookies.Get(sv));
                rci.AppendChild(rcv);
                rc.AppendChild(rci);
            }
            var c = new ErrorLogContext();

            c.ErrorLog1.Add(new ErrorLog1()
            {
                ErrorId     = Guid.NewGuid(),
                Application = this.ApplicationName,
                Message     = error.Message,
                StatusCode  = error.StatusCode,
                TimeUtc     = error.Time,
                Type        = error.Type,
                User        = error.User,
                Host        = error.HostName,
                Source      = error.Source,
                AllXml      = r.OuterXml
            });

            c.SaveChanges();
            return("successful");
        }
Example #6
0
        public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
        {
            CheckTableExists();

            if (pageIndex < 0)
            {
                throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
            }

            if (pageSize < 0)
            {
                throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
            }

            int max = pageSize * (pageIndex + 1);

            // http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetQuerying.html
            AmazonDynamoDBClient client = new AmazonDynamoDBClient();
            Dictionary <string, AttributeValue> lastKeyEvaluated = null;
            List <EL.ErrorLogEntry>             list             = new List <EL.ErrorLogEntry>(max);

            // there is a max of 1MB of data returned per read operation, so you have to do repeated reads until you reach the end
            do
            {
                Amazon.DynamoDBv2.Model.QueryRequest request = new Amazon.DynamoDBv2.Model.QueryRequest(s_TableName);
                request.KeyConditionExpression    = "Application = :v_Application";
                request.ExpressionAttributeValues = new Dictionary <string, AttributeValue> {
                    { ":v_Application", new AttributeValue(this.ApplicationName) }
                };
                request.IndexName        = "Application-TimeUtc-index";
                request.ScanIndexForward = false;
                request.Limit            = max;
                request.Select           = Select.ALL_PROJECTED_ATTRIBUTES;
                if (lastKeyEvaluated != null)
                {
                    request.ExclusiveStartKey = lastKeyEvaluated;
                }

                QueryResponse response = client.Query(request);
                foreach (Dictionary <string, AttributeValue> item in response.Items)
                {
                    string   errorXml = item["AllXml"].S;
                    string   errorId  = item["ErrorId"].S;
                    EL.Error error    = EL.ErrorXml.DecodeString(errorXml);
                    list.Add(new EL.ErrorLogEntry(this, errorId, error));
                }
                lastKeyEvaluated = response.LastEvaluatedKey;
            } while (lastKeyEvaluated != null && lastKeyEvaluated.Count > 0);

            int numToSkip = (pageIndex - 1) * pageSize;

            list = list.Skip(numToSkip).ToList();
            list.ForEach(err => errorEntryList.Add(err));
            return(errorEntryList.Count);
        }
        public override string Log(Error error)
        {
            if (error != null)
            {
                log.Error(error.Message, error.Exception);
            } else
            {
                log.Error("The error supplied by ELMAH was null");
            }

            return base.Log(error);
        }
Example #8
0
        public void LogToElmah(System.Exception ex)
        {
            /*if (HttpContext.Current != null && HttpContext.Current.ApplicationInstance != null)
             * {
             *  //TODO: Existe un problema a pesar que HttpContext.Current, el HttpContext.Current.ApplicationInstance  es nulo
             *  //HttpContext.Current.ApplicationInstance
             *  ErrorSignal.FromCurrentContext().Raise(ex);
             * }
             * else
             * {
             *  //TODO: JSA, REVISAR COMO APLICAR ELMAH EN CONSOLA, OPCION 1 NO REGISTRA SEGUN EL CORREO PERMITE ENVIAR CORREOS, LA OPCION 2 REGISTRA EN LA BASE DE DATOS
             *  //INVESTIGAR
             *  //http://stackoverflow.com/questions/841451/using-elmah-in-a-console-application
             *
             *  //OPCION 1
             *  //if (httpApplication == null) InitNoContext();
             *  //ErrorSignal.Get(httpApplication).Raise(ex);
             *
             *  //OPCION 2
             *  ErrorLog errorLog = ErrorLog.GetDefault(null);
             *  //TODO: Configurar el nombre de la aplicacion
             *  errorLog.ApplicationName = "Farmaline"; // ErrorHandling.Application;
             *  var error = new Elmah.Error(ex);
             *  var app = ServiceLocator.Current.GetInstance<IApplication>();
             *  error.User = app?.GetCurrentUser()?.Cuenta;
             *  errorLog.Log(error);
             * }*/

            ErrorLog errorLog = ErrorLog.GetDefault(null);

            //TODO: Configurar el nombre de la aplicacion
            errorLog.ApplicationName = "Farmaline"; // ErrorHandling.Application;
            var     error   = new Elmah.Error(ex);
            var     app     = ServiceLocator.Current.GetInstance <IApplication>();
            Usuario usuario = null;

            try
            {
                usuario = app?.GetCurrentUser();
            }
            catch (Exception e)
            {
            }

            error.User = usuario?.Cuenta;
            errorLog.Log(error);
        }
Example #9
0
        /// <summary>
        /// Writes the error to the EventLog.
        /// </summary>
        protected virtual void ReportError(Elmah.Error error)
        {
            // Compose an error message.
            StringBuilder sb = new StringBuilder();

            sb.Append(error.Message);
            sb.AppendLine();
            sb.AppendLine();
            sb.Append("Date and Time: " + error.Time.ToString("dd.MM.yyyy HH.mm.ss"));
            sb.AppendLine();
            sb.Append("Host Name: " + error.HostName);
            sb.AppendLine();
            sb.Append("Error Type: " + error.Type);
            sb.AppendLine();
            sb.Append("Error Source: " + error.Source);
            sb.AppendLine();
            sb.Append("Error Status Code: " + error.StatusCode.ToString());
            sb.AppendLine();
            sb.Append("Error Request Url: " + HttpContext.Current.Request.Url.AbsoluteUri);
            sb.AppendLine();
            sb.AppendLine();
            sb.Append("Error Details:");
            sb.AppendLine();
            sb.Append(error.Detail);
            sb.AppendLine();

            string messageString = sb.ToString();

            if (messageString.Length > 32765)
            {
                // Max limit of characters that EventLog allows for an event is 32766.
                messageString = messageString.Substring(0, 32765);
            }

            // Write the error entry to the event log.
            try
            {
                EventLog.WriteEntry(eventLogSource, messageString, EventLogEntryType.Error, error.StatusCode);
            }
            catch
            {
                // Nothing to do if it is not possible to write an error message to the EventLog.
                // Most likely an application hasn't rights to write to the EventLog.
                // Or maybe eventLogSource is not valid.
            }
        }
Example #10
0
        private void ElmahSensitiveHandle(ExceptionFilterEventArgs args, HttpContext context)
        {
            var newError = new Elmah.Error(args.Exception, (HttpContext)args.Context);

            foreach
            (var key in context.Request.Form.OfType <String>().Where
             (
                 k => sensitiveKeys.Any(sk => k.IndexOf(sk, StringComparison.OrdinalIgnoreCase) >= 0)
             )
            )
            {
                newError.Form.Set(key, "*******************");
            }

            Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(newError);
            args.Dismiss();
        }
Example #11
0
        private void ErrorListToErrorLogEntryList(ErrorList list, IList errorEntryList)
        {
            foreach (var item in list)
            {
                var error = new Elmah.Error()
                {
                    ApplicationName = item.Application,
                    HostName        = item.Host,
                    Type            = item.Type,
                    Message         = item.Message,
                    Source          = item.Source,
                    User            = item.User,
                    Time            = item.UtcTime.ToLocalTime(),
                    StatusCode      = item.StatusCode,
                };

                errorEntryList.Add(new ErrorLogEntry(this, item.Id.ToString(), error));
            }
        }
Example #12
0
        /// <summary>
        /// Reports the exception.
        /// </summary>
        protected virtual void OnError(Exception e, HttpContext context)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            // Fire an event to check if listeners want to filter out reporting of the uncaught exception.
            Elmah.ExceptionFilterEventArgs args = new Elmah.ExceptionFilterEventArgs(e, context);
            OnFiltering(args);

            if (args.Dismissed)
            {
                return;
            }

            // Get the last error and then write it to the EventLog.
            Elmah.Error error = new Elmah.Error(e, context);
            ReportError(error);
        }
        public static Error ToError(this ErrorRecord errorRecord)
        {
            var error = new Error()
            {
                ApplicationName = errorRecord.ApplicationName,
                Detail = errorRecord.Detail,
                HostName = errorRecord.HostName,
                Message = errorRecord.Message,
                Source = errorRecord.Source,
                StatusCode = errorRecord.StatusCode,
                Type = errorRecord.Type,
                Time = errorRecord.WhenUtc,
                User = errorRecord.User,
                WebHostHtmlMessage = errorRecord.WebHostHtmlMessage
            };
            
            error.Cookies.AddKeyValueCollection(errorRecord.Cookies);
            error.Form.AddKeyValueCollection(errorRecord.Form);
            error.QueryString.AddKeyValueCollection(errorRecord.QueryString);
            error.ServerVariables.AddKeyValueCollection(errorRecord.ServerVariables);

            return error;
        }
Example #14
0
        public override EL.ErrorLogEntry GetError(string id)
        {
            CheckTableExists();

            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id");
            }
            Guid errorGuid;

            if (!Guid.TryParse(id, out errorGuid))
            {
                throw new ArgumentException(string.Format("'{0}' is not a Guid", id), "id");
            }

            AmazonDynamoDBClient client = new AmazonDynamoDBClient();
            Table    errorTable         = Table.LoadTable(client, s_TableName);
            Document errorDoc           = errorTable.GetItem(new Primitive(this.ApplicationName), new Primitive(id));
            string   errorXml           = errorDoc["AllXml"].AsString();

            EL.Error error = EL.ErrorXml.DecodeString(errorXml);
            return(new EL.ErrorLogEntry(this, id, error));
        }
Example #15
0
        /// <summary>
        /// Logs an error to the database.
        /// </summary>
        /// <remarks>
        /// Use the stored procedure called by this implementation to set a
        /// policy on how long errors are kept in the log. The default
        /// implementation stores all errors for an indefinite time.
        /// </remarks>
        public override string Log(Elmah.Error error)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }

            var errorXml = ErrorXml.EncodeString(error);
            var id       = Guid.NewGuid();

            id = Error.LogError(
                id,
                ApplicationName,
                error.HostName,
                error.Type,
                error.Source,
                error.Message,
                error.User,
                error.StatusCode,
                error.Time,
                errorXml);

            return(id.ToString());
        }
Example #16
0
        /// <summary>
        /// Formats the error type of an <see cref="Error"/> object in a 
        /// short and human-readable form.
        /// </summary>
        public static string HumaneExceptionErrorType(Error error)
        {
            if (error == null)
                throw new System.ArgumentNullException("error");

            return HumaneExceptionErrorType(error.Type);
        }
 public void GivenAnELMAHError()
 {
     _givenError = Random.ElmahError;
 }
Example #18
0
        /// <summary>
        /// Logs an error to the application memory.
        /// </summary>
        /// <remarks>
        /// If the log is full then the oldest error entry is removed.
        /// </remarks>
        public override string Log(Error error)
        {
            if (error == null)
                throw new ArgumentNullException("error");

            //
            // Make a copy of the error to log since the source is mutable.
            // Assign a new GUID and create an entry for the error.
            //

            error = (Error)((ICloneable)error).Clone();
            error.ApplicationName = this.ApplicationName;
            Guid newId = Guid.NewGuid();
            ErrorLogEntry entry = new ErrorLogEntry(this, newId.ToString(), error);

            Lock.AcquireWriterLock(Timeout.Infinite);

            try
            {
                if (_entries == null)
                    _entries = new EntryCollection(_size);

                _entries.Add(entry);
            }
            finally
            {
                Lock.ReleaseWriterLock();
            }

            return newId.ToString();
        }
        private void ErrorListToErrorLogEntryList(ErrorList list, IList errorEntryList)
        {
            foreach (var item in list)
            {
                var error = new Elmah.Error()
                {
                    ApplicationName = item.Application,
                    HostName = item.Host,
                    Type = item.Type,
                    Message = item.Message,
                    Source = item.Source,
                    User = item.User,
                    Time = item.UtcTime.ToLocalTime(),
                    StatusCode = item.StatusCode,
                };

                errorEntryList.Add(new ErrorLogEntry(this, item.Id.ToString(), error));
            }
        }