Collection of utility methods for masking values.
예제 #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Error"/> class
        /// from a given <see cref="Exception"/> instance and
        /// <see cref="HttpContext"/> instance representing the HTTP
        /// context during the exception.
        /// </summary>

        public Error(Exception e, HttpContext context)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            _exception = e;
            Exception baseException = e.GetBaseException();

            //
            // Load the basic information.
            //

            _hostName = Environment.TryGetMachineName(context);
            _typeName = baseException.GetType().FullName;
            _message  = baseException.Message;
            _source   = baseException.Source;
            _detail   = e.ToString();
            _user     = Mask.NullString(Thread.CurrentPrincipal.Identity.Name);
            _time     = DateTime.Now;

            //
            // If this is an HTTP exception, then get the status code
            // and detailed HTML message provided by the host.
            //

            HttpException httpException = e as HttpException;

            if (httpException != null)
            {
                _statusCode         = httpException.GetHttpCode();
                _webHostHtmlMessage = TryGetHtmlErrorMessage(httpException);
            }

            //
            // If the HTTP context is available, then capture the
            // collections that represent the state request as well as
            // the user.
            //

            if (context != null)
            {
                IPrincipal webUser = context.User;
                if (webUser != null &&
                    Mask.NullString(webUser.Identity.Name).Length > 0)
                {
                    _user = webUser.Identity.Name;
                }

                HttpRequest request = context.Request;

                _serverVariables = CopyCollection(request.ServerVariables);

                if (_serverVariables != null)
                {
                    // Hack for issue #140:
                    // http://code.google.com/p/elmah/issues/detail?id=140

                    const string authPasswordKey = "AUTH_PASSWORD";
                    string       authPassword    = _serverVariables[authPasswordKey];
                    if (authPassword != null) // yes, mask empty too!
                    {
                        _serverVariables[authPasswordKey] = "*****";
                    }
                }

                _queryString = CopyCollection(request.QueryString);
                _form        = CopyCollection(request.Form);
                _cookies     = CopyCollection(request.Cookies);
            }
        }
예제 #2
0
 public override string ToString()
 {
     return(Mask.EmptyString(Exception.Message, Exception.GetType().FullName));
 }
예제 #3
0
        /// <summary>
        /// Schedules the error to be e-mailed synchronously.
        /// </summary>

        protected virtual void ReportError(Error error)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }

            //
            // Start by checking if we have a sender and a recipient.
            // These values may be null if someone overrides the
            // implementation of OnInit but does not override the
            // MailSender and MailRecipient properties.
            //

            string sender        = this.MailSender ?? string.Empty;
            string recipient     = this.MailRecipient ?? string.Empty;
            string copyRecipient = this.MailCopyRecipient ?? string.Empty;

            if (recipient.Length == 0)
            {
                return;
            }

            //
            // Create the mail, setting up the sender and recipient and priority.
            //

            MailMessage mail = new MailMessage();

            mail.Priority = this.MailPriority;

            mail.From = new MailAddress(sender);
            mail.To.Add(recipient);

            if (copyRecipient.Length > 0)
            {
                mail.CC.Add(copyRecipient);
            }

            //
            // Format the mail subject.
            //

            string subjectFormat = Mask.EmptyString(this.MailSubjectFormat, "Error ({1}): {0}");

            mail.Subject = string.Format(subjectFormat, error.Message, error.Type).
                           Replace('\r', ' ').Replace('\n', ' ');

            //
            // Format the mail body.
            //

            ErrorTextFormatter formatter = CreateErrorFormatter();

            StringWriter bodyWriter = new StringWriter();

            formatter.Format(bodyWriter, error);
            mail.Body = bodyWriter.ToString();

            switch (formatter.MimeType)
            {
            case "text/html": mail.IsBodyHtml = true; break;

            case "text/plain": mail.IsBodyHtml = false; break;

            default:
            {
                throw new ApplicationException(string.Format(
                                                   "The error mail module does not know how to handle the {1} media type that is created by the {0} formatter.",
                                                   formatter.GetType().FullName, formatter.MimeType));
            }
            }

            MailAttachment     ysodAttachment = null;
            ErrorMailEventArgs args           = new ErrorMailEventArgs(error, mail);

            try
            {
                //
                // If an HTML message was supplied by the web host then attach
                // it to the mail if not explicitly told not to do so.
                //

                if (!NoYsod && error.WebHostHtmlMessage.Length > 0)
                {
                    ysodAttachment = CreateHtmlAttachment("YSOD", error.WebHostHtmlMessage);

                    if (ysodAttachment != null)
                    {
                        mail.Attachments.Add(ysodAttachment);
                    }
                }

                //
                // Send off the mail with some chance to pre- or post-process
                // using event.
                //

                OnMailing(args);
                SendMail(mail);
                OnMailed(args);
            }
            finally
            {
                OnDisposingMail(args);
                mail.Dispose();
            }
        }
