public override string ParseTemplate(MessageTemplatePart template, ParseTemplateContext context) { var layout = template.Layout; var templateContent = template.Text; var viewBag = context.ViewBag; if (layout != null) { _razorMachine.RegisterLayout("~/shared/_layout.cshtml", layout.Text); templateContent = "@{ Layout = \"_layout\"; }\r\n" + templateContent; } try { // Convert viewBag to string/object pairs if required if (viewBag != null) { if (viewBag is IEnumerable <KeyValuePair <string, string> > ) { viewBag = ((IEnumerable <KeyValuePair <string, string> >)viewBag).Select(x => new KeyValuePair <string, object>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value); } } var tmpl = _razorMachine.ExecuteContent(templateContent, context.Model, viewBag); return(tmpl.Result); } catch (TemplateCompileException ex) { Logger.Log(LogLevel.Error, ex, "Failed to parse the {0} Razor template with layout {1}", template.Title, layout != null ? layout.Title : "[none]"); return(BuildErrorContent(ex, template, layout)); } }
public override string ParseTemplate(TemplatePart template, ParseTemplateContext context) { int versionrecordid = template.Record.ContentItemRecord.Versions.Where(x => x.Published).FirstOrDefault().Id; string key = _shellSettings.Name + versionrecordid.ToString(); // var tr = new RazorTemplateManager(); var layout = template.Layout; var templateContent = template.Text; //var viewBag = context.ViewBag; string layoutString = null; if (layout != null) { key += "_" + template.Layout.Record.ContentItemRecord.Versions.Where(x => x.Published).FirstOrDefault().Id; layoutString = layout.Text; // _razorTemplateManager.AddLayout("Layout" + key, layout.Text); templateContent = "@{ Layout = \"Layout" + key + "\"; }\r\n" + templateContent; } try { var tmpl = _razorTemplateManager.RunString(key, templateContent, context.Model, (Dictionary <string, object>)context.ViewBag, layoutString); return(tmpl); } catch (Exception ex) { Logger.Log(LogLevel.Error, ex, "Failed to parse the {0} Razor template with layout {1}", template.Title, layout != null ? layout.Title : "[none]"); return(BuildErrorContent(ex, template, layout)); } }
public override string ParseTemplate(TemplatePart template, ParseTemplateContext context) { var layout = template.Layout; var templateContent = new StringBuilder(template.Text); //var viewBag = context.ViewBag; if (layout != null) { templateContent = new StringBuilder(layout.Text.Replace(LayoutBeacon, templateContent.ToString())); } //if (viewBag != null) { // var variables = viewBag as IEnumerable<KeyValuePair<string, string>>; // if (variables != null) { // templateContent = variables.Aggregate(templateContent, (current, variable) => current.Replace(string.Format("[{0}]", variable.Key), variable.Value)); // } //} return(templateContent.ToString()); }
/// <summary> /// Sends a contact email. /// </summary> /// <param name="name">The name of the sender.</param> /// <param name="confirmEmail">The email address of the sender.</param> /// <param name="email">The email address entered in by spam bot</param> /// <param name="subject">The email subject.</param> /// <param name="message">The email message.</param> /// <param name="mediaid">The id of the attached file or -1 if no file is provided</param> /// <param name="sendTo">The email address to send the message to.</param> /// <param name="requiredName">Bool of Name is required</param> /// <param name="useStaticSubject">Boolean indicating if a fixed subject must be used for all emails</param> /// <param name="templateId">The id of the mail template or -1 if no template is selected</param> /// <param name="attachFiles">Boolean indicating whether to attach uploaded files (true) or only add their URL to the body of the mail (false)</param> public void SendContactEmail(string name, string confirmEmail, string email, string subject, string message, int mediaid, string sendTo, bool requiredName, bool requiredAttachment = false, bool useStaticSubject = false, int templateId = -1, bool attachFiles = false, object additionalData = null) { if (ValidateContactFields(name, email, message, requiredName, (mediaid != -1), requiredAttachment)) { if (string.IsNullOrEmpty(name)) { name = email; } var host = string.Format("{0}://{1}{2}", _orchardServices.WorkContext.HttpContext.Request.Url.Scheme, _orchardServices.WorkContext.HttpContext.Request.Url.Host, _orchardServices.WorkContext.HttpContext.Request.Url.Port == 80 ? string.Empty : ":" + _orchardServices.WorkContext.HttpContext.Request.Url.Port); var smtpSettings = _orchardServices.WorkContext.CurrentSite.As <SmtpSettingsPart>(); var smtpLogger = new SmtpLogger(); ((Component)_messageManager).Logger = smtpLogger; if (smtpSettings != null && smtpSettings.IsValid()) { var mailClient = BuildSmtpClient(smtpSettings); var contactFormSettings = _orchardServices.WorkContext.CurrentSite.As <ContactFormSettingsPart>().Record; if (confirmEmail != email) { // This option allows spam to be sent to a separate email address. if (contactFormSettings.EnableSpamEmail && !string.IsNullOrEmpty(contactFormSettings.SpamEmail)) { try { MediaPart mediaData = new MediaPart(); if (mediaid != -1) { mediaData = _contentManager.Get(mediaid).As <MediaPart>(); } var body = "<strong>" + name + "</strong><hr/>" + "<br/><br/><div>" + message + "</div>"; if (mediaid != -1 && !attachFiles) { body += "<div><a href=\"" + host + mediaData.MediaUrl + "\">" + T("Attachment") + "</a></div>"; } var data = new Dictionary <string, object>(); data.Add("Recipients", sendTo); data.Add("ReplyTo", email); data.Add("Subject", subject); data.Add("Body", body); if (mediaid != -1 && attachFiles) { data.Add("Attachments", new string[] { _orchardServices.WorkContext.HttpContext.Server.MapPath(mediaData.MediaUrl) }); } _messageManager.Process(data); string spamMessage = string.Format(T("Your message was flagged as spam. If you feel this was in error contact us directly at: {0}").Text, sendTo); _notifier.Information(T(spamMessage)); } catch (Exception e) { Logger.Error(e, T("An unexpected error while sending a contact form message flagged as spam to {0} at {1}").Text, contactFormSettings.SpamEmail, DateTime.Now.ToLongDateString()); string errorMessage = string.Format(T("Your message was flagged as spam. If you feel this was in error contact us directly at: {0}").Text, sendTo); _notifier.Error(T(errorMessage)); } } else { _notifier.Error(T("'Confirm email' and 'Email' does not match. Please retry.")); } } else { try { if (templateId > 0) { ParseTemplateContext templatectx = new ParseTemplateContext(); var template = _templateServices.GetTemplate(templateId); var urlHelper = new UrlHelper(_orchardServices.WorkContext.HttpContext.Request.RequestContext); string mailSubject = ""; if (useStaticSubject && !String.IsNullOrWhiteSpace(template.Subject)) { mailSubject = template.Subject; } else { mailSubject = subject; } MediaPart mediaData = new MediaPart(); if (mediaid != -1) { mediaData = _contentManager.Get(mediaid).As <MediaPart>(); } dynamic model = new { SenderName = name, SenderEmail = email, Subject = mailSubject, Message = message, AttachmentUrl = (mediaid != -1 ? host + mediaData.MediaUrl : ""), AdditionalData = additionalData }; // Creo un model che ha Content (il contentModel), Urls con alcuni oggetti utili per il template // Nel template pertanto Model, diventa Model.Content templatectx.Model = model; var body = _templateServices.ParseTemplate(template, templatectx); var data = new Dictionary <string, object>(); data.Add("Recipients", sendTo); data.Add("ReplyTo", email); data.Add("Subject", mailSubject); data.Add("Body", body); if (mediaid != -1 && attachFiles) { data.Add("Attachments", new string[] { _orchardServices.WorkContext.HttpContext.Server.MapPath(mediaData.MediaUrl) }); } _messageManager.Process(data); } else { MediaPart mediaData = new MediaPart(); if (mediaid != -1) { mediaData = _contentManager.Get(mediaid).As <MediaPart>(); } var body = "<strong>" + name + "</strong><hr/>" + "<br/><br/><div>" + message + "</div>"; if (mediaid != -1 && !attachFiles) { body += "<div><a href=\"" + host + mediaData.MediaUrl + "\">" + T("Attachment") + "</a></div>"; } var data = new Dictionary <string, object>(); data.Add("Recipients", sendTo); data.Add("ReplyTo", email); data.Add("Subject", subject); data.Add("Body", body); if (mediaid != -1 && attachFiles) { data.Add("Attachments", new string[] { _orchardServices.WorkContext.HttpContext.Server.MapPath(mediaData.MediaUrl) }); } _messageManager.Process(data); } if (!string.IsNullOrWhiteSpace(smtpLogger.ErrorMessage)) { throw new Exception(smtpLogger.ErrorMessage, smtpLogger.Exception); } Logger.Debug(T("Contact form message sent to {0} at {1}").Text, sendTo, DateTime.Now.ToLongDateString()); _notifier.Information(T("Operation completed successfully.")); //_notifier.Information(T("Thank you for your inquiry, we will respond to you shortly.")); } catch (Exception e) { Logger.Error(e, T("An unexpected error while sending a contact form message to {0} at {1}").Text, sendTo, DateTime.Now.ToLongDateString()); var errorMessage = string.Format(T("An unexpected error occured when sending your message. You may email us directly at: {0}").Text, sendTo); _notifier.Error(T(errorMessage)); throw new System.Exception(errorMessage); } } } else { string errorMessage = string.Format(T("Our email server isn't configured. You may email us directly at: {0}").Text, sendTo); _notifier.Error(T(errorMessage)); throw new System.Exception(errorMessage); } } else { _notifier.Error(T(validationError)); throw new System.Exception(T(validationError).Text); } }
public abstract string ParseTemplate(MessageTemplatePart template, ParseTemplateContext context);