private void CreateReport(ReportInformation reportInformation)
        {
            string filePath = null;

            try
            {
                if (!_fileProcessor.DirectoryExists(ReportFolderPath))
                {
                    _fileProcessor.DirectoryCreate(ReportFolderPath);
                }

                filePath = GeneratorHelper.GetFilePathFormatted(
                    ReportFolderPath,
                    ReportFileNameFormat,
                    reportInformation.FeedId.ToString(),
                    reportInformation.FeedRunId.HasValue ? reportInformation.FeedRunId.Value.ToString() : "0",
                    reportInformation.ExecutionStartTime.ToString("yyyy-MM-dd_hh-mm-ss-fff"));

                using (var fileStream = _fileProcessor.FileCreate(filePath))
                {
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {
                        using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        {
                            var serializer = new JsonSerializer();
                            serializer.NullValueHandling = NullValueHandling.Ignore;
                            serializer.Serialize(jsonWriter, reportInformation);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.Error(ex, string.Format("Failed to create a report for {0}", filePath));
            }
        }
        /// <summary>
        /// Sends the notification.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <param name="alarm">The alarm.</param>
        /// <param name="globalProperties">The global properties.</param>
        /// <param name="notifications">The notifications.</param>
        /// <returns></returns>
        public bool SendNotification(BizTalkEnvironment environment, Common.Alarm alarm, string globalProperties, Dictionary <MonitorGroupTypeName, MonitorGroupData> notifications)
        {
            try
            {
                LoggingHelper.Info("DESCRIPTION " + alarm.Description);
                XDocument globalDocument = XDocument.Parse(globalProperties);
                XDocument alarmDocument  = XDocument.Parse(alarm.AlarmProperties);

                //Read configured properties
                XNamespace bsd              = XNamespace.Get("http://www.biztalk360.com/alarms/notification/basetypes");
                string     email            = string.Empty;
                string     emailTo          = string.Empty;
                string     ccEmail          = string.Empty;
                string     upAlert          = string.Empty;
                string     autoCorrectAlert = string.Empty;

                //Global Properties
                XDocument globalProps = XDocument.Load(new StringReader(globalProperties));

                foreach (XElement element in globalProps.Descendants(bsd + "TextArea"))
                {
                    XAttribute xAttribute = element.Attribute("Name");
                    if (element.Attribute("Name").Value == "Email-To")
                    {
                        emailTo = element.Attribute("Value").Value;
                    }
                    if (element.Attribute("Name").Value == "C-C")
                    {
                        ccEmail = element.Attribute("Value").Value;
                    }
                    if (element.Attribute("Name").Value == "Up-Alert")
                    {
                        upAlert = element.Attribute("Value").Value;
                    }
                    if (element.Attribute("Name").Value == "AutoCorrect-Alert")
                    {
                        autoCorrectAlert = element.Attribute("Value").Value;
                    }
                }
                bool useEmailTo = Convert.ToBoolean(globalDocument.XPathSelectElement(
                                                        "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'CheckBox' and @Name = 'use-Email-To']")
                                                    ?.Attribute("Value")?.Value);

                BT360Helper helper = new BT360Helper(notifications, environment, alarm, MessageType.ConsolidatedMessage, MessageFormat.Text);

                EmailMessageBody emailMessageBody = (EmailMessageBody)helper.ConvertDictionaryToObject <EmailMessageBody>(alarm.AdditionalProperties, SMTPConfigurationInfo.EmailMessageBody);
                EmailAttachments emailAttachments = (EmailAttachments)helper.ConvertDictionaryToObject <EmailAttachments>(alarm.AdditionalProperties, SMTPConfigurationInfo.EmailAttachments);
                SMTPSetting      smtpSetting      = (SMTPSetting)helper.ConvertDictionaryToObject <SMTPSetting>(alarm.AdditionalProperties, SMTPConfigurationInfo.SMTPSetting);
                if (smtpSetting == null)
                {
                    throw new Exception("SMTP Setting is not present in the database. Please use the UI to update the correct setting.");
                }

                //When installed first time, these values will be blank
                if (smtpSetting.serverName == "" || smtpSetting.adminEmailAddress == "")
                {
                    //SK: 4th Feb 2012, replaced returning null with exception, since we can't proceed further.
                    throw new Exception("SMTP Setting is not configured (admin email or server name is blank). Please use the UI to update the correct setting.");
                    //return null;
                }
                switch (emailMessageBody.notificationType)
                {
                case NotificationType.UpAlert:
                    if (upAlert != "" && useEmailTo)
                    {
                        email = upAlert;
                    }
                    else
                    {
                        email = emailTo;
                    }
                    break;

                case NotificationType.AutoCorrectAlert:
                    if (autoCorrectAlert != "" && useEmailTo)
                    {
                        email = autoCorrectAlert;
                    }
                    else
                    {
                        email = emailTo;
                    }
                    break;

                default:
                    email = emailTo;
                    break;
                }

                string strFrom    = emailMessageBody.fromEmailAddress;
                string strName    = emailMessageBody.fromDisplayName;
                string strTo      = email;
                string strCC      = ccEmail;
                string strSubject = emailMessageBody.subject;
                string strBody    = emailMessageBody.xmlData;
                LoggingHelper.Info("SUBJECT " + strSubject);
                try
                {
                    SmtpClient smtp = new SmtpClient();

                    smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                    smtp.Host                  = smtpSetting.serverName;
                    smtp.Port                  = Convert.ToInt32(smtpSetting.port);
                    smtp.EnableSsl             = (smtpSetting.sslMode == SMTPSSLMode.DedicatedSSLPort) ? true : false;
                    smtp.UseDefaultCredentials = (smtpSetting.authentication == SMTPAuthentication.IntegratedWindowsAuthOverNtlm) ? true : false;
                    smtp.Credentials           = (smtpSetting.authentication == SMTPAuthentication.Anonymous) ? null : new NetworkCredential(smtpSetting.userName, smtpSetting.password);

                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                    string      htmlData    = Helper.TransformXMLToHTML(emailMessageBody.xslt, emailMessageBody.xmlData);
                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From       = new MailAddress(strFrom, strName);
                    mailMessage.Subject    = strSubject;
                    mailMessage.Body       = htmlData;
                    mailMessage.IsBodyHtml = true;
                    //Adding multiple To Addresses
                    foreach (string sTo in strTo.Split(";".ToCharArray()))
                    {
                        mailMessage.To.Add(sTo);
                    }

                    //Adding multiple CC Addresses
                    if (strCC != string.Empty)
                    {
                        foreach (string sCC in strCC.Split(";".ToCharArray()))
                        {
                            mailMessage.CC.Add(sCC);
                        }
                    }
                    int    attachementCount = 0;
                    double totalSizeInMB    = 0;
                    var    attachmentsOrderedByImportance = emailAttachments.OrderByDescending(issue => issue.importance);

                    foreach (EmailAttachment attachment in attachmentsOrderedByImportance)
                    {
                        string fileName = Path.Combine(emailMessageBody.attachmentFolder, attachment.name);
                        if (File.Exists(fileName))
                        {
                            //Apply maximum size restriction rule
                            FileInfo f        = new FileInfo(fileName);
                            long     filesize = f.Length;
                            double   sizeInMB = (filesize / 1024f) / 1024f;

                            if ((totalSizeInMB + sizeInMB) >= emailMessageBody.maxAttachmentsSizeInMb)
                            {
                                LoggingHelper.Warn(string.Format("The size of the attachment is above the configured limit. Alarm {0}. FileName :{1}. Configured Value :{2}. Current Limit: {3}", alarm.Name, attachment.name, emailMessageBody.maxAttachmentsSizeInMb, totalSizeInMB));
                            }
                            else if (attachementCount >= emailMessageBody.maxAttachments)  //Apply Maximum attachments/email rule
                            {
                                LoggingHelper.Warn(string.Format("Maximum attachments count reached for alarm {0}. Configured Value :{1}. Current Limit: {2}", alarm.Name, emailMessageBody.maxAttachments, attachementCount));
                            }
                            else
                            {
                                mailMessage.Attachments.Add(new Attachment(fileName));
                                totalSizeInMB += sizeInMB; // Attachment Size
                                attachementCount++;        // Attachement Count
                            }
                        }
                        else
                        {
                            LoggingHelper.Warn(string.Format(" Attachment file {0} cannot be found.", attachment));
                        }
                    }


                    MailPriority mailPriority = MailPriority.Normal;
                    switch (alarm.EmailPriority)
                    {
                    case "1":
                        mailPriority = MailPriority.High;
                        break;

                    case "0":
                        mailPriority = MailPriority.Low;
                        break;
                    }
                    mailMessage.Priority = mailPriority;
                    smtp.Send(mailMessage);
                    LoggingHelper.Info("SMTP Notification channel posted the message successfully");
                    return(true);
                }
                catch (Exception ex)
                {
                    LoggingHelper.Error("SMTP Notification channel failed. Error " + ex.Message);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.Error("SMTP Notification channel failed. Error " + ex.Message);
                return(false);
            }
        }
Beispiel #3
0
        public static object CallTBMA(string instrumentid, string setdate, double yield, double cprice, string ytype, bool y2p)
        {
            try
            {
                MA_TBMA_CONFIG config = LookupUIP.GetTBMAConfig(SessionInfo);

                string username, userpassword, token, Key, ErrorMessage;
                username     = config.TBMA_CAL_USERNAME;
                userpassword = config.TBMA_CAL_PASSWORD;
                MA_INSTRUMENT ins = InstrumentUIP.GetByID(SessionInfo, new Guid(instrumentid));
                if (ins == null)
                {
                    throw new Exception("Instrument is not found");
                }

                LoggingHelper.Info("TBMA Calculation Service has been called by " + SessionInfo.UserLogon);

                //Step 1 Create new instant object
                ThaiBMACalc.ThaiBMA_Claculation_Service calc = new ThaiBMACalc.ThaiBMA_Claculation_Service(); //Service Object
                ThaiBMACalc.BondFactor   BF     = new ThaiBMACalc.BondFactor();                               //input object
                ThaiBMACalc.AuthenHeader header = new ThaiBMACalc.AuthenHeader();                             //authen object
                //Step 2 Get token
                Authen.ThaiBMA_Calculation_Auth authen = new Authen.ThaiBMA_Calculation_Auth();
                token = authen.GetToken(username);

                //Step 3 Get Key for access
                Key             = GetKey.getKeyLogin(token, username, userpassword);
                header.key      = Key;
                header.username = username;

                //Step 4 Set auhen value
                calc.AuthenHeaderValue = header;

                //Step 5 Set input value to object
                BF.Symbol           = ins.LABEL;
                BF.SettlementDate   = DateTime.ParseExact(setdate, "dd/MM/yyyy", null);
                BF.TradeDateAndTime = System.DateTime.Now;
                BF.Yield            = yield;
                BF.Percent_Price    = cprice;
                BF.isYield2Price    = y2p;
                BF.isCallPutOption  = false;
                BF.Unit             = 1;
                BF.PriceType        = ThaiBMACalc.PriceType.Clean;

                if (ins.LABEL.StartsWith("ILB"))
                {
                    BF.isILB = true;
                }

                if (ytype == "DM")
                {
                    BF.YieldType = ThaiBMACalc.YieldType.DM;
                }
                else
                {
                    BF.YieldType = ThaiBMACalc.YieldType.YTM;
                }

                //Step 6 Call calc method
                ThaiBMACalc.CalculationOutput result  = calc.BondCalculation(BF);
                ThaiBMACalc.ServiceError      sresult = (ThaiBMACalc.ServiceError)result.ServiceResult;

                //Error while calling service
                if (sresult != null && !sresult.Result)
                {
                    ErrorMessage = sresult.ErrorMessage;
                    string ErrorNo = sresult.ErrorNo;
                    bool   rtn     = sresult.Result;
                    string attime  = sresult.TimeStamp.ToString();
                    LoggingHelper.Error("ThaiBMA service is fail. " + ErrorMessage);
                    return(new { Result = "ERROR", Message = "ThaiBMA service is fail. " + ErrorMessage });
                }

                if ((result.CalcError == null) && (result.CalcResult != null))
                {
                    ThaiBMACalc.CalcResult myResult = (ThaiBMACalc.CalcResult)result.CalcResult;

                    //Calculation Result
                    double RGrossPrice = 0;
                    double RCleanPrice = 0;
                    double RYield      = 0;

                    if (myResult.Symbol.StartsWith("ILB"))
                    {
                        RCleanPrice = (double)myResult.Percent_Unadjusted_CleanPrice;
                        RYield      = (double)myResult.Percent_RealYield;
                        RGrossPrice = (double)myResult.Percent_Unadjusted_GrossPrice;
                    }
                    else
                    {
                        RYield      = ytype == "DM" ? (double)myResult.Percent_DM : (double)myResult.Percent_Yield;
                        RCleanPrice = (double)myResult.Percent_CleanPrice;
                        RGrossPrice = (double)myResult.Percent_GrossPrice;
                    }
                    return(new { Result = "OK", gprice = RGrossPrice, cprice = RCleanPrice, yield = RYield });
                    //.... and more
                }
                else
                {
                    Type error = result.CalcError.GetType();
                    IList <PropertyInfo> props = new List <PropertyInfo>(error.GetProperties());

                    string errmsg = string.Join(",", props.Where(p => p.GetValue(result.CalcError, null).ToString() != "").Select(p => p.GetValue(result.CalcError, null)).ToList());

                    LoggingHelper.Error("ThaiBMA Caculation is fail. " + errmsg);
                    return(new { Result = "ERROR", Message = "ThaiBMA Caculation is fail. " + errmsg });
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.Error("ThaiBMA service is fail. " + ex.Message);
                return(new { Result = "ERROR", Message = ex.Message });
            }
        }
        public void Build(RunType requestedRunType, DateTime?effectiveStartTime = null, DateTime?effectiveEndTime = null)
        {
            try
            {
                NewRelic.Api.Agent.NewRelic.AddCustomParameter("FeedId", FeedId);
                // start report creation
                _reportInformation = new ReportInformation(FeedId)
                {
                    ExecutionStartTime = DateTime.Now,
                    RunType            = requestedRunType,
                    EffectiveEndTime   = effectiveEndTime
                };

                //check if another instance is running - if so exit
                var isProcessRunning = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1;
                if (isProcessRunning)
                {
                    Log.Info("Another instance was running, so exiting the application without any processing.");
                    return;
                }

                Log.Info("Execution started!");
                if (!Runner.IsReady())
                {
                    Log.Info("Runner is not ready for a new run. Exiting the application without executing a new run.");
                    return;
                }

                var feed = FeedService.GetFeed(FeedId);
                _reportInformation.FeedName = feed.Name;
                if (feed.IsPaused)
                {
                    Log.InfoFormat("{0} feed is paused. Exiting application without any processing.", feed.Name);
                    _reportInformation.CustomMessages.Add("Feed is paused. No processing done.");
                    return;
                }

                // First decide if a full run should be enforced.
                var lastSuccessfulRun = FeedRunService.GetLastSuccessfulRun(FeedId);
                var enforceFullRun    = ShouldEnforceFullRun(requestedRunType, lastSuccessfulRun);

                // If incremental run requested, but full run required first (unless forced)
                // then abort as the incremental might be configured for different output
                if (requestedRunType == RunType.Incremental && enforceFullRun)
                {
                    Log.InfoFormat("{0} feed must execute a full run first. Exiting application without any processing.", feed.Name);
                    _reportInformation.CustomMessages.Add("Must execute a full run first. No processing done.");
                    return;
                }

                // Next, need to decide on the effective start time.
                _currentRun = FeedRunService.GetOrCreateActiveFeedRun(FeedId, enforceFullRun, AllowIncrementalRuns);
                _reportInformation.FeedRunId = _currentRun.FeedRunId;
                DateTime?fromTime = null;
                // Only set these values if we aren't in a "real" full run
                if (!enforceFullRun && requestedRunType != RunType.OnDemand)
                {
                    fromTime = GetFromTime(_currentRun);
                    // Effective start time is used for callibrating the fromTime to a previous point in time, in case this is needed due to the execution
                    // sequence/timinig of other processes that impact the data that the inventory feed depends on. For example, if results of an inventory-related
                    // process takes 2 hours to get replicated down to the catalogue/website, where as the inventory data has already been updated in Bronte at
                    // the time of execution AND business has updated rules related to the feed in the past 15 minutes, then gathering the incremental data as
                    // if the run started two hours ago but applying rule changes using "now" as the reference point will yield more "accurate" results.
                    effectiveStartTime = fromTime;
                    if (_currentRun.FeedRunType == FeedRunType.Incremental)
                    {
                        effectiveStartTime = fromTime.Value.AddMinutes(-IncrementalRunBufferTimeLength);
                    }
                }

                _reportInformation.EffectiveStartTime = effectiveStartTime;
                _effectiveExecutionEndTime            = DateTime.Now;

                var runType = _currentRun.FeedRunType == FeedRunType.Incremental ? RunType.Incremental : requestedRunType;
                Runner.Initialize(
                    runType,
                    effectiveStartTime,
                    effectiveEndTime);
                _executionInformation = Runner.Execute();
                UpdateCountersInReport(_executionInformation, runType);

                // Ensure that we kill the watcher here as well
                if (_executionInformation.HasError)
                {
                    _reportInformation.HasErrors = true;
                    LoggingHelper.Error("Execution failed!!! Exiting application without further processing.", Log);
                    HandleExit();
                    return;
                }

                _reportInformation.ExecutionEndTime = DateTime.Now;
                HandleSuccess();

                var elapsedTime = _reportInformation.ExecutionEndTime.Value - _reportInformation.ExecutionStartTime;
                Log.InfoFormat("Execution completed in {0}", elapsedTime.ToString(@"dd\.hh\:mm\:ss"));
            }
            catch (Exception e)
            {
                LoggingHelper.Error(e, "Execution failed!!!", Log);
                _reportInformation.CustomMessages.Add("Exception during execution. See logs for details.");
                HandleExit();
            }
        }
        public bool SendNotification(BizTalkEnvironment environment, Alarm alarm, string globalProperties, Dictionary <MonitorGroupTypeName, MonitorGroupData> notifications)
        {
            try
            {
                XDocument globalDocument = XDocument.Parse(globalProperties);

                string uriString = globalDocument.XPathSelectElement("/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'TextBox' and @Name = 'servicenow-url']")?.Attribute("Value")?.Value;
                string userName  = globalDocument.XPathSelectElement("/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'TextBox' and @Name = 'username']")?.Attribute("Value")?.Value;
                string password  = globalDocument.XPathSelectElement("/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'TextBox' and @Name = 'password']")?.Attribute("Value")?.Value;
                bool   useProxy  = Convert.ToBoolean(globalDocument.XPathSelectElement(
                                                         "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'CheckBox' and @Name = 'use-proxy']")
                                                     ?.Attribute("Value")?.Value);
                bool useDefaultCredentials = Convert.ToBoolean(globalDocument.XPathSelectElement(
                                                                   "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'Group']/*[local-name() = 'CheckBox' and @Name = 'use-default-credentials']")
                                                               ?.Attribute("Value")?.Value);

                WebProxy proxy = new WebProxy();
                if (useProxy)
                {
                    string serverName = globalDocument.XPathSelectElement(
                        "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'Group']/*[local-name() = 'TextBox' and @Name = 'server-name']")
                                        ?.Attribute("Value")?.Value;
                    string domainName = globalDocument.XPathSelectElement(
                        "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'Group']/*[local-name() = 'TextBox' and @Name = 'domain']")
                                        ?.Attribute("Value")?.Value;
                    string portName = globalDocument.XPathSelectElement(
                        "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'Group']/*[local-name() = 'TextBox' and @Name = 'port']")
                                      ?.Attribute("Value")?.Value;
                    string proxyUsername = globalDocument.XPathSelectElement(
                        "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'Group']/*[local-name() = 'TextBox' and @Name = 'user-name']")
                                           ?.Attribute("Value")?.Value;

                    string proxyPassword = globalDocument.XPathSelectElement(
                        "/*[local-name() = 'GlobalProperties']/*[local-name() = 'Section']/*[local-name() = 'Group']/*[local-name() = 'TextBox' and @Name = 'proxy-password']")
                                           ?.Attribute("Value")?.Value;

                    if (!string.IsNullOrEmpty(serverName) && !string.IsNullOrEmpty(portName))
                    {
                        proxy = new WebProxy(serverName, Convert.ToInt32(portName));
                        if (!string.IsNullOrEmpty(proxyUsername) && !string.IsNullOrEmpty(proxyPassword) && !string.IsNullOrEmpty(domainName))
                        {
                            proxy.Credentials = new NetworkCredential(proxyUsername, proxyPassword, domainName);
                        }
                    }

                    if (useDefaultCredentials)
                    {
                        proxy.UseDefaultCredentials = true;
                    }
                }

                XDocument alarmProperties = XDocument.Parse(alarm.AlarmProperties);

                string shortDescription   = alarmProperties.XPathSelectElement("/*[local-name() = 'AlarmProperties']/*[local-name() = 'TextBox' and @Name = 'short-description']").Attribute("Value").Value;
                string impact             = alarmProperties.XPathSelectElement("/*[local-name() = 'AlarmProperties']/*[local-name() = 'TextBox' and @Name = 'impact']").Attribute("Value").Value;
                string urgency            = alarmProperties.XPathSelectElement("/*[local-name() = 'AlarmProperties']/*[local-name() = 'TextBox' and @Name = 'urgency']").Attribute("Value").Value;
                string assignmentgroup    = alarmProperties.XPathSelectElement("/*[local-name() = 'AlarmProperties']/*[local-name() = 'TextBox' and @Name = 'assignment-group']").Attribute("Value").Value;
                string category           = alarmProperties.XPathSelectElement("/*[local-name() = 'AlarmProperties']/*[local-name() = 'TextBox' and @Name = 'category']").Attribute("Value").Value;
                string subcategory        = alarmProperties.XPathSelectElement("/*[local-name() = 'AlarmProperties']/*[local-name() = 'TextBox' and @Name = 'subcategory']").Attribute("Value").Value;
                string configItem         = alarmProperties.XPathSelectElement("/*[local-name() = 'AlarmProperties']/*[local-name() = 'TextBox' and @Name = 'configuration-item']").Attribute("Value").Value;
                string additionalcomments = alarmProperties.XPathSelectElement("/*[local-name() = 'AlarmProperties']/*[local-name() = 'TextBox' and @Name = 'additional-comments']").Attribute("Value").Value;

                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "short_description", shortDescription },
                    { "impact", impact },
                    { "urgency", urgency },
                    { "assignment_group", assignmentgroup },
                    { "category", category },
                    { "subcategory", subcategory },
                    { "cmdb_ci", configItem },
                    { "comments", additionalcomments }
                };

                string incidentMessage = string.Empty + string.Format($"\nAlarm Name: {alarm.Name} \n\nAlarm Desc: {alarm.Description} \n" + "\n----------------------------------------------------------------------------------------------------\n" + $"\nEnvironment Name: {environment.Name} \n\nMgmt Sql Instance Name: { Regex.Escape(environment.MgmtSqlInstanceName)} \nMgmt Sql Db Name: {environment.MgmtSqlDbName}\n" + "\n----------------------------------------------------------------------------------------------------\n");
                foreach (KeyValuePair <MonitorGroupTypeName, MonitorGroupData> keyValuePair in notifications.OrderBy <KeyValuePair <MonitorGroupTypeName, MonitorGroupData>, MonitorGroupTypeName>(n => n.Key))
                {
                    string monitorGroupType = keyValuePair.Key.ToString();
                    LoggingHelper.Debug($"Populate the monitor Status{monitorGroupType}");
                    foreach (MonitorGroup monitorGroup in keyValuePair.Value.monitorGroups)
                    {
                        incidentMessage += string.Format("{0} {1}\n", monitorGroupType, monitorGroup.name);
                        if (monitorGroup.monitors != null)
                        {
                            foreach (Monitor monitor in monitorGroup.monitors)
                            {
                                incidentMessage += string.Format(" - {0} {1}\n", monitor.name, monitor.monitorStatus);
                            }
                        }
                    }
                    foreach (MonitorGroup monitorGroup in keyValuePair.Value.monitorGroups)
                    {
                        if (monitorGroup.monitors != null)
                        {
                            foreach (Monitor monitor in monitorGroup.monitors)
                            {
                                if (monitor.issues != null)
                                {
                                    incidentMessage += string.Format("\n{0} Issues for {1}\n", monitorGroupType, monitor.name);

                                    foreach (Issue issue in monitor.issues)
                                    {
                                        incidentMessage += string.Format(" - {0}\n", issue.description);

                                        if (issue.monitoringErrorDescriptions != null)
                                        {
                                            foreach (MonitorErrorDescription monitorErrorDescription in issue.monitoringErrorDescriptions)
                                            {
                                                incidentMessage += $" {monitorErrorDescription.key} ({monitorErrorDescription.count}) -> {monitorErrorDescription.value} \n";
                                            }
                                        }

                                        if (!string.IsNullOrEmpty(issue.optionalDetails))
                                        {
                                            incidentMessage += string.Format("{0}\n", issue.optionalDetails);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    incidentMessage += "\n";
                }

                dictionary.Add("work_notes", incidentMessage);
                LoggingHelper.Debug($"Successfully added to the Incident Object, Message: {incidentMessage}");

                string content = JsonConvert.SerializeObject((object)dictionary);

                HttpClientHandler handler = new HttpClientHandler()
                {
                    Proxy    = proxy,
                    UseProxy = useProxy
                };
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                using (HttpClient httpClient = new HttpClient(handler))
                {
                    httpClient.BaseAddress = new Uri(uriString);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage result = httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Post, "/api/now/table/incident")
                    {
                        Headers =
                        {
                            Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password))))
                        },
                        Content = new StringContent(content, Encoding.UTF8, "application/json")
                    }).Result;
                    if (result.IsSuccessStatusCode)
                    {
                        LoggingHelper.Info("ServiceNow Incident Creation was Successful");
                    }
                    else
                    {
                        LoggingHelper.Error(string.Format("ServiceNow Incident Creation was Unsuccessful. \n Response: {0}", result));
                    }

                    return(result.IsSuccessStatusCode);
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.Fatal(ex.ToString());
                LoggingHelper.Fatal(ex.StackTrace);
                LoggingHelper.Error(ex.Message);
                return(false);
            }
        }