예제 #4
0
        /// <summary>
        /// Renders a collection as a table in HTML document body.
        /// </summary>
        /// <remarks>
        /// This method is called by <see cref="RenderCollections"/> to 
        /// format a diagnostic collection from <see cref="Error"/> object.
        /// </remarks>

        protected virtual void RenderCollection(NameValueCollection collection, string caption)
        {
            if (collection == null || collection.Count == 0)
            {
                return;
            }

            HtmlTextWriter writer = this.Writer;

            writer.RenderBeginTag(HtmlTextWriterTag.H1);
            HttpUtility.HtmlEncode(caption, writer);
            writer.RenderEndTag(); // </h1>
            writer.WriteLine();

            //
            // Write a table with each key in the left column
            // and its value in the right column.
            //

            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "5");
            writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0");
            writer.AddAttribute(HtmlTextWriterAttribute.Border, "1");
            writer.AddAttribute(HtmlTextWriterAttribute.Width, "100%");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            //
            // Write the column headings.
            //

            writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            writer.AddAttribute(HtmlTextWriterAttribute.Align, "left");
            writer.RenderBeginTag(HtmlTextWriterTag.Th);
            writer.Write("Name");
            writer.RenderEndTag(); // </th>

            writer.AddAttribute(HtmlTextWriterAttribute.Align, "left");
            writer.RenderBeginTag(HtmlTextWriterTag.Th);
            writer.Write("Value");
            writer.RenderEndTag(); // </th>

            writer.RenderEndTag(); // </tr>

            //
            // Write the main body of the table containing keys
            // and values in a two-column layout.
            //

            foreach (string key in collection.Keys)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Valign, "top");
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                HttpUtility.HtmlEncode(key, writer);
                writer.RenderEndTag(); // </td>
                
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                string value = Mask.NullString(collection[key]);

                if (value.Length != 0)
                {
                    HttpUtility.HtmlEncode(value, writer);
                }
                else
                {
                    writer.Write("&nbsp;");
                }

                writer.RenderEndTag(); // </td>

                writer.RenderEndTag(); // </tr>
            }

            writer.RenderEndTag(); // </table>
            writer.WriteLine();
        }
