protected void LoginButton_Click(object sender, EventArgs e) { LoggingHelper.Info("Begin Login....."); string result = LogOn(UserName.Text, Password.Text); LoggingHelper.Info("End Login."); }
protected virtual GivenBlock <object> Given(string description, Action action) { LoggingHelper.Info($"[given] (start) {description}"); action(); LoggingHelper.Info($"[given] (end) {description}"); return(new GivenBlock <object>()); }
public void AllNamespacesStartWithGetcuReoneTestCase() { string beginNamespace = "GetcuReone"; string partNameAssemblies = "MvvmFrame.Wpf"; string[] excludeFiles = new string[] { "Example_MvvmFrame.Wpf.dll", }; Given("Get all file", () => InfrastructureHelper.GetAllFiles(_solutionFolder)) .And("Get all assemblies", files => files.Where(file => file.Name.Contains(".dll"))) .And($"Includ only {partNameAssemblies} assemblies", files => files.Where(file => file.Name.Contains(partNameAssemblies))) .And($"Include only library assemlies", files => files .Where(file => !file.Name.Contains("Tests.dll") && !file.FullName.Contains("TestAdapter.dll") && !file.FullName.Contains("obj") && file.FullName.Contains(_buildConfiguration) && excludeFiles.All(excludeFile => file.Name != excludeFile))) .And($"Exclude duplicate", files => files .DistinctByFunc((x, y) => x.Name == y.Name) .ToList()) .And("Get assembly infos", files => files.Select(file => { LoggingHelper.Info($"test assembly {file.FullName}"); return(Assembly.LoadFrom(file.FullName)); }).ToList()) .When("Get types", assemblies => assemblies.SelectMany(assembly => assembly.GetTypes())) .Then("Check types", types => { var invalidTypes = new List <Type>(); foreach (Type type in types) { if (type.FullName.Length <= beginNamespace.Length) { invalidTypes.Add(type); } else if (!type.FullName.Substring(0, beginNamespace.Length).Equals(beginNamespace, StringComparison.Ordinal)) { invalidTypes.Add(type); } } if (invalidTypes.Count != 0) { Assert.Fail($"Invalid types: \n{string.Join("\n", invalidTypes.ConvertAll(type => type.FullName))}"); } }); }
public void AssembliesHaveMajorVersionTestCase() { string[] includeAssemblies = new string[] { Path.Combine("NugetProject", "bin", _buildConfiguration, "netstandard2.0", "NugetProject.dll"), Path.Combine("JwtTestAdapter", "bin", _buildConfiguration, "netstandard2.0", "JwtTestAdapter.dll"), }; string majorVersion = Environment.GetEnvironmentVariable("majorVersion"); string excpectedAssemblyVersion = majorVersion != null ? $"{majorVersion}.0.0.0" : "1.0.0.0"; string partNameAssemblies = "FactFactory"; Given("Get all file", () => InfrastructureHelper.GetAllFiles(new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.Parent.Parent.Parent)) .And("Get all assemblies", files => files.Where(file => file.Name.Contains(".dll"))) .And($"Includ only {partNameAssemblies} assemblies", files => files.Where(file => file.Name.Contains(partNameAssemblies) || includeAssemblies.Any(inAss => file.FullName.Contains(inAss)))) .And($"Include only library assemlies", files => files .Where(file => !file.FullName.Contains("TestAdapter.dll") && !file.FullName.Contains("obj") && file.FullName.Contains(_buildConfiguration))) .And($"Exclude duplicate", files => files .DistinctByFunc((x, y) => x.Name == y.Name) .ToList()) .When("Get assembly infos", files => files.Select(file => { LoggingHelper.Info($"test assembly {file.FullName}"); return(Assembly.LoadFrom(file.FullName)); }).ToList()) .Then("Checke assembly version", assemblies => { var invalidAssemblies = new List <Assembly>(); foreach (Assembly assembly in assemblies) { if (!assembly.FullName.Contains($"Version={excpectedAssemblyVersion}")) { invalidAssemblies.Add(assembly); } CustomAttributeData attr = assembly.CustomAttributes.SingleOrDefault(attr => attr.AttributeType.Name.Equals(nameof(AssemblyFileVersionAttribute), StringComparison.Ordinal)); if (attr == null || attr.ConstructorArguments.Count == 0 || attr.ConstructorArguments[0].Value == null) { invalidAssemblies.Add(assembly); } else if (!(attr.ConstructorArguments[0].Value is string attrStr)) { invalidAssemblies.Add(assembly); }
public virtual ThenBlock <TResult1> And <TResult1>(string description, Func <TResult, TResult1> func) { LoggingHelper.Info($"[then] (start) {description}"); var then = new ThenBlock <TResult1> { Result = func((TResult)Result) }; LoggingHelper.Info($"[then] (end) {description}"); return(then); }
public virtual ThenBlock <TResult> And(string description, Action <TResult> action) { LoggingHelper.Info($"[then] (start) {description}"); action((TResult)Result); LoggingHelper.Info($"[then] (end) {description}"); return(new ThenBlock <TResult> { Result = Result }); }
protected virtual GivenBlock <TResult> Given <TResult>(string description, Func <TResult> func) { LoggingHelper.Info($"[given] (start) {description}"); var given = new GivenBlock <TResult> { Result = func() }; LoggingHelper.Info($"[given] (end) {description}"); return(given); }
public virtual WhenBlock <TResult1> When <TResult1>(string description, Func <TResult1> func) { LoggingHelper.Info($"[when] (start) {description}"); var when = new WhenBlock <TResult1> { Result = func() }; LoggingHelper.Info($"[when] (end) {description}"); return(when); }
public virtual WhenBlock <TResult> When(string description, Action action) { LoggingHelper.Info($"[when] (start) {description}"); action(); LoggingHelper.Info($"[when] (end) {description}"); return(new WhenBlock <TResult> { Result = Result }); }
public virtual GivenBlock <TResult1> And <TResult1>(string description, Func <TResult1> func) { LoggingHelper.Info($"[given] (start) {description}"); var given = new GivenBlock <TResult1> { Result = func() }; LoggingHelper.Info($"[given] (end) {description}"); return(given); }
public void AllHaveTimeoutTestCase() { string partNameAssemblies = "MvvmFrame.Wpf"; Given("Get all file", () => InfrastructureHelper.GetAllFiles(_solutionFolder)) .And("Get all assemblies", files => files.Where(file => file.Name.Contains(".dll"))) .And($"Includ only {partNameAssemblies} assemblies", files => files.Where(file => file.Name.Contains(partNameAssemblies))) .And($"Include only tests assemlies", files => files .Where(file => file.Name.Contains("Tests.dll") && !file.FullName.Contains("TestAdapter.dll") && !file.FullName.Contains("obj") && file.FullName.Contains(_buildConfiguration)) .ToList()) .And("Get assembly infos", files => files.Select(file => { LoggingHelper.Info($"test assembly {file.FullName}"); return(Assembly.LoadFrom(file.FullName)); }).ToList()) .And("Get types", assemblies => assemblies.SelectMany(assembly => assembly.GetTypes())) .And("Get test classes", types => types.Where(type => type.GetCustomAttribute(typeof(TestClassAttribute)) != null)) .When("Get test methods", typeClasses => { var result = new List <MemberInfo>(); foreach (var cl in typeClasses) { foreach (var method in cl.GetMethods().Where(method => method.GetCustomAttribute(typeof(TestMethodAttribute)) != null)) { result.Add(method); LoggingHelper.Info($"test method {cl.FullName}.{method.Name}()"); } } return(result); }) .Then("Check timeouts", methods => { List <MemberInfo> invalidMethods = methods.Where(method => method.GetCustomAttribute(typeof(TestMethodAttribute)) == null).ToList(); if (invalidMethods.Count != 0) { Assert.Fail("Methods dont have TestMethodAttribute:\n" + string.Join("\n", invalidMethods.Select(method => $"{method.DeclaringType.FullName}.{method.Name}"))); } }); }
public bool SendNotification(BizTalkEnvironment environment, Alarm alarm, string globalProperties, Dictionary <MonitorGroupTypeName, MonitorGroupData> notifications) { try { //Construct Message var message = string.Empty; message += string.Format("\nAlarm Name: {0} \n\nAlarm Desc: {1} \n", alarm.Name, alarm.Description); message += "\n----------------------------------------------------------------------------------------------------\n"; message += string.Format("\nEnvironment Name: {0} \n\nMgmt Sql Instance Name: {1} \nMgmt Sql Db Name: {2}\n", environment.Name, environment.MgmtSqlDbName, environment.MgmtSqlInstanceName); message += "\n----------------------------------------------------------------------------------------------------\n"; // Change the Message Type and Format based on your need. var helper = new BT360Helper(notifications, environment, alarm, MessageType.ConsolidatedMessage, MessageFormat.Text); message += helper.GetNotificationMessage(); //Read configured properties var bsd = XNamespace.Get("http://www.biztalk360.com/alarms/notification/basetypes"); var fileFolder = string.Empty; var folderOverride = string.Empty; //Alarm Properties var almProps = XDocument.Load(new StringReader(alarm.AlarmProperties)); foreach (var element in almProps.Descendants(bsd + "TextBox")) { var xAttribute = element.Attribute("Name"); if (xAttribute == null || xAttribute.Value != "file-override-path") { continue; } var attribute = element.Attribute("Value"); if (attribute != null) { folderOverride = attribute.Value; } } //Global Properties var globalProps = XDocument.Load(new StringReader(globalProperties)); foreach (var element in globalProps.Descendants(bsd + "TextBox")) { var xAttribute = element.Attribute("Name"); if (xAttribute == null || xAttribute.Value != "file-path") { continue; } var attribute = element.Attribute("Value"); if (attribute != null) { fileFolder = attribute.Value; } } //Save to Disk var filePath = string.IsNullOrEmpty(folderOverride) ? fileFolder : folderOverride; var fileLocation = Path.Combine(filePath, Guid.NewGuid() + ".txt"); using (var fs = new FileStream(fileLocation, FileMode.CreateNew)) { fs.Write(Encoding.UTF8.GetBytes(message), 0, message.Length); } LoggingHelper.Info("File notification completed successfully"); return(true); } catch (Exception ex) { LoggingHelper.Info("File notification failed. Error " + ex.Message); return(false); // ignored } }
/// <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); } }
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 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); } }