public static string GetMessageBody(string maName, string triggerType, string triggerDetails, DateTime errorTime, bool hasTerminated, Exception ex) { StringBuilder builder = new StringBuilder(); builder.AppendFormat(MessageBuilder.GetTemplate("TriggerErrorFragment"), maName, triggerType, triggerDetails, errorTime, hasTerminated ? "Yes" : "No", ex); InlineResult result = PreMailer.Net.PreMailer.MoveCssInline(MessageBuilder.GetTemplate("EmailTemplate").Replace("%BODY%", builder.ToString())); return(result.Html); }
public static string GetMessageBody(RunDetails r, string thresholdMessage) { StringBuilder builder = new StringBuilder(); if (thresholdMessage != null) { builder.AppendFormat(MessageBuilder.GetTemplate("ThresholdExceededFragment"), r.RunProfileName, r.MAName, r.StartTime, r.EndTime, r.SecurityID, r.LastStepStatus, r.RunNumber, thresholdMessage); } else { builder.AppendFormat(MessageBuilder.GetTemplate("RunSummaryFragment"), r.RunProfileName, r.MAName, r.StartTime, r.EndTime, r.SecurityID, r.LastStepStatus, r.RunNumber); } builder.AppendFormat(MessageBuilder.GetTemplate("StepTableFragment"), MessageBuilder.BuildStepDetails(r.StepDetails)); string stagingErrors = MessageBuilder.BuildStagingErrorDetails(r.StepDetails); if (stagingErrors != null) { builder.AppendLine(stagingErrors); } string importErrors = MessageBuilder.BuildImportErrorDetails(r.StepDetails); if (importErrors != null) { builder.AppendLine(importErrors); } string exportErrors = MessageBuilder.BuildExportErrorDetails(r.StepDetails); if (exportErrors != null) { builder.AppendLine(exportErrors); } string syncErrors = MessageBuilder.BuildSyncErrorDetails(r.StepDetails); if (syncErrors != null) { builder.AppendLine(syncErrors); } InlineResult result = PreMailer.Net.PreMailer.MoveCssInline(MessageBuilder.GetTemplate("EmailTemplate").Replace("%BODY%", builder.ToString())); return(result.Html); }
/// <summary> /// 產生 Email 的 Html 內容 /// </summary> /// <param name="viewName">View 名稱</param> /// <param name="model"></param> /// <returns></returns> private string GenerateMailBody(string viewName, object model) { // Note: Use HostingEnvironment.MapPath(path) on ASP.Net project string emailViewDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Views\Emails\"); // Prepare Viewbag dynamic viewBag = new DynamicViewBag(); viewBag.WebsiteUrl = GlobalConfig.WebsiteUrl; viewBag.WebsiteName = GlobalConfig.WebsiteName; // Generate HTML string html = Engine.Razor.RunCompile(viewName, null, model, (DynamicViewBag)viewBag); // Inline CSS InlineResult result = PreMailer.Net.PreMailer.MoveCssInline(new Uri(emailViewDir), html); result.Warnings.ForEach(w => System.Diagnostics.Debug.WriteLine(w)); return(result.Html); }
/// <summary> /// Send mail to mailreceivers using Mailgun REST API /// </summary> /// <param name="mailInfo"></param> /// <param name="recepients">receivers</param> /// <param name="testMode">No mails are sent, generating report for user</param> /// <returns>A html formatted report of the send process</returns> public override SendMailLog SendEmail(MailInformation mailInfo, JobWorkItems recepients, bool testMode) { _log.Debug("Starting Mailgun Send"); // Inline all css InlineResult cssInline = PreMailer.Net.PreMailer.MoveCssInline(mailInfo.BodyHtml); mailInfo.BodyHtml = cssInline.Html; // Base will send SendMailLog log = base.SendEmail(mailInfo, recepients, testMode); // Log any messages, debug is only detected // if we have an HttpContext. if (IsInDebugMode()) { log.WarningMessages.Add("Premailer CSS warning messages are only shown in debug mode. Primarily for developers."); log.WarningMessages.AddRange(cssInline.Warnings.ToArray()); } _log.Debug("Ending Mailgun Send"); // return report return(log); }
public static void CreateHtmlReport(string htmlFilename, bool zipRequired, bool logoUpload, bool sauceFlag, bool isSummaryRequiredInResults, bool isGrid, bool callFromKryptonVbScriptGrid, bool creatHtmlReport) { Property.TotalCaseExecuted = 0; Property.TotalCasePass = 0; Property.TotalCaseFail = 0; Property.TotalCaseWarning = 0; Property.TotalStepExecuted = 0; Property.TotalStepFail = 0; Property.TotalStepPass = 0; Property.TotalStepWarning = 0; FileInfo oFileInfo = new FileInfo(Assembly.GetExecutingAssembly().Location); if (oFileInfo.Directory != null) { string templatePath = Path.Combine(oFileInfo.Directory.FullName, "ReportTemplate"); string reportTemplate = Path.Combine(templatePath, "HtmlReportTemplate.htm"); StreamReader sr = new StreamReader(reportTemplate); string htmlReportTemplate = sr.ReadToEnd(); sr.Close(); string parentRow = Path.Combine(templatePath, "ParentRow.htm"); sr = new StreamReader(parentRow); string parentRowTemplate = sr.ReadToEnd(); sr.Close(); if (string.IsNullOrWhiteSpace(htmlFilename)) { htmlFilename = "HtmlReport.html"; } Property.Time = "HH:mm:ss"; DateTime executionStartTime = DateTime.Now; DateTime executionEndTime = DateTime.Now; DateTime currentTime = executionEndTime; string[] xmlFilesLocation = LogFile.AllXmlFilesLocation.Split(';'); string htmlFileLocation = Property.HtmlFileLocation + "/" + htmlFilename; Property.FinalExecutionStatus = ExecutionStatus.Pass; int count = 0; StringBuilder sbHtml = new StringBuilder(); StringBuilder sbSummaryHtml = new StringBuilder(); StringBuilder sbInlineHtml = new StringBuilder(); //Somtimes if multiple testcases are running then browser name comes blank after first test case. So set same browser name for next textcases too. string lastBrowserName = string.Empty; foreach (string xmlLocation in xmlFilesLocation) { string tcName = string.Empty; string tcId = string.Empty; string tcBrowser = string.Empty; string tcMachine = string.Empty; string tcStartTime = string.Empty; string tcEndTime = string.Empty; string tcDuration = string.Empty; if (File.Exists(xmlLocation)) { count++; var rootFolderExt = Property.DateTime; Property.TotalCaseExecuted++; DataTable dtTemp = null; try { DataSet dsStore = new DataSet(); // copying all data from XML to datatable dsStore.ReadXml(xmlLocation); dtTemp = dsStore.Tables[0]; // getting TestCase Name and ID from extended properties if (dtTemp.ExtendedProperties["TestCase Name"] != null) { tcName = dtTemp.ExtendedProperties["TestCase Name"].ToString(); } if (dtTemp.ExtendedProperties["TestCase Id"] != null) { tcId = dtTemp.ExtendedProperties["TestCase Id"].ToString(); } if (dtTemp.ExtendedProperties["Browser"] != null) { tcBrowser = dtTemp.ExtendedProperties["Browser"].ToString(); } if (dtTemp.ExtendedProperties["RCMachineId"] != null) { tcMachine = dtTemp.ExtendedProperties["RCMachineId"].ToString(); } //Extract date/time information from xml files if (dtTemp.ExtendedProperties["ExecutionEndTime"] != null) { tcEndTime = dtTemp.ExtendedProperties["ExecutionEndTime"].ToString(); } if (dtTemp.ExtendedProperties["ExecutionStartTime"] != null) { tcStartTime = dtTemp.ExtendedProperties["ExecutionStartTime"].ToString(); } if (dtTemp.ExtendedProperties["ExecutionDuration"] != null) { tcDuration = dtTemp.ExtendedProperties["ExecutionDuration"].ToString(); } } catch (Exception e) { Console.WriteLine(e.Message); } try { DateTime xmlStartTime = DateTime.ParseExact(tcStartTime, Property.Date_Time, null); DateTime xmlEndTime = DateTime.ParseExact(tcEndTime, Property.Date_Time, null); //Set start time if (executionStartTime > xmlStartTime) { executionStartTime = xmlStartTime; } //Set end time if ((xmlEndTime > executionEndTime) || (executionEndTime.Equals(currentTime))) { executionEndTime = xmlEndTime; } } catch { // ignored } string tempParentRow = parentRowTemplate; tempParentRow = tempParentRow.Replace("$RowId$", "RowId" + count); tempParentRow = tempParentRow.Replace("$Row-Childs-Id$", "RowChildsId" + count); tempParentRow = tempParentRow.Replace("$TestCaseId$", tcId); if (tcName.Trim().Length > 0) { tempParentRow = tempParentRow.Replace("$TestCaseName$", " - " + tcName); } else { tempParentRow = tempParentRow.Replace("$TestCaseName$", string.Empty); } if (tcBrowser.Trim().Length > 0) { lastBrowserName = tcBrowser; } tempParentRow = tempParentRow.Replace("$Browser$", lastBrowserName); tempParentRow = tempParentRow.Replace("$Machine$", tcMachine); tempParentRow = tcDuration.Trim().Length == 0 ? tempParentRow.Replace("$TotalTestcaseDuration$", dtTemp.Rows[0][3] + " : " + dtTemp.Rows[0][4]) : tempParentRow.Replace("$TotalTestcaseDuration$", tcDuration); string headerRemarkFail = string.Empty; string headerRemarkWarning = string.Empty; string finalStatus = ExecutionStatus.Pass; string childRows = GetChildRowsHtml(dtTemp, rootFolderExt, ref finalStatus, ref headerRemarkFail, ref headerRemarkWarning); tempParentRow = tempParentRow.Replace("$FinalStatus$", finalStatus); if (finalStatus == ExecutionStatus.Fail) { tempParentRow = tempParentRow.Replace("$Remarks$", headerRemarkFail); tempParentRow = tempParentRow.Replace("$FinalStatusClass$", "Fail"); Property.TotalCaseFail++; Property.ExecutionFailReason = headerRemarkFail; } else if (finalStatus == ExecutionStatus.Pass) { tempParentRow = tempParentRow.Replace("$Remarks$", string.Empty); tempParentRow = tempParentRow.Replace("$FinalStatusClass$", "Pass"); Property.TotalCasePass++; } else { tempParentRow = tempParentRow.Replace("$Remarks$", headerRemarkWarning); tempParentRow = tempParentRow.Replace("$FinalStatusClass$", "Warning"); Property.TotalCaseWarning++; } string parentRowComplete = tempParentRow.Replace("$HTMLChildRows$", childRows); sbHtml.Append(parentRowComplete); string inlineHtml = parentRowComplete; sbInlineHtml.Append(RemoveExpandIcon(inlineHtml, "[" + count + "]", true)); //Remove child which include step actions. string tempParentSummaryRow = tempParentRow; string rowDeliminetor = "</tr>"; int index = tempParentSummaryRow.IndexOf(rowDeliminetor, StringComparison.Ordinal); tempParentSummaryRow = tempParentSummaryRow.Substring(0, index + rowDeliminetor.Length); sbSummaryHtml.Append(RemoveExpandIcon(tempParentSummaryRow, "[" + count + "]", false)); } using (StreamWriter sw = new StreamWriter(Property.ErrorLog)) { sw.WriteLine(count); } } using (StreamWriter sw = new StreamWriter(Property.ErrorLog)) { sw.WriteLine("Foreach end of HTMlReport.."); } htmlReportTemplate = htmlReportTemplate.Replace("$KryptonVersion$", Property.KryptonVersion); htmlReportTemplate = htmlReportTemplate.Replace("$projectname$", Utility.GetParameter("ProjectName").Trim()); htmlReportTemplate = htmlReportTemplate.Replace("$TestSuitName$", Utility.GetParameter("TestSuite").Trim()); htmlReportTemplate = htmlReportTemplate.Replace("$Environment$", Utility.GetParameter(Property.Environment)); htmlReportTemplate = htmlReportTemplate.Replace("$ExecutionStartedAt$", Property.ExecutionStartDateTime); htmlReportTemplate = htmlReportTemplate.Replace("$ExecutionFinishedAt$", Property.ExecutionEndDateTime); TimeSpan time = executionEndTime - executionStartTime; htmlReportTemplate = htmlReportTemplate.Replace("$TotalDuration$", time.ToString()); htmlReportTemplate = htmlReportTemplate.Replace("$TestCase(s)Executed$", Property.TotalCaseExecuted.ToString()); htmlReportTemplate = htmlReportTemplate.Replace("$TotalPassed$", Property.TotalCasePass.ToString()); htmlReportTemplate = htmlReportTemplate.Replace("$TotalFailed$", Property.TotalCaseFail.ToString()); htmlReportTemplate = htmlReportTemplate.Replace("$TotalWarning$", Property.TotalCaseWarning.ToString()); htmlReportTemplate = htmlReportTemplate.Replace("$CompanyLogo$", ImageToBase64(Property.CompanyLogo)); string finalHtmlReportTemplate = htmlReportTemplate.Replace("$TableBody$", sbHtml.ToString()); if (creatHtmlReport) { WriteInFile(htmlFileLocation, finalHtmlReportTemplate); } string inlineHtmlTemplate = RemoveImagesAndHeader(htmlReportTemplate.Replace("$TableBody$", sbInlineHtml.ToString())); InlineResult inlineCss1 = PreMailer.Net.PreMailer.MoveCssInline(inlineHtmlTemplate); if (isGrid) { WriteInFile(htmlFileLocation.Replace(".html", "smail.html"), inlineCss1.Html); } else { WriteInFile(htmlFileLocation.Replace(".html", "mail.html"), inlineCss1.Html); // only used for sending mail through krypton } string htmlSummaryReportTemplate = htmlReportTemplate; htmlSummaryReportTemplate = htmlSummaryReportTemplate.Replace("$TableBody$", sbSummaryHtml.ToString()); htmlFileLocation = htmlFileLocation.Replace(".html", "s.html"); #region if (isSummaryRequiredInResults && creatHtmlReport) { WriteInFile(htmlFileLocation, htmlSummaryReportTemplate); } #endregion // created in result folder with logo and report header #region htmlSummaryReportTemplate = RemoveImagesAndHeader(htmlSummaryReportTemplate); InlineResult inlineCss3 = PreMailer.Net.PreMailer.MoveCssInline(htmlSummaryReportTemplate); Property.ReportSummaryBody = inlineCss3.Html; if (callFromKryptonVbScriptGrid) { WriteInFile(htmlFileLocation, inlineCss3.Html); } #endregion // for Mail Summary and Existing Grid body without logo and report header if (zipRequired) //if ziprequied flag is ture then create zip file with all images and html file { CreateZip(xmlFilesLocation); } } }
private static (string, MinifyResult) Minify(string input, bool usePreMailer) { var headers = new List <string>(); while (true) { if (input.StartsWith("@")) { var index = input.IndexOf(Environment.NewLine); if (index == -1) { break; } var lastChar = input[index - 1]; if (lastChar == '{' || lastChar == '}') { break; } var content = input.Substring(0, index); input = input.Remove(0, index + 2); headers.Add(content); } else { var match = _singleEmptyLineRegex.Match(input); if (match.Success) { input = input.Remove(0, match.Length); } else { break; } } } InlineResult inlineResult = null; if (usePreMailer) { inlineResult = PreMailer.Net.PreMailer.MoveCssInline(input, stripIdAndClassAttributes: true); input = inlineResult.Html; } input = _multiLineCommentRegex.Replace(input, string.Empty); input = _emptyLineRegex.Replace(input, string.Empty); var indexOffset = 0; foreach (Match match in _razorSectionRegex.Matches(input)) { input = input.Insert(match.Index + indexOffset, Environment.NewLine); indexOffset += Environment.NewLine.Length; } indexOffset = 0; foreach (Match match in _razorFunctionsRegex.Matches(input)) { input = input.Insert(match.Index + indexOffset, Environment.NewLine); indexOffset += Environment.NewLine.Length; } foreach (var header in System.Linq.Enumerable.Reverse(headers)) { input = string.Concat(header, Environment.NewLine, input); } return(input, new MinifyResult { Success = inlineResult is null || (inlineResult != null && inlineResult.Warnings.Count == 0), Message = inlineResult is null ? null : string.Join(", ", inlineResult.Warnings) }); }
/// <summary> /// /// </summary> /// <param name="mailInfo"></param> /// <param name="recepients">receivers</param> /// <param name="testMode">No mails are sent, generating report for user</param> /// <returns>A html formatted report of the send process</returns> public override SendMailLog SendEmail(MailInformation mailInfo, JobWorkItems recepients, bool testMode) { _log.Debug("Starting Send"); // for logging SendMailLog log = new SendMailLog(); // Need someone to send to if (recepients.Items.Count == 0) { _log.Error("Trying to send newsletter with an empty JobWorkCollection. Please check the collection before attemting to send mail."); throw new ArgumentNullException("recepients", "Recipient collection is empty, there is no recipients to send to."); } // And, we need a sender address if (string.IsNullOrEmpty(mailInfo.From)) { _log.Error("Missing from address."); throw new ArgumentNullException("mailInfo", "Missing from address."); } // Inline all css PreMailer.Net.PreMailer preMailer = new PreMailer.Net.PreMailer(mailInfo.BodyHtml); if (mailInfo.Utm.HasValidUtmCode) { preMailer.AddAnalyticsTags(mailInfo.Utm.Source, mailInfo.Utm.Medium, mailInfo.Utm.Campaign, mailInfo.Utm.Content); } InlineResult cssInline = preMailer.MoveCssInline(); mailInfo.BodyHtml = cssInline.Html; // Log any messages, debug is only detected // if we have an HttpContext. if (IsInDebugMode()) { log.WarningMessages.Add("Premailer CSS warning messages are only shown in debug mode. Primarily for developers."); log.WarningMessages.AddRange(cssInline.Warnings.ToArray()); } // Loop through receivers collection, add to collection and send // one email per batch size. int batchRun = 0; int batchSize = GetBatchSize(); do { IEnumerable <JobWorkItem> workItems = recepients.Skip(batchRun * batchSize).Take(batchSize); int numberofItemsToSend = workItems.Count(); if (numberofItemsToSend == 0) { break; } batchRun++; try { if (SendMailBatch(mailInfo, workItems, testMode)) { // Mark each item as sent foreach (JobWorkItem workItem in workItems) { log.SuccessMessages.Add(workItem.EmailAddress); // Update status and save it workItem.Status = JobWorkStatus.Complete; // Only save if real work item (could be a test item) if (workItem.JobId > 0) { workItem.Save(); } } } } catch (Exception ex) { _log.Error(string.Format("Error sending batch (to {0} recipients).", recepients.Count()), ex); string exceptionMsg = ex.Message; log.ErrorMessages.Add(exceptionMsg); // Update work item foreach (JobWorkItem workItem in workItems) { workItem.Status = JobWorkStatus.Failed; if (exceptionMsg.Length >= 2000) { exceptionMsg = exceptionMsg.Substring(0, 1999); } workItem.Info = exceptionMsg; if (workItem.JobId > 0) { workItem.Save(); } } // can't continue break; } } while (true); // Finished log.SendStop = DateTime.Now; _log.Debug("Ending Send"); // return report return(log); }