} //

        public static int GetAppKeyValue(string keyName, int defaultValue)
        {
            int appValue = -1;

            try
            {
                appValue = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings[keyName]);

                // If we get here, then number is an integer, otherwise we will use the default
            }
            catch
            {
                appValue = defaultValue;
                if (HasMessageBeenPreviouslySent(keyName) == false)
                {
                    LoggingHelper.LogError(string.Format("@@@@ Error on appKey: {0},  using default of: {1}", keyName, defaultValue));
                }
            }

            return(appValue);
        } //
        }        //

        /// <summary>
        /// Create the passed directory structure
        /// As System.IO.Directory.CreateDirectory() checks folder existence from root to lowest folder, it will fail if an intermediate folder
        /// doesn't exist. This method performs the scan in the reverse way - from lowest to upper. Therefore, it won't fail unless it will get to
        /// some folder with no read permissions.
        /// requires Microsoft Scripting Runtime COM (windows\system32\scrrun.dll)
        /// ref: http://www.codeproject.com/KB/files/createdirectorymethod.aspx
        /// </summary>
        /// <param name="path"></param>
        public static void CreateDirectory(string path)
        {
            // trim leading \ character

            try
            {
                //first check if already exists
                if (DoesPathExist(path))
                {
                    return;
                }


                path = path.TrimEnd(Path.DirectorySeparatorChar);
                // check if folder exists, if yes - no work to do

                if (!Directory.Exists(path))
                {
                    int i = path.LastIndexOf(Path.DirectorySeparatorChar);
                    // find last\lowest folder name

                    string CurrentDirectoryName = path.Substring(i + 1, path.Length - i - 1);
                    // find parent folder of the last folder

                    string ParentDirectoryPath = path.Substring(0, i);
                    // recursive calling of function to create all parent folders

                    CreateDirectory(ParentDirectoryPath);
                    // create last folder in current path
                    DirectoryInfo dirInfo = new DirectoryInfo(ParentDirectoryPath);
                    dirInfo.CreateSubdirectory(CurrentDirectoryName);

                    //Scripting.Folder folder = fso.GetFolder( ParentDirectoryPath );
                    //folder.SubFolders.Add( CurrentDirectoryName );
                }
            } catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".CreateDirectory(" + path + ")");
            }
        }
Beispiel #3
0
        } //

        public static decimal GetAppKeyValue(string keyName, decimal defaultValue)
        {
            decimal appValue = -1;

            try
            {
                var dv = GetAppKeyValue(keyName, "");
                appValue = decimal.Parse(dv);

                // If we get here, then number is an decimal, otherwise we will use the default
            }
            catch
            {
                appValue = defaultValue;
                if (HasMessageBeenPreviouslySent(keyName) == false)
                {
                    LoggingHelper.LogError(string.Format("@@@@ Error on appKey: {0},  using default of: {1}", keyName, defaultValue));
                }
            }

            return(appValue);
        } //
        }         //

        /// <summary>
        /// Return true if the passed path exists
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool DoesPathExist(string path)
        {
            if (path == null)
            {
                return(false);
            }

            try
            {
                if (Directory.Exists(path))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            } catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".DoesPathExist(" + path + ")");
                return(false);
            }
        }
        } //

        /// <summary>
        /// Gets the value of an application key from web.config. Returns the default value if not found
        /// </summary>
        /// <remarks>This property is explicitly thread safe.</remarks>
        public static string GetAppKeyValue(string keyName, string defaultValue)
        {
            string appValue = "";

            try
            {
                appValue = System.Configuration.ConfigurationManager.AppSettings[keyName];
                if (appValue == null)
                {
                    appValue = defaultValue;
                }
            }
            catch
            {
                appValue = defaultValue;
                if (HasMessageBeenPreviouslySent(keyName) == false)
                {
                    LoggingHelper.LogError(string.Format("@@@@ Error on appKey: {0},  using default of: {1}", keyName, defaultValue));
                }
            }

            return(appValue);
        } //
        /// <summary>
        /// Check if file exists on server
        /// </summary>
        /// <param name="documentFolder"></param>
        /// <param name="fileName"></param>
        public static bool DoesFileExist(string pathAndFileName)
        {
            if (pathAndFileName == null || pathAndFileName == null)
            {
                return(false);
            }

            try
            {
                if (System.IO.File.Exists(pathAndFileName))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            } catch (Exception ex)
            {
                LoggingHelper.LogError(ex, thisClassName + ".DoesFileExist() - Unexpected error encountered while retrieving document. File: " + pathAndFileName);

                return(false);
            }
        }        //
        private static bool PostRequest(string postBody, string serviceUri)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.
                    Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


                    var task = client.PostAsync(serviceUri,
                                                new StringContent(postBody, Encoding.UTF8, "application/json"));
                    task.Wait();
                    var response = task.Result;

                    return(response.IsSuccessStatusCode);
                }
            }
            catch (Exception exc)
            {
                LoggingHelper.LogError(exc, "Factories.EmailManager.PostRequest");
                return(false);
            }
        }
        /// <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>
        /// 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);
        }         //
Beispiel #10
0
        /// <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
            }
        } //