예제 #5
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (_result != null)
            {
                throw new InvalidOperationException("An asynchronous operation is already pending.");
            }

            HttpRequest         request = context.Request;
            NameValueCollection query   = request.QueryString;

            //
            // Limit the download by some maximum # of records?
            //

            _maxDownloadCount = Math.Max(0, Convert.ToInt32(query["limit"], CultureInfo.InvariantCulture));

            //
            // Determine the desired output format.
            //

            string format = Mask.EmptyString(query["format"], "csv").ToLower(CultureInfo.InvariantCulture);

            switch (format)
            {
            case "csv": _format = new CsvFormat(context); break;

            case "jsonp": _format = new JsonPaddingFormat(context); break;

            case "html-jsonp": _format = new JsonPaddingFormat(context, /* wrapped */ true); break;

            default:
                throw new Exception("Request log format is not supported.");
            }

            Debug.Assert(_format != null);

            //
            // Emit format header, initialize and then fetch results.
            //

            context.Response.BufferOutput = false;
            _format.Header();

            AsyncResult result = _result = new AsyncResult(extraData);

            _log            = ErrorLog.GetDefault(context);
            _pageIndex      = 0;
            _lastBeatTime   = DateTime.Now;
            _context        = context;
            _callback       = cb;
            _errorEntryList = new List <ErrorLogEntry>(_pageSize);

            _log.BeginGetErrors(_pageIndex, _pageSize, _errorEntryList,
                                new AsyncCallback(GetErrorsCallback), null);

            return(result);
        }
        private void RenderErrors(HtmlTextWriter writer)
        {
            Debug.Assert(writer != null);

            //
            // Create a table to display error information in each row.
            //

            Table table = new Table();

            table.ID          = "ErrorLog";
            table.CellSpacing = 0;

            //
            // Create the table row for headings.
            //

            TableRow headRow = new TableRow();

            headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Host", "host-col"));
            headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Code", "code-col"));
            headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Type", "type-col"));
            headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Error", "error-col"));
            headRow.Cells.Add(FormatCell(new TableHeaderCell(), "User", "user-col"));
            headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Date", "date-col"));
            headRow.Cells.Add(FormatCell(new TableHeaderCell(), "Time", "time-col"));

            table.Rows.Add(headRow);

            //
            // Generate a table body row for each error.
            //

            for (int errorIndex = 0; errorIndex < _errorEntryList.Count; errorIndex++)
            {
                ErrorLogEntry errorEntry = (ErrorLogEntry)_errorEntryList[errorIndex];
                Error         error      = errorEntry.Error;

                TableRow bodyRow = new TableRow();
                bodyRow.CssClass = errorIndex % 2 == 0 ? "even-row" : "odd-row";

                //
                // Format host and status code cells.
                //

                bodyRow.Cells.Add(FormatCell(new TableCell(), error.HostName, "host-col"));
                bodyRow.Cells.Add(FormatCell(new TableCell(), error.StatusCode.ToString(), "code-col", Mask.NullString(HttpWorkerRequest.GetStatusDescription(error.StatusCode))));
                bodyRow.Cells.Add(FormatCell(new TableCell(), ErrorDisplay.HumaneExceptionErrorType(error), "type-col", error.Type));

                //
                // Format the message cell, which contains the message
                // text and a details link pointing to the page where
                // all error details can be viewed.
                //

                TableCell messageCell = new TableCell();
                messageCell.CssClass = "error-col";

                Label messageLabel = new Label();
                messageLabel.Text = this.Server.HtmlEncode(error.Message);

                HyperLink detailsLink = new HyperLink();
                detailsLink.NavigateUrl = BasePageName + "/detail?id=" + HttpUtility.UrlEncode(errorEntry.Id);
                detailsLink.Text        = "Details&hellip;";

                messageCell.Controls.Add(messageLabel);
                messageCell.Controls.Add(new LiteralControl(" "));
                messageCell.Controls.Add(detailsLink);

                bodyRow.Cells.Add(messageCell);

                //
                // Format the user, date and time cells.
                //

                bodyRow.Cells.Add(FormatCell(new TableCell(), error.User, "user-col"));
                bodyRow.Cells.Add(FormatCell(new TableCell(), error.Time.ToShortDateString(), "date-col",
                                             error.Time.ToLongDateString()));
                bodyRow.Cells.Add(FormatCell(new TableCell(), error.Time.ToShortTimeString(), "time-col",
                                             error.Time.ToLongTimeString()));

                //
                // Finally, add the row to the table.
                //

                table.Rows.Add(bodyRow);
            }

            table.RenderControl(writer);
        }
        /// <summary>
        /// Schedules the error to be e-mailed synchronously.
        /// </summary>

        protected virtual void ReportError(Error error)
        {
            if (error == null)
            {
                throw new ArgumentNullException("error");
            }

            //
            // Start by checking if we have a sender and a recipient.
            // These values may be null if someone overrides the
            // implementation of OnInit but does not override the
            // MailSender and MailRecipient properties.
            //

            string sender        = Mask.NullString(this.MailSender);
            string recipient     = Mask.NullString(this.MailRecipient);
            string copyRecipient = Mask.NullString(this.MailCopyRecipient);

#if NET_1_0 || NET_1_1
            //
            // The sender can be defaulted in the <system.net> settings in 2.0
            //

            if (sender.Length == 0)
            {
                return;
            }
#endif

            if (recipient.Length == 0)
            {
                return;
            }

            //
            // Create the mail, setting up the sender and recipient and priority.
            //

            MailMessage mail = new MailMessage();
            mail.Priority = this.MailPriority;

#if NET_1_0 || NET_1_1
            mail.From = sender;
            mail.To   = recipient;

            if (copyRecipient.Length > 0)
            {
                mail.Cc = copyRecipient;
            }
#else
            mail.From = new MailAddress(sender);
            mail.To.Add(recipient);

            if (copyRecipient.Length > 0)
            {
                mail.CC.Add(copyRecipient);
            }
#endif
            //
            // Format the mail subject.
            //

            string subjectFormat = Mask.EmptyString(this.MailSubjectFormat, "Error ({1}): {0}");
            mail.Subject = string.Format(subjectFormat, error.Message, error.Type).
                           Replace('\r', ' ').Replace('\n', ' ');

            //
            // Format the mail body.
            //

            ErrorTextFormatter formatter = CreateErrorFormatter();

            StringWriter bodyWriter = new StringWriter();
            formatter.Format(bodyWriter, error);
            mail.Body = bodyWriter.ToString();

            switch (formatter.MimeType)
            {
#if NET_1_0 || NET_1_1
            case "text/html": mail.BodyFormat = MailFormat.Html; break;

            case "text/plain": mail.BodyFormat = MailFormat.Text; break;
#else
            case "text/html": mail.IsBodyHtml = true; break;

            case "text/plain": mail.IsBodyHtml = false; break;
#endif
            default:
            {
                throw new ApplicationException(string.Format(
                                                   "The error mail module does not know how to handle the {1} media type that is created by the {0} formatter.",
                                                   formatter.GetType().FullName, formatter.MimeType));
            }
            }

#if NET_1_1
            //
            // If the mail needs to be delivered to a particular SMTP server
            // then set-up the corresponding CDO configuration fields of the
            // mail message.
            //

            string smtpServer = Mask.NullString(this.SmtpServer);

            if (smtpServer.Length > 0)
            {
                IDictionary fields = mail.Fields;

                fields.Add(CdoConfigurationFields.SendUsing, /* cdoSendUsingPort */ 2);
                fields.Add(CdoConfigurationFields.SmtpServer, smtpServer);
                int smtpPort = this.SmtpPort;
                fields.Add(CdoConfigurationFields.SmtpServerPort, smtpPort <= 0 ? 25 : smtpPort);

                //
                // If the SMTP server requires authentication (indicated by
                // non-blank user name and password settings) then set-up
                // the corresponding CDO configuration fields of the mail
                // message.
                //

                string userName = Mask.NullString(this.AuthUserName);
                string password = Mask.NullString(this.AuthPassword);

                if (userName.Length > 0 && password.Length > 0)
                {
                    fields.Add(CdoConfigurationFields.SmtpAuthenticate, 1);
                    fields.Add(CdoConfigurationFields.SendUserName, userName);
                    fields.Add(CdoConfigurationFields.SendPassword, password);
                }
            }
#endif
            MailAttachment     ysodAttachment = null;
            ErrorMailEventArgs args           = new ErrorMailEventArgs(error, mail);

            try
            {
                //
                // If an HTML message was supplied by the web host then attach
                // it to the mail if not explicitly told not to do so.
                //

                if (!NoYsod && error.WebHostHtmlMessage.Length > 0)
                {
                    ysodAttachment = CreateHtmlAttachment("YSOD", error.WebHostHtmlMessage);

                    if (ysodAttachment != null)
                    {
                        mail.Attachments.Add(ysodAttachment);
                    }
                }

                //
                // Send off the mail with some chance to pre- or post-process
                // using event.
                //

                OnMailing(args);
                SendMail(mail);
                OnMailed(args);
            }
            finally
            {
#if NET_1_0 || NET_1_1
                //
                // Delete any attached files, if necessary.
                //

                if (ysodAttachment != null)
                {
                    File.Delete(ysodAttachment.Filename);
                    mail.Attachments.Remove(ysodAttachment);
                }
#endif
                OnDisposingMail(args);

#if !NET_1_0 && !NET_1_1
                mail.Dispose();
#endif
            }
        }
