} // /// <summary> /// Send a email created with the parameters /// The destination is assumed to be the site contact, and from defaults to the system value /// </summary> /// <remarks> /// Use the SMTP server configured in the web.config as smtpEmail /// </remarks> /// <param name="subject">Email subject</param> /// <param name="message">Message Text</param> /// <returns></returns> public static bool SendSiteEmail(string subject, string message) { string toEmail = UtilityManager.GetAppKeyValue("contactUsMailTo", "*****@*****.**"); string fromEmail = UtilityManager.GetAppKeyValue("contactUsMailFrom", "*****@*****.**"); return(SendEmail(toEmail, fromEmail, subject, message, "", "")); } //
} // private static void DoSendEmail(MailMessage emailMsg) { string emailService = UtilityManager.GetAppKeyValue("emailService", "smtp"); if (emailService == "mailgun") { SendEmailViaMailgun(emailMsg); } else if (emailService == "serviceApi") { SendEmailViaApi(emailMsg); } else if (emailService == "smtp") { SmtpClient smtp = new SmtpClient(UtilityManager.GetAppKeyValue("SmtpHost")) { UseDefaultCredentials = false, Credentials = new NetworkCredential("mparsons", "SomeNewCreds") }; smtp.Send(emailMsg); //SmtpMail.Send(email); } //else if ( emailService == "sendGrid" ) //{ // EmailViaSendGrid( emailMsg ); //} else { //no service api LoggingHelper.DoTrace(2, "***** EmailManager.SendEmail - UNHANDLED EMAIL SERVICE ENCOUNTERED ******"); return; } }
public static bool IsMessageInCache(string message) { if (string.IsNullOrWhiteSpace(message)) { return(false); } string key = UtilityManager.GenerateMD5String(message); try { if (HttpRuntime.Cache[key] != null) { var msgExists = ( string )HttpRuntime.Cache[key]; if (msgExists.ToLower() == message.ToLower()) { LoggingHelper.DoTrace(7, "LoggingHelper. Duplicate message: " + message); return(true); } } } catch { } return(false); }
/// <summary> /// IsTestEnv - determines if the current environment is a testing/development /// </summary> /// <returns>True if localhost - implies testing</returns> //public static bool IsTestEnv() //{ // string host = HttpContext.Current.Request.Url.Host.ToString(); // if ( host.ToLower() == "localhost" ) // return true; // else // return false; //} // /// <summary> /// Handle trace requests - typically during development, but may be turned on to track code flow in production. /// </summary> /// <param name="message">Trace message</param> /// <remarks>This is a helper method that defaults to a trace level of 10</remarks> public static void DoTrace(string message) { //default level to 8 int appTraceLevel = UtilityManager.GetAppKeyValue("appTraceLevel", 8); if (appTraceLevel < 8) { appTraceLevel = 8; } DoTrace(appTraceLevel, message, true); }
/// <summary> /// Write the message to the log file. /// </summary> /// <remarks> /// The message will be appended to the log file only if the flag "logErrors" (AppSetting) equals yes. /// The log file is configured in the web.config, appSetting: "error.log.path" /// </remarks> /// <param name="message">Message to be logged.</param> public static void LogError(string message, string subject = "Credential Finder Exception encountered") { if (UtilityManager.GetAppKeyValue("notifyOnException", "no").ToLower() == "yes") { LogError(message, true, subject); } else { LogError(message, false, subject); } } //
} // /// <summary> /// Write the message to the log file. /// </summary> /// <remarks> /// The message will be appended to the log file only if the flag "logErrors" (AppSetting) equals yes. /// The log file is configured in the web.config, appSetting: "error.log.path" /// </remarks> /// <param name="message">Message to be logged.</param> /// <param name="notifyAdmin"></param> public static void LogError(string message, bool notifyAdmin, string subject = "Credential Finder Exception encountered") { if (UtilityManager.GetAppKeyValue("logErrors").ToString().Equals("yes")) { try { //would like to limit number, just need a means to overwrite the first time used in a day //- check existance, then if for a previous day, overwrite string datePrefix1 = System.DateTime.Today.ToString("u").Substring(0, 10); string datePrefix = System.DateTime.Today.ToString("yyyy-dd"); string logFile = UtilityManager.GetAppKeyValue("path.error.log", ""); if (!string.IsNullOrWhiteSpace(logFile)) { string outputFile = logFile.Replace("[date]", datePrefix); if (File.Exists(outputFile)) { if (File.GetLastWriteTime(outputFile).Month != DateTime.Now.Month) { File.Delete(outputFile); } } else { System.IO.FileInfo f = new System.IO.FileInfo(outputFile); f.Directory.Create(); // If the directory already exists, this method does nothing. } StreamWriter file = File.AppendText(outputFile); file.WriteLine(DateTime.Now + ": " + message); file.WriteLine("---------------------------------------------------------------------"); file.Close(); } if (notifyAdmin) { if (ShouldMessagesBeSkipped(message) == false && !IsADuplicateRequest(message)) { EmailManager.NotifyAdmin(subject, message); } StoreLastError(message); } } catch (Exception ex) { //eat any additional exception DoTrace(5, thisClassName + ".LogError(string message, bool notifyAdmin). Exception while logging. \r\nException: " + ex.Message + ".\r\n Original message: " + message); } } } //
public static void StoreSessionMessage(string message) { string sessionKey = UtilityManager.GenerateMD5String(message); try { if (HttpContext.Current.Session != null) { HttpContext.Current.Session[sessionKey] = message; } } catch { } } //
public static void AddMessageToCache(string message, int cacheForHours = 2) { string key = UtilityManager.GenerateMD5String(message); if (HttpContext.Current != null) { if (HttpContext.Current.Cache[key] != null) { HttpRuntime.Cache.Remove(key); } else { System.Web.HttpRuntime.Cache.Insert(key, message, null, DateTime.Now.AddHours(cacheForHours), TimeSpan.Zero); } } }
} // /// <summary> /// Log email message - for future resend/reviews /// </summary> /// <param name="level"></param> /// <param name="email"></param> public static void LogEmail(int level, MailMessage email) { string msg = ""; int appTraceLevel = 0; try { appTraceLevel = UtilityManager.GetAppKeyValue("appTraceLevel", 1); //Allow if the requested level is <= the application thresh hold if (level <= appTraceLevel) { msg = "\n=============================================================== "; msg += "\nDate: " + System.DateTime.Now.ToString(); msg += "\nFrom: " + email.From.ToString(); msg += "\nTo: "+ email.To.ToString(); msg += "\nCC: "+ email.CC.ToString(); msg += "\nBCC: " + email.Bcc.ToString(); msg += "\nSubject: " + email.Subject.ToString(); msg += "\nMessage: " + email.Body.ToString(); msg += "\n=============================================================== "; string datePrefix1 = System.DateTime.Today.ToString("u").Substring(0, 10); string datePrefix = System.DateTime.Today.ToString("yyyy-dd"); string logFile = UtilityManager.GetAppKeyValue("path.email.log", ""); if (!string.IsNullOrWhiteSpace(logFile)) { string outputFile = logFile.Replace("[date]", datePrefix); if (File.Exists(outputFile)) { if (File.GetLastWriteTime(outputFile).Month != DateTime.Now.Month) { File.Delete(outputFile); } } StreamWriter file = File.AppendText(outputFile); file.WriteLine(msg); file.Close(); } } } catch { //ignore errors } }
public static void DoBotTrace(int level, string message) { string msg = ""; int appTraceLevel = 0; try { appTraceLevel = UtilityManager.GetAppKeyValue("botTraceLevel", 5); //Allow if the requested level is <= the application thresh hold if (level <= appTraceLevel) { msg = "\n " + System.DateTime.Now.ToString() + " - " + message; string datePrefix1 = System.DateTime.Today.ToString("u").Substring(0, 10); string datePrefix = System.DateTime.Today.ToString("yyyy-dd"); string logFile = UtilityManager.GetAppKeyValue("path.botTrace.log", ""); if (!string.IsNullOrWhiteSpace(logFile)) { string outputFile = logFile.Replace("[date]", datePrefix); if (File.Exists(outputFile)) { if (File.GetLastWriteTime(outputFile).Month != DateTime.Now.Month) { File.Delete(outputFile); } } else { System.IO.FileInfo f = new System.IO.FileInfo(outputFile); f.Directory.Create(); // If the directory already exists, this method does nothing. } StreamWriter file = File.AppendText(outputFile); file.WriteLine(msg); file.Close(); } } } catch { //ignore errors } } //
/// <summary> /// ExportDataTableAsCsv - formats a DataTable in CSV format and then streams to the browser /// </summary> /// <param name="dt">DataTable</param> /// <param name="tempFilename">Name of temporary file</param> public void ExportDataTableAsCsv(DataTable dt, string tempFilename) { string datePrefix = System.DateTime.Today.ToString("u").Substring(0, 10); string filePath = UtilityManager.GetAppKeyValue("path.ReportsOutputPath", ""); string outputFile = filePath + datePrefix + "_" + tempFilename; // //string filename = "budgetExport.csv"; string csvFilename = this.DataTableAsCsv(dt, outputFile, false); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + tempFilename + ""); HttpContext.Current.Response.WriteFile(csvFilename); HttpContext.Current.Response.End(); // Delete the newly created file. //TODO: - this line is not actually executed - need scheduled clean ups? //File.Delete(Server.MapPath(csvFilename)); }
/// <summary> /// Set Application Message using passed resource manager, resource string and placeholder /// </summary> /// <param name="msgString">Message to be displayed</param> /// <param name="msgPlaceholder">PlaceHolder where message control will be loaded</param> public static void SetApplicationMessage(string msgString, PlaceHolder msgPlaceholder) { SetSessionItem("appMessage", msgString); // //assume error style for now string css = UtilityManager.GetAppKeyValue("errorMessageCss", "errorMessage"); FormMessage formMessage = new FormMessage(); formMessage.Text = msgString; formMessage.Title = "Application Error"; formMessage.CssClass = css; formMessage.ShowPopup = false; if (msgString.IndexOf("<") > -1 || msgString.IndexOf("</") > -1) { formMessage.IsFormatted = true; } HttpContext.Current.Session["FormMessage"] = formMessage; } //
public static bool IsADuplicateRecentSessionMessage(string message) { string sessionKey = UtilityManager.GenerateMD5String(message); bool isDup = false; try { if (HttpContext.Current.Session != null) { string msgExists = HttpContext.Current.Session[sessionKey].ToString(); if (msgExists.ToLower() == message.ToLower()) { LoggingHelper.DoTrace(7, "LoggingHelper. Duplicate message: " + message); return(true); } } } catch { } return(isDup); }
private static void SendEmailViaApi(MailMessage emailMsg) { string emailServiceUri = UtilityManager.GetAppKeyValue("SendEmailService"); if (string.IsNullOrWhiteSpace(emailServiceUri)) { //no service api LoggingHelper.DoTrace(2, "***** EmailManager.SendEmail - no email service has been configured"); return; } //else if ( emailServiceUri.ToLower().Equals( "sendgrid" ) ) //{ // EmailViaSendGrid( emailMsg ); // return; //} //else if ( emailServiceUri.ToLower().Equals( "smtp" ) ) //{ // EmailViaSmtp( emailMsg ); // return; //} var email = new Email() { Message = emailMsg.Body, From = emailMsg.From.Address, To = emailMsg.To.ToString(), CC = emailMsg.CC.ToString(), BCC = emailMsg.Bcc.ToString(), IsHtml = true, Subject = emailMsg.Subject }; var postBody = JsonConvert.SerializeObject(email); PostRequest(postBody, emailServiceUri); }
} // public static void SendEmail(string fromEmail, string[] toEmail, string[] ccEmail, string[] bccEmail, string subject, string emailBody, string[] attachments) { MailMessage email = new MailMessage(); try { email.From = new MailAddress(fromEmail); if (toEmail != null) { foreach (string address in toEmail) { email.To.Add(address.Trim()); } } if (ccEmail != null) { foreach (string address in ccEmail) { email.CC.Add(address.Trim()); } } if (bccEmail != null) { foreach (string address in bccEmail) { email.Bcc.Add(address.Trim()); } } email.Subject = subject; email.Body = emailBody; if (attachments != null) { foreach (string fileName in attachments) { Attachment mailAttachment = new Attachment(fileName.Trim()); email.Attachments.Add(mailAttachment); } } DoSendEmail(email); if (UtilityManager.GetAppKeyValue("logAllEmail", "no") == "yes") { LogEmail(1, email); } } catch (Exception ex) { if (UtilityManager.GetAppKeyValue("logAllEmail", "no") == "yes") { LogEmail(1, email); } Console.WriteLine(ex.ToString()); // LoggingHelper.LogError( "UtilityManager.sendEmail(): Error while attempting to send:" //+ "\r\nFrom:" + fromEmail + " To:" + toEmail //+ "\r\nCC:(" + CC + ") BCC:(" + BCC + ") " //+ "\r\nSubject:" + subject //+ "\r\nMessage:" + message //+ "\r\nError message: " + exc.ToString() ); } }
/// <summary> /// Sends an email message to the system administrator /// </summary> /// <param name="emailTo">admin resource responsible for exceptions</param> /// <param name="subject">Email subject</param> /// <param name="message">Email message</param> /// <returns>True id message was sent successfully, otherwise false</returns> public static bool NotifyAdmin(string emailTo, string subject, string message) { char[] delim = new char[1]; delim[0] = ','; string emailFrom = UtilityManager.GetAppKeyValue("systemNotifyFromEmail"); string cc = UtilityManager.GetAppKeyValue("systemAdminEmail"); if (emailTo == "") { emailTo = cc; cc = ""; } //avoid infinite loop by ensuring this method didn't generate the exception if (message.IndexOf("EmailManager.NotifyAdmin") > -1) { //skip may be error on send return(true); } else { if (emailTo.ToLower() == cc.ToLower()) { cc = ""; } message = message.Replace("\r", "<br/>"); MailMessage email = new MailMessage(emailFrom, emailTo); //try to make subject more specific //if: workNet Exception encountered, try to insert type if (subject.IndexOf("Finder Exception") > -1) { subject = FormatExceptionSubject(subject, message); } subject = FormHelper.CleanText(subject); subject = System.Text.RegularExpressions.Regex.Replace(subject, @"\r\n?|\n", ""); email.Subject = subject; if (message.IndexOf("Type:") > 0) { int startPos = message.IndexOf("Type:"); int endPos = message.IndexOf("Error Message:"); if (endPos > startPos) { subject += " - " + message.Substring(startPos, endPos - startPos); } } if (cc.Trim().Length > 0) { cc = cc.Replace(";", ","); //email.CC.Add( CC ); string[] ccSplit = cc.Trim().Split(delim); foreach (string item in ccSplit) { if (item.Trim() != "") { string addr = HandleProxyEmails(item.Trim()); MailAddress ma = new MailAddress(addr); email.CC.Add(ma); } } } email.Body = DateTime.Now + "<br>" + message.Replace("\n\r", "<br>"); email.Body = email.Body.Replace("\r\n", "<br>"); email.Body = email.Body.Replace("\n", "<br>"); email.Body = email.Body.Replace("\r", "<br>"); email.IsBodyHtml = true; //email.BodyFormat = MailFormat.Html; try { //The trace was a just in case, if the send fails, a LogError call will be made anyway. Set to a high level so not shown in prod LoggingHelper.DoTrace(11, "EmailManager.NotifyAdmin: - Admin email was requested:\r\nSubject:" + subject + "\r\nMessage:" + message); if (UtilityManager.GetAppKeyValue("sendEmailFlag", "false") == "TRUE") { DoSendEmail(email); } if (UtilityManager.GetAppKeyValue("logAllEmail", "no") == "yes") { LogEmail(1, email); } return(true); } catch (Exception exc) { LoggingHelper.LogError("EmailManager.NotifyAdmin(): Error while attempting to send:" + "\r\nSubject:" + subject + "\r\nMessage:" + message + "\r\nError message: " + exc.ToString(), false); } } return(false); } //
} /// /// <summary> /// Sends an email message to the system administrator /// </summary> /// <param name="subject">Email subject</param> /// <param name="message">Email message</param> /// <returns>True id message was sent successfully, otherwise false</returns> public static bool NotifyAdmin(string subject, string message) { string emailTo = UtilityManager.GetAppKeyValue("systemAdminEmail", "*****@*****.**"); return(NotifyAdmin(emailTo, subject, message)); }
/// <summary> /// Format an exception and message, and then log it /// </summary> /// <param name="ex">Exception</param> /// <param name="message">Additional message regarding the exception</param> /// <param name="notifyAdmin">If true, an email will be sent to admin</param> public static void LogError(Exception ex, string message, bool notifyAdmin, string subject = "Credential Finder Exception encountered") { //string userId = ""; string sessionId = "unknown"; string remoteIP = "unknown"; string path = "unknown"; string queryString = "unknown"; string url = "unknown"; string parmsString = ""; string lRefererPage = ""; try { if (UtilityManager.GetAppKeyValue("notifyOnException", "no").ToLower() == "yes") { notifyAdmin = true; } if (HttpContext.Current != null) { if (HttpContext.Current.Session != null) { sessionId = HttpContext.Current.Session.SessionID.ToString(); } remoteIP = HttpContext.Current.Request.ServerVariables["REMOTE_HOST"]; if (HttpContext.Current.Request.UrlReferrer != null) { lRefererPage = HttpContext.Current.Request.UrlReferrer.ToString(); } string serverName = UtilityManager.GetAppKeyValue("serverName", HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]); path = serverName + HttpContext.Current.Request.Path; if (FormHelper.IsValidRequestString() == true) { queryString = HttpContext.Current.Request.Url.AbsoluteUri.ToString(); //url = GetPublicUrl( queryString ); url = HttpContext.Current.Server.UrlDecode(queryString); //if ( url.IndexOf( "?" ) > -1 ) //{ // parmsString = url.Substring( url.IndexOf( "?" ) + 1 ); // url = url.Substring( 0, url.IndexOf( "?" ) ); //} } else { url = "suspicious url encountered!!"; } //???? //userId = WUM.GetCurrentUserid(); } } catch { //eat any additional exception } try { string errMsg = message + "\r\nType: " + ex.GetType().ToString() + ";" + "\r\nSession Id - " + sessionId + "____IP - " + remoteIP + "\r\rReferrer: " + lRefererPage + ";" + "\r\nException: " + ex.Message.ToString() + ";" + "\r\nStack Trace: " + ex.StackTrace.ToString() + "\r\nServer\\Template: " + path + "\r\nUrl: " + url; if (ex.InnerException != null && ex.InnerException.Message != null) { errMsg += "\r\n****Inner exception: " + ex.InnerException.Message; if (ex.InnerException.InnerException != null && ex.InnerException.InnerException.Message != null) { errMsg += "\r\n@@@@@@Inner-Inner exception: " + ex.InnerException.InnerException.Message; } } if (parmsString.Length > 0) { errMsg += "\r\nParameters: " + parmsString; } LoggingHelper.LogError(errMsg, notifyAdmin, subject); } catch { //eat any additional exception } } //
} // /// <summary> /// Send an e-mail using a formatted EmailNotice /// - assumes the Message property contains the formatted e-mail - allows for not HTML variety /// </summary> /// <param name="toEmail"></param> /// <param name="notice"></param> /// <returns></returns> //public static bool SendEmail( string toEmail, EmailNotice notice ) //{ // return SendEmail( toEmail, notice.FromEmail, notice.Subject, notice.Message, notice.CcEmail, notice.BccEmail ); //} // /// <summary> /// Send a email created with the parameters /// </summary> /// <param name="toEmail"></param> /// <param name="fromEmail"></param> /// <param name="subject"></param> /// <param name="message"></param> /// <param name="CC"></param> /// <param name="BCC"></param> /// <returns></returns> public static bool SendEmail(string toEmail, string fromEmail, string subject, string message, string CC, string BCC) { char[] delim = new char[1]; delim[0] = ','; MailMessage email = new MailMessage(); string appEmail = UtilityManager.GetAppKeyValue("contactUsMailFrom", "*****@*****.**"); string systemAdminEmail = UtilityManager.GetAppKeyValue("systemAdminEmail", "*****@*****.**"); if (string.IsNullOrWhiteSpace(BCC)) { BCC = systemAdminEmail; } else { BCC += ", " + systemAdminEmail; } try { MailAddress maFrom; if (fromEmail.Trim().Length == 0) { fromEmail = appEmail; } maFrom = new MailAddress(fromEmail); if (toEmail.Trim().EndsWith(";")) { toEmail = toEmail.TrimEnd(Char.Parse(";"), Char.Parse(" ")); } email.From = maFrom; //use the add format to handle multiple email addresses - not sure what delimiters are allowed toEmail = toEmail.Replace(";", ","); //email.To.Add( toEmail ); string[] toSplit = toEmail.Trim().Split(delim); foreach (string item in toSplit) { if (item.Trim() != "") { string addr = HandleProxyEmails(item.Trim()); MailAddress ma = new MailAddress(addr); email.To.Add(ma); } } //email.To = FormatEmailAddresses( toEmail ); if (CC.Trim().Length > 0) { CC = CC.Replace(";", ","); //email.CC.Add( CC ); string[] ccSplit = CC.Trim().Split(delim); foreach (string item in ccSplit) { if (item.Trim() != "") { string addr = HandleProxyEmails(item.Trim()); MailAddress ma = new MailAddress(addr); email.CC.Add(ma); } } } if (BCC.Trim().Length > 0) { BCC = BCC.Replace(";", ","); //email.Bcc.Add( BCC ); string[] bccSplit = BCC.Trim().Split(delim); foreach (string item in bccSplit) { if (item.Trim() != "") { string addr = HandleProxyEmails(item.Trim()); MailAddress ma = new MailAddress(addr); email.Bcc.Add(ma); } } } email.Subject = subject; email.Body = message; email.IsBodyHtml = true; //email.BodyFormat = MailFormat.Html; if (UtilityManager.GetAppKeyValue("sendEmailFlag", "false") == "TRUE") { DoSendEmail(email); } if (UtilityManager.GetAppKeyValue("logAllEmail", "no") == "yes") { LogEmail(1, email); } return(true); } catch (Exception exc) { if (UtilityManager.GetAppKeyValue("logAllEmail", "no") == "yes") { LogEmail(1, email); } LoggingHelper.LogError("UtilityManager.sendEmail(): Error while attempting to send:" + "\r\nFrom:" + fromEmail + " To:" + toEmail + "\r\nCC:(" + CC + ") BCC:(" + BCC + ") " + "\r\nSubject:" + subject + "\r\nMessage:" + message + "\r\nError message: " + exc.ToString()); } return(false); } //
} // /// <summary> /// Sends an email message to the system administrator /// </summary> /// <param name="subject">Email subject</param> /// <param name="message">Email message</param> /// <returns>True id message was sent successfully, otherwise false</returns> public static bool NotifyAdmin(string subject, string message) { string emailTo = UtilityManager.GetAppKeyValue("systemAdminEmail", "*****@*****.**"); return(NotifyAdmin(emailTo, subject, message)); }
/// <summary> /// Handle trace requests - typically during development, but may be turned on to track code flow in production. /// </summary> /// <param name="level"></param> /// <param name="message"></param> /// <param name="showingDatetime">If true, precede message with current date-time, otherwise just the message> The latter is useful for data dumps</param> public static void DoTrace(int level, string message, bool showingDatetime = true, string logPrefix = "") { //TODO: Future provide finer control at the control level string msg = ""; int appTraceLevel = UtilityManager.GetAppKeyValue("appTraceLevel", 6); //bool useBriefFormat = true; const int NumberOfRetries = 4; const int DelayOnRetry = 1000; if (showingDatetime) { msg = "\n " + System.DateTime.Now.ToString() + " - " + message; } else { msg = "\n " + message; } string datePrefix1 = System.DateTime.Today.ToString("u").Substring(0, 10); string datePrefix = System.DateTime.Today.ToString("yyyy-dd"); string logFile = UtilityManager.GetAppKeyValue("path.trace.log", ""); if (!string.IsNullOrWhiteSpace(logPrefix)) { datePrefix += "_" + logPrefix; } //Allow if the requested level is <= the application thresh hold if (string.IsNullOrWhiteSpace(logFile) || level > appTraceLevel) { return; } string outputFile = ""; if (message.IndexOf("UPPER CASE URI") > -1 || message.IndexOf("GRAPH URI") > -1) { logFile = logFile.Replace("[date]", "[date]_URI_ISSUES"); } //added retries where log file is in use for (int i = 1; i <= NumberOfRetries; ++i) { try { outputFile = logFile.Replace("[date]", datePrefix + (i < 3 ? "" : "_" + i.ToString())); if (File.Exists(outputFile)) { if (File.GetLastWriteTime(outputFile).Month != DateTime.Now.Month) { File.Delete(outputFile); } } else { System.IO.FileInfo f = new System.IO.FileInfo(outputFile); f.Directory.Create(); // If the directory already exists, this method does nothing. } StreamWriter file = File.AppendText(outputFile); file.WriteLine(msg); file.Close(); if (level > 0) { Console.WriteLine(msg); } break; } catch (IOException e) when(i <= NumberOfRetries) { // You may check error code to filter some exceptions, not every error // can be recovered. Thread.Sleep(DelayOnRetry); } catch (Exception ex) { //ignore errors } } }
public static void WriteLogFile(int level, string filename, string message, string datePrefixOverride = "", bool appendingText = true) { int appTraceLevel = 0; try { appTraceLevel = UtilityManager.GetAppKeyValue("appTraceLevel", 6); //Allow if the requested level is <= the application thresh hold if (level <= appTraceLevel) { string datePrefix = System.DateTime.Today.ToString("u").Substring(0, 10); if (!string.IsNullOrWhiteSpace(datePrefixOverride)) { datePrefix = datePrefixOverride; } else if (datePrefixOverride == " ") { datePrefix = ""; } string logFile = UtilityManager.GetAppKeyValue("path.log.file", "C:\\LOGS.txt"); string outputFile = logFile.Replace("[date]", datePrefix).Replace("[filename]", filename); if (outputFile.IndexOf("csv.txt") > 1) { outputFile = outputFile.Replace("csv.txt", "csv"); } else if (outputFile.IndexOf("csv.json") > 1) { outputFile = outputFile.Replace("csv.json", "csv"); } else if (outputFile.IndexOf("html.json") > 1) { outputFile = outputFile.Replace("html.json", "html"); } else if (outputFile.IndexOf("json.txt") > 1) { outputFile = outputFile.Replace("json.txt", "json"); } else if (outputFile.IndexOf("json.json") > 1) { outputFile = outputFile.Replace("json.json", "json"); } else if (outputFile.IndexOf("txt.json") > 1) { outputFile = outputFile.Replace("txt.json", "txt"); } if (appendingText) { StreamWriter file = File.AppendText(outputFile); file.WriteLine(message); file.Close(); } else { //FileStream file = File.Create( outputFile ); //file.( message ); //file.Close(); File.WriteAllText(outputFile, message); } } } catch { //ignore errors } }