/// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public SQLiteErrorLog(IDictionary config) { if (config == null) { throw new ArgumentNullException("config"); } string connectionString = ConnectionStringHelper.GetConnectionString(config, true); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) { throw new ApplicationException("Connection string is missing for the SQLite error log."); } _connectionString = connectionString; InitializeDatabase(); ApplicationName = Mask.NullString((string)config["applicationName"]); }
/// <summary> /// Reads the error data in XML attributes. /// </summary> private static void ReadXmlAttributes(XmlReader reader, Error error) { if (reader == null) { throw new ArgumentNullException("reader"); } if (!reader.IsStartElement()) { throw new ArgumentException("Reader is not positioned at the start of an element.", "reader"); } error.ApplicationName = reader.GetAttribute("application"); error.HostName = reader.GetAttribute("host"); error.Type = reader.GetAttribute("type"); error.Message = reader.GetAttribute("message"); error.Source = reader.GetAttribute("source"); error.Detail = reader.GetAttribute("detail"); error.User = reader.GetAttribute("user"); string timeString = Mask.NullString(reader.GetAttribute("time")); error.Time = timeString.Length == 0 ? new DateTime() : XmlConvert.ToDateTime(timeString); string statusCodeString = Mask.NullString(reader.GetAttribute("statusCode")); error.StatusCode = statusCodeString.Length == 0 ? 0 : XmlConvert.ToInt32(statusCodeString); error.WebHostHtmlMessage = reader.GetAttribute("webHostHtmlMessage"); }
protected override void OnLoad(EventArgs e) { // // Retrieve the ID of the error to display and read it from // the store. // string errorId = Mask.NullString(this.Request.QueryString["id"]); if (errorId.Length == 0) { return; } _errorEntry = this.ErrorLog.GetError(errorId); // // Perhaps the error has been deleted from the store? Whatever // the reason, bail out silently. // if (_errorEntry == null) { Response.Status = HttpStatus.NotFound.ToString(); return; } // // Setup the title of the page. // this.PageTitle = string.Format("Error: {0} [{1}]", _errorEntry.Error.Type, _errorEntry.Id); base.OnLoad(e); }
/// <summary> /// Initializes a new instance of the <see cref="VistaDBErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public VistaDBErrorLog(IDictionary config) { if (config == null) { throw new ArgumentNullException("config"); } _connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (_connectionString.Length == 0) { throw new ApplicationException("Connection string is missing for the VistaDB error log."); } _databasePath = ConnectionStringHelper.GetDataSourceFilePath(_connectionString); InitializeDatabase(); string appName = Mask.NullString((string)config["applicationName"]); if (appName.Length > _maxAppNameLength) { throw new ApplicationException(string.Format( "Application name is too long. Maximum length allowed is {0} characters.", _maxAppNameLength.ToString("N0"))); } ApplicationName = appName; }
public static object Eval(object container, string expression) { if (container == null) { throw new ArgumentNullException("container"); } // // The ASP.NET DataBinder.Eval method does not like an empty or null // expression. Rather than making it an unnecessary exception, we // turn a nil-expression to mean, "evaluate to container." // if (Mask.NullString(expression).Length == 0) { return(container); } // // CAUTION! DataBinder.Eval performs late-bound evaluation, using // reflection, at runtime, therefore it can cause performance less // than optimal. If needed, this point can be used to either // compile the expression or optimize out certain cases (known to be // heavily used) by binding statically at compile-time or even // partially at runtime using delegates. // return(System.Web.UI.DataBinder.Eval(container, expression)); }
/// <summary> /// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public XmlFileErrorLog(IDictionary config) { string logPath = Mask.NullString(config["logPath"] as string); if (logPath.Length == 0) { // // For compatibility reasons with older version of this // implementation, we also try "LogPath". // logPath = Mask.NullString(config["LogPath"] as string); if (logPath.Length == 0) { throw new ApplicationException("Log path is missing for the XML file-based error log."); } } #if !NET_1_1 && !NET_1_0 if (logPath.StartsWith("~/")) { logPath = MapPath(logPath); } #endif _logPath = logPath; }
/// <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); _queryString = CopyCollection(request.QueryString); _form = CopyCollection(request.Form); _cookies = CopyCollection(request.Cookies); } }
/// <summary> /// Gets the connection string from the given configuration /// dictionary. /// </summary> public static string GetConnectionString(IDictionary config) { Debug.Assert(config != null); #if !NET_1_1 && !NET_1_0 // // First look for a connection string name that can be // subsequently indexed into the <connectionStrings> section of // the configuration to get the actual connection string. // string connectionStringName = (string)config["connectionStringName"] ?? string.Empty; if (connectionStringName.Length > 0) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[connectionStringName]; if (settings == null) { return(string.Empty); } return(settings.ConnectionString ?? string.Empty); } #endif // // Connection string name not found so see if a connection // string was given directly. // string connectionString = Mask.NullString((string)config["connectionString"]); if (connectionString.Length > 0) { return(connectionString); } // // As a last resort, check for another setting called // connectionStringAppKey. The specifies the key in // <appSettings> that contains the actual connection string to // be used. // string connectionStringAppKey = Mask.NullString((string)config["connectionStringAppKey"]); if (connectionStringAppKey.Length == 0) { return(string.Empty); } return(Configuration.AppSettings[connectionStringAppKey]); }
public void ProcessRequest(HttpContext context) { HttpResponse response = context.Response; response.ContentType = "application/xml"; // // Retrieve the ID of the requested error and read it from // the store. // string errorId = Mask.NullString(context.Request.QueryString["id"]); if (errorId.Length == 0) { throw new ApplicationException("Missing error identifier specification."); } ErrorLogEntry entry = ErrorLog.GetDefault(context).GetError(errorId); // // Perhaps the error has been deleted from the store? Whatever // the reason, pretend it does not exist. // if (entry == null) { throw new HttpException((int)HttpStatusCode.NotFound, string.Format("Error with ID '{0}' not found.", errorId)); } // // Stream out the error as formatted XML. // #if !NET_1_0 && !NET_1_1 XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.NewLineOnAttributes = true; settings.CheckCharacters = false; XmlWriter writer = XmlWriter.Create(response.Output, settings); #else XmlTextWriter writer = new XmlTextWriter(response.Output); writer.Formatting = Formatting.Indented; #endif writer.WriteStartDocument(); writer.WriteStartElement("error"); ErrorXml.Encode(entry.Error, writer); writer.WriteEndElement(/* error */); writer.WriteEndDocument(); writer.Flush(); }
/// <summary> /// Initializes a new instance of the <see cref="OracleErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public OracleErrorLog(IDictionary config) { if (config == null) { throw new ArgumentNullException("config"); } string connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) { throw new ApplicationException("Connection string is missing for the Oracle error log."); } _connectionString = connectionString; // // Set the application name as this implementation provides // per-application isolation over a single store. // string appName = Mask.NullString((string)config["applicationName"]); if (appName.Length > _maxAppNameLength) { throw new ApplicationException(string.Format( "Application name is too long. Maximum length allowed is {0} characters.", _maxAppNameLength.ToString("N0"))); } ApplicationName = appName; _schemaOwner = Mask.NullString((string)config["schemaOwner"]); if (_schemaOwner.Length > _maxSchemaNameLength) { throw new ApplicationException(string.Format( "Oracle schema owner is too long. Maximum length allowed is {0} characters.", _maxSchemaNameLength.ToString("N0"))); } if (_schemaOwner.Length > 0) { _schemaOwner = _schemaOwner + "."; } }
private static string ResolveDataSourceFilePath(string path) { const string dataDirectoryMacroString = "|DataDirectory|"; // // Check to see if it starts with a ~/ and if so map it and return it. // if (path.StartsWith("~/")) { return(MapPath(path)); } // // Else see if it uses the DataDirectory macro/substitution // string, and if so perform the appropriate substitution. // if (!path.StartsWith(dataDirectoryMacroString, StringComparison.OrdinalIgnoreCase)) { return(path); } // // Look-up the data directory from the current AppDomain. // See "Working with local databases" for more: // http://blogs.msdn.com/smartclientdata/archive/2005/08/26/456886.aspx // string baseDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string; // // If not, try the current AppDomain's base directory. // if (string.IsNullOrEmpty(baseDirectory)) { baseDirectory = AppDomain.CurrentDomain.BaseDirectory; } // // Piece the file path back together, taking leading and // trailing backslashes into account to avoid duplication. // return(Mask.NullString(baseDirectory).TrimEnd(_dirSeparators) + Path.DirectorySeparatorChar + path.Substring(dataDirectoryMacroString.Length).TrimStart(_dirSeparators)); }
/// <summary> /// Determines whether the request is from the local computer or not. /// </summary> /// <remarks> /// This method is primarily for .NET Framework 1.x where the /// <see cref="HttpRequest.IsLocal"/> was not available. /// </remarks> public static bool IsLocal(HttpRequest request) { if (request == null) { throw new ArgumentNullException("request"); } #if NET_1_0 || NET_1_1 string userHostAddress = Mask.NullString(request.UserHostAddress); return(userHostAddress.Equals("127.0.0.1") /* IP v4 */ || userHostAddress.Equals("::1") /* IP v6 */ || userHostAddress.Equals(request.ServerVariables["LOCAL_ADDR"])); #else return(request.IsLocal); #endif }
private static string GetString(IDictionary options, string name) { Debug.Assert(name != null); if (options == null) { return(string.Empty); } object value = options[name]; if (value == null) { return(string.Empty); } return(Mask.NullString(value.ToString())); }
public static object CreateFromConfigSection(string sectionName) { Debug.AssertStringNotEmpty(sectionName); // // Get the configuration section with the settings. // IDictionary config = (IDictionary)Configuration.GetSection(sectionName); if (config == null) { return(null); } // // We modify the settings by removing items as we consume // them so make a copy here. // config = (IDictionary)((ICloneable)config).Clone(); // // Get the type specification of the service provider. // string typeSpec = Mask.NullString((string)config["type"]); if (typeSpec.Length == 0) { return(null); } config.Remove("type"); // // Locate, create and return the service provider object. // Type type = Type.GetType(typeSpec, true); return(Activator.CreateInstance(type, new object[] { config })); }
private static string GetSetting(IDictionary config, string name, string defaultValue) { Debug.Assert(config != null); Debug.AssertStringNotEmpty(name); string value = Mask.NullString((string)config[name]); if (value.Length == 0) { if (defaultValue == null) { throw new ApplicationException(string.Format( "The required configuration setting '{0}' is missing for the error mailing module.", name)); } value = defaultValue; } return(value); }
/// <summary> /// Initializes a new instance of the <see cref="MemoryErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public MemoryErrorLog(IDictionary config) { if (config == null) { _size = DefaultSize; } else { string sizeString = Mask.NullString((string)config["size"]); if (sizeString.Length == 0) { _size = DefaultSize; } else { _size = Convert.ToInt32(sizeString, CultureInfo.InvariantCulture); _size = Math.Max(0, Math.Min(MaximumSize, _size)); } } }
protected override void Render(HtmlTextWriter writer) { if (writer == null) { throw new ArgumentNullException("writer"); } // // Retrieve the ID of the error to display and read it from // the log. // string errorId = Mask.NullString(this.Request.QueryString["id"]); if (errorId.Length == 0) { return; } ErrorLogEntry errorEntry = this.ErrorLog.GetError(errorId); if (errorEntry == null) { // TODO: Send error response entity Response.Status = HttpStatus.NotFound.ToString(); return; } // // If we have a host (ASP.NET) formatted HTML message // for the error then just stream it out as our response. // if (errorEntry.Error.WebHostHtmlMessage.Length == 0) { return; } writer.Write(errorEntry.Error.WebHostHtmlMessage); }
/// <remarks> /// If <paramref name="unknownName"/> is a null reference then this /// method will still return an empty string. /// </remarks> public static string TryGetMachineName(HttpContext context, string unknownName) { // // System.Web.HttpServerUtility.MachineName and // System.Environment.MachineName require different permissions. // Try the former then the latter...chances are higher to have // permissions for the former. // if (context != null) { try { return(context.Server.MachineName); } catch (HttpException) { // Yes, according to docs, HttpServerUtility.MachineName // throws HttpException on failing to obtain computer name. } catch (SecurityException) { // A SecurityException may occur in certain, possibly // user-modified, Medium trust environments. } } try { return(System.Environment.MachineName); } catch (SecurityException) { // A SecurityException may occur in certain, possibly // user-modified, Medium trust environments. } return(Mask.NullString(unknownName)); }
public override void Header() { string callback = Mask.NullString(Context.Request.QueryString[Mask.EmptyString(null, "callback")]); if (callback.Length == 0) { throw new Exception("The JSONP callback parameter is missing."); } if (!_callbackExpression.IsMatch(callback)) { throw new Exception("The JSONP callback parameter is not in an acceptable format."); } _callback = callback; HttpResponse response = Context.Response; if (!_wrapped) { response.AppendHeader("Content-Type", "text/javascript"); response.AppendHeader("Content-Disposition", "attachment; filename=errorlog.js"); } else { response.AppendHeader("Content-Type", "text/html"); TextWriter output = response.Output; output.WriteLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"); output.WriteLine(@" <html xmlns='http://www.w3.org/1999/xhtml'> <head> <title>Error Log in HTML-Wrapped JSONP Format</title> </head> <body> <p>This page is primarily designed to be used in an IFRAME of a parent HTML document.</p>"); } }
public void ProcessRequest(HttpContext context) { HttpResponse response = context.Response; response.ContentType = "application/json"; // // Retrieve the ID of the requested error and read it from // the store. // string errorId = Mask.NullString(context.Request.QueryString["id"]); if (errorId.Length == 0) { throw new ApplicationException("Missing error identifier specification."); } ErrorLogEntry entry = ErrorLog.GetDefault(context).GetError(errorId); // // Perhaps the error has been deleted from the store? Whatever // the reason, pretend it does not exist. // if (entry == null) { throw new HttpException((int)HttpStatusCode.NotFound, string.Format("Error with ID '{0}' not found.", errorId)); } // // Stream out the error as formatted JSON. // ErrorJson.Encode(entry.Error, response.Output); }
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()); }
/// <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(" "); } writer.RenderEndTag(); // </td> writer.RenderEndTag(); // </tr> } writer.RenderEndTag(); // </table> writer.WriteLine(); }
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…"; 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); }
public Item(string text, string title, string href) { _text = Mask.NullString(text); _title = Mask.NullString(title); _href = Mask.NullString(href); }
/// <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 } }
public static string EmptyString(string s, string filler) { return(Mask.NullString(s).Length == 0 ? filler : s); }