예제 #8
0
 public Item(string text, string title, string href)
 {
     _text  = Mask.NullString(text);
     _title = Mask.NullString(title);
     _href  = Mask.NullString(href);
 }
예제 #9
0
        public override void Execute()
        {
            WriteLiteral("\r\n");



            #line 3 "..\..\PoweredBy.cshtml"

            var about = GetAbout((version, fileVersion, product, copyright) => new
            {
                Version = version != null
                  ? version.ToString()
                  : fileVersion != null
                  ? fileVersion.ToString()
                  : "?.?.?.?",
                Product   = Mask.EmptyString(product, "(product)"),
                Copyright = copyright,
            });


            #line default
            #line hidden
            WriteLiteral("<span>\r\n    Powered by <a href=\"http://elmah.googlecode.com/\">");



            #line 15 "..\..\PoweredBy.cshtml"
            Write(about.Product);


            #line default
            #line hidden
            WriteLiteral("</a>,\r\n    version ");



            #line 16 "..\..\PoweredBy.cshtml"
            Write(about.Version);


            #line default
            #line hidden


            #line 16 "..\..\PoweredBy.cshtml"

#if DEBUG
            #line default
            #line hidden
            WriteLiteral(" (");



            #line 18 "..\..\PoweredBy.cshtml"
            Write(Build.Configuration);


            #line default
            #line hidden
            WriteLiteral(")");



            #line 18 "..\..\PoweredBy.cshtml"
                                    #endif


            #line default
            #line hidden
            WriteLiteral(".\r\n    ");



            #line 20 "..\..\PoweredBy.cshtml"
            Write(about.Copyright);


            #line default
            #line hidden
            WriteLiteral("\r\n    Licensed under <a href=\"http://www.apache.org/licenses/LICENSE-2.0\">Apache " +
                         "License, Version 2.0</a>.\r\n</span>\r\n");
        }
예제 #10
0
        public static string BindFormatToken(string token, object[] args, IFormatProvider provider)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }
            if (token.Length == 0)
            {
                throw new ArgumentException("Format token cannot be an empty string.", "token");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }
            if (args.Length == 0)
            {
                throw new ArgumentException("Missing replacement arguments.", "args");
            }

            object source   = args[0];
            int    dotIndex = token.IndexOf('.');
            int    sourceIndex;

            if (dotIndex > 0 && 0 <= (sourceIndex = TryParseUnsignedInteger(token.Substring(0, dotIndex))))
            {
                source = args[sourceIndex];
                token  = token.Substring(dotIndex + 1);
            }

            string format = string.Empty;

            int colonIndex = token.IndexOf(':');

            if (colonIndex > 0)
            {
                format = "{0:" + token.Substring(colonIndex + 1) + "}";
                token  = token.Substring(0, colonIndex);
            }

            if ((sourceIndex = TryParseUnsignedInteger(token)) >= 0)
            {
                source = args[sourceIndex];
                token  = null;
            }

            object result;

            try
            {
                result = DataBinder.Eval(source, token);
                if (result == null)
                {
                    result = string.Empty;
                }
            }
            catch (HttpException e) // Map silly exception type from DataBinder.Eval
            {
                throw new FormatException(e.Message, e);
            }

            return(Mask.NullString(format).Length > 0
                 ? string.Format(provider, format, result)
                 : result.ToString());
        }
예제 #11
0
 public override string ToString()
 {
     return(Mask.EmptyString(MemberName, "<?member>")
            + "@" + Mask.EmptyString(FilePath, "<?filename>")
            + ":" + LineNumber.ToInvariantString());
 }