Exemplo n.º 1
0
        protected override string RenderTemplate(string content, PageContext pageData)
        {
            var serviceConfiguration = new TemplateServiceConfiguration
            {
                TemplateManager  = new IncludesResolver(FileSystem, includesPath),
                BaseTemplateType = typeof(ExtensibleTemplate <>)
            };

            serviceConfiguration.Activator = new ExtensibleActivator(serviceConfiguration.Activator, Filters, Tags);
            Engine.Razor = RazorEngineService.Create(serviceConfiguration);

            content = Regex.Replace(content, "<p>(@model .*?)</p>", "$1");

            try
            {
                return(Engine.Razor.RunCompile(content, pageData.Page.File, typeof(PageContext), pageData));
            }
            catch (Exception e)
            {
                Tracing.Error(@"Failed to render template, falling back to direct content");
                Tracing.Debug(e.Message);
                Tracing.Debug(e.StackTrace);
                return(content);
            }
        }
        public void Issue21_SubclassModelShouldBeSupportedInLayout()
        {
            using (var service = RazorEngineService.Create())
                using (var writer = new StringWriter())
                {
                    const string Parent = "@model RazorEngine.Tests.TestTypes.Person\n<h1>@Model.Forename</h1>@RenderSection(\"Child\")";

                    var key = service.GetKey(nameof(Parent));

                    service.AddTemplate(key, Parent);
                    service.Compile(key);

                    const string child    = "@{ Layout = \"Parent\"; }\n@section Child { <h2>@Model.Department</h2> }";
                    const string expected = "<h1>Matt</h1> <h2>IT</h2> ";

                    var model = new Employee
                    {
                        Age        = 27,
                        Department = "IT",
                        Forename   = "Matt",
                        Surname    = "Abbott"
                    };

                    var childKey = service.GetKey(nameof(child));

                    service.AddTemplate(childKey, child);
                    service.RunCompile(childKey, writer, model.GetType(), model: model);

                    string result = writer.ToString();
                    Assert.That(result == expected, "Result does not match expected: " + result);
                }
        }
Exemplo n.º 3
0
        public string GetEmailBody(BaseUserEventSubscribeDTO message, string messageTemplate)
        {
            if (message == null)
            {
                throw new ArgumentException("message is null");
            }

            if (String.IsNullOrEmpty(messageTemplate))
            {
                throw new ArgumentException("messageTemplate is null");
            }

            var config = new TemplateServiceConfiguration();

            config.DisableTempFileLocking = true;
            config.CachingProvider        = new DefaultCachingProvider(t => { });
            config.TemplateManager        = new DelegateTemplateManager(name =>
            {
                string path = Path.Combine(templateFolderPath, name);
                return(File.ReadAllText(path));
            });


            var service = RazorEngineService.Create(config);

            Engine.Razor = service;

            var template = File.ReadAllText(Path.Combine(templateFolderPath, $"{messageTemplate}.cshtml"));


            return(Engine.Razor.RunCompile(template, messageTemplate, message.GetType(), message));
        }
Exemplo n.º 4
0
        static void RazorTemplateTest(Dictionary <Tree, Dictionary <Tree, Dictionary <Tree, List <Tree> > > > treeList)
        {
            var config = new TemplateServiceConfiguration
            {
                CachingProvider = new DefaultCachingProvider(t => { })
            };

            Engine.Razor = RazorEngineService.Create(config); // new API
            string      template     = File.ReadAllText(string.Format("{0}/static/razorTemplate/list.html", rootPath));
            long        milliseconds = 0;
            List <long> timeList     = new List <long>();
            Stopwatch   watch        = new Stopwatch();

            for (int i = 0; i < 10000; i++)
            {
                watch.Reset();
                watch.Start();
                Engine.Razor.RunCompile(template, "templateKey", null, treeList);
                watch.Stop();
                milliseconds = watch.ElapsedMilliseconds;
                if (milliseconds == 0)
                {
                    continue;
                }
                timeList.Add(milliseconds);
            }

            Console.WriteLine(string.Format("RazorTemplateTest min:{0},max:{1} totalCount:10000 milliseconds > 0 count:{2}", timeList.Min(), timeList.Max(), timeList.Count));
        }
Exemplo n.º 5
0
        public async Task <ActionResult> ForgetPassword(ForgetPasswordViewModel model)
        {
            var forgetPasswordValidation = securityProvider.FindUserByEmailAddress(model.Email);

            if (forgetPasswordValidation != null && this.IsCaptchaValid("Invalid captcha words"))
            {
                var newPassword = securityProvider.ResetPassword(forgetPasswordValidation, model.Email);
                var viewModel   = new ForgetPasswordMailViewModel();
                viewModel.CustomerName = String.Format("{0} {1}",
                                                       forgetPasswordValidation.FirstName,
                                                       forgetPasswordValidation.LastName);
                viewModel.NewPassword = newPassword;


                var template = emailTemplateProvider.GetEmailTemplate(EmailTemplates.ForgetPassword);

                var config = new TemplateServiceConfiguration();
                using (var service = RazorEngineService.Create(config))
                {
                    var subject = service.RunCompile(template.Subject, "subject", typeof(ForgetPasswordMailViewModel),
                                                     viewModel);
                    var content = service.RunCompile(template.Content, "content", typeof(ForgetPasswordMailViewModel),
                                                     viewModel);
                    await mailer.SendMail(model.Email, template.Bcc, subject, content);
                }
                TempData["EmailAddress"] = model.Email;
                return(RedirectToAction("ForgetPasswordSuccess"));
            }
            ModelState.AddModelError("ForgetPassword", "Sorry we are unable to validate your account. Please try again.");
            return(RedirectToAction("ForgetPassword"));
        }
Exemplo n.º 6
0
        /// <summary>
        /// 初始化
        /// </summary>
        public static void Init()
        {
            SetManager();
            //添加文件修改监控,以便在cshtml文件修改时重新编译该文件
            watcher.Path = Cache._Path.Web;
            watcher.IncludeSubdirectories = true;
            watcher.Filter              = "*.*html";
            watcher.NotifyFilter        = NotifyFilters.LastWrite | NotifyFilters.FileName;
            watcher.Created            += new FileSystemEventHandler(OnChanged);
            watcher.Changed            += new FileSystemEventHandler(OnChanged);
            watcher.Deleted            += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;

            var config = new TemplateServiceConfiguration()
            {
                Namespaces = new HashSet <string>()
                {
                    "Microsoft.CSharp", "MM.Engine"
                },                                                                      // 引入命名空间
                Language               = Language.CSharp,
                EncodedStringFactory   = new HtmlEncodedStringFactory(),
                DisableTempFileLocking = true,
                TemplateManager        = mg,
                BaseTemplateType       = typeof(MmTemplateBase <>),
                CachingProvider        = cache
            };

            cache.InvalidateAll();
            razor = RazorEngineService.Create(config);
        }
Exemplo n.º 7
0
        public void Write(IEnumerable <IRow> rows)
        {
            var l = new Cfg.Net.Loggers.MemoryLogger();

            _output.Debug(() => $"Loading template {_output.Connection.Template}");
            var template = _templateReader.Read(_output.Connection.Template, new Dictionary <string, string>(), l);

            if (l.Errors().Any())
            {
                foreach (var error in l.Errors())
                {
                    _output.Error(error);
                }
            }
            else
            {
                using (var service = RazorEngineService.Create(_config)) {
                    //File.WriteAllText(_output.Connection.File, service.RunCompile(template, _output.Connection.Name, typeof(RazorModel), new RazorModel(_output.Process, _output.Entity, rows)));

                    using (var file = new StreamWriter(_output.Connection.File)) {
                        service.RunCompile(template, _output.Connection.Name, file, typeof(RazorModel), new RazorModel(_output.Process, _output.Entity, rows));
                    }

                    // the template must set Model.Entity.Inserts
                }
            }
        }
        public string ExecuteString(string codeTemplate, IContent content, IDictionary <string, object> tokens = null)
        {
            if (!string.IsNullOrEmpty(codeTemplate))
            {
                var config = new TemplateServiceConfiguration();
#if DEBUG
                config.Debug = true;
#endif
                string result = "";
                using (var service = RazorEngineService.Create(config)) {
                    var model = new RazorModelContext {
                        OrchardServices = _orchardServices,
                        ContentItem     = content,
                        Tokens          = tokens ?? new Dictionary <string, object>(),
                        T = T
                    };
                    result = service.RunCompile(new LoadedTemplateSource(codeTemplate, null), "htmlRawTemplatea", null, (Object)model);
                }
                string resultnobr = result.Replace("\r\n", "").Replace(" ", "");
                if (!string.IsNullOrEmpty(resultnobr))
                {
                    return(result);
                }
            }
            return(null);
        }
Exemplo n.º 9
0
        public void TemplateBase_CanRenderWithLayout_WithSimpleLayout()
        {
            using (var service = RazorEngineService.Create())
                using (var writer = new StringWriter())
                {
                    const string parent   = @"<div>@RenderSection(""TestSection"")</div>@RenderBody()";
                    const string template = @"@{Layout = ""Parent"";}@section TestSection {<span>Hello</span>}<h1>Hello World</h1>";
                    const string expected = "<div><span>Hello</span></div><h1>Hello World</h1>";

                    /* GetTemplate is the simplest method for compiling and caching a template without using a
                     * resolver to locate the layout template at a later time in exection. */
                    var key            = service.GetKey("Parent");
                    var key2           = service.GetKey("Child");
                    var parentTemplate = new LoadedTemplateSource(parent);
                    var childTemplate  = new LoadedTemplateSource(template);

                    service.AddTemplate(key, parentTemplate);
                    service.AddTemplate(key2, childTemplate);
                    service.Compile(key);
                    service.Compile(key2);

                    service.Run(key2, writer);
                    string result = writer.ToString();

                    Assert.AreEqual(expected, result);
                }
        }
Exemplo n.º 10
0
 void ToHtml(Document doc, string tneTxt)
 {
     try
     {
         ThreadHelper.ThrowIfNotOnUIThread();
         //var tdoc = doc.Object("TextDocument") as TextDocument;
         var cshtml  = File.ReadAllText(doc.FullName);
         var config  = new TemplateServiceConfiguration();
         var project = doc.ProjectItem.ContainingProject;
         config.TemplateManager      = new TneMapTemplateManager($"{Path.GetDirectoryName(project.FullName)}\\", doc.Path);
         config.CachingProvider      = new DefaultCachingProvider();
         config.EncodedStringFactory = new RawStringFactory();         // Raw string encoding.
         config.EncodedStringFactory = new HtmlEncodedStringFactory(); // Html encoding.
         var engin = RazorEngineService.Create(config);
         Engine.Razor = engin;
         var result = $"<!--此代码由机器生成,请不要手动修改-->\r\n";
         result += Engine.Razor.RunCompile(new LoadedTemplateSource(cshtml, doc.FullName), "ToHtml", null, null, new DynamicViewBag());
         var filePath = $"{doc.FullName.Remove(doc.FullName.Length - 7, 7)}.html";
         if (!File.Exists(filePath))
         {
             File.WriteAllText(filePath, result);
             var hItem = doc.ProjectItem.ProjectItems.AddFromFile(filePath);
             hItem.Properties.Item("ItemType").Value = "EmbeddedResource";
         }
         else
         {
             File.WriteAllText(filePath, result);
         }
     }
     catch (Exception ex)
     {
         File.WriteAllText($"{doc.FullName.Remove(doc.FullName.Length - 7, 7)}.html", ex.ToString());
     }
 }
Exemplo n.º 11
0
        private static string GenerateHtml(object model)
        {
            var config = new TemplateServiceConfiguration
            {
                EncodedStringFactory = new RawStringFactory(),
                Language             = RazorEngine.Language.CSharp,
                TemplateManager      = new DelegateTemplateManager(name =>
                {
                    var content = File.ReadAllText(HostingEnvironment.MapPath(name));
                    return(content);
                }),
            };

            config.Namespaces.Add("System");
            config.Namespaces.Add("System.Web");
            config.Namespaces.Add("System.Linq");
            config.Namespaces.Add("Receipt.Models");
            config.Namespaces.Add("System.Collections");
            config.Namespaces.Add("System.Collections.Generic");

            Engine.Razor = RazorEngineService.Create(config);

            string body = string.Empty;

            body = Engine.Razor.RunCompile("/views/pdf/template.cshtml", model.GetType(), model, null);
            return(body);
        }
Exemplo n.º 12
0
        public static void Test1()
        {
            var config = new TemplateServiceConfiguration();

            config.BaseTemplateType = typeof(MyCustomTemplateBase <>);


            using (var service = RazorEngineService.Create(config)) {
                string index_path = Environment.CurrentDirectory + "../../../Test.cshtml";
                string index      = System.IO.File.ReadAllText(index_path, System.Text.Encoding.UTF8);

                var lst = new List <Student> {
                    new Student {
                        Age = 18, Height = 10, Name = "F*****g"
                    }, new Student {
                        Name = "CC", Height = 20, Age = 20
                    }
                };
                var bag = new DynamicViewBag();
                bag.AddValue("SSSS", "F*****g");

                var result = Engine.Razor.RunCompile(index, "f*****g", null, new { Name = "World" }, bag);

                Console.WriteLine(result);
            }
        }
Exemplo n.º 13
0
        public RazorTransform(IContext context) : base(context, context.Field.Type)
        {
            _input = MultipleInput();

            var key = GetHashCode(context.Transform.Template, _input);

            if (!Cache.TryGetValue(key, out _service))
            {
                var config = new TemplateServiceConfiguration {
                    DisableTempFileLocking = true,
                    EncodedStringFactory   = Context.Transform.ContentType == "html"
                        ? (IEncodedStringFactory) new HtmlEncodedStringFactory()
                        : new RawStringFactory(),
                    Language        = Language.CSharp,
                    CachingProvider = new DefaultCachingProvider(t => { })
                };
                _service = RazorEngineService.Create(config);
            }

            try {
                _service.Compile(Context.Transform.Template, Context.Key, typeof(ExpandoObject));
                Cache[key] = _service;
            } catch (Exception ex) {
                Context.Warn(Context.Transform.Template.Replace("{", "{{").Replace("}", "}}"));
                Context.Warn(ex.Message);
                throw;
            }
        }
Exemplo n.º 14
0
        private void button1_Click(object sender, EventArgs e)
        {
            //http://devlights.hatenablog.com/entry/20121030/p1より
            string TemplateFilePath = @"C:\temp\Templates\test.tpl";
            string OutputFilePath   = @"c:\temp\Templates\test.txt";
            var    template         = File.ReadAllText(TemplateFilePath);
            var    model            = new
            {
                Name = "hogehoge",
                TEL  = "000-111-2345"
            };

            //config
            var config = new TemplateServiceConfiguration();

            config.Language             = Language.CSharp;
            config.EncodedStringFactory = new RawStringFactory();
            //Service
            var service = RazorEngineService.Create(config);

            Engine.Razor = service;
            //Generate
            string ret = Engine.Razor.RunCompile(template, "templatekey", null, model);

            File.WriteAllText(OutputFilePath, ret);
        }
Exemplo n.º 15
0
        public static string RenderRazorViewToString(string pathToView, object model = null)
        {
            var path = HostingEnvironment.MapPath(pathToView);

            if (path == null)
            {
                return("");
            }

            pathToView = pathToView.Replace("~", "");

            if (config == null || ConfigurationManager.AppSettings["Environment"] == "Dev")
            { // always reload in dev mode
                config = new TemplateServiceConfiguration();
                config.TemplateManager = new ResolvePathTemplateManager(new[] { HostingEnvironment.MapPath("~") });
            }
            var razor = RazorEngineService.Create(config);

            //var template = File.ReadAllText(path);

            //var body = Engine.Razor.RunCompile(template, "Test", null, model);
            //new FullPathTemplateKey("x", path)
            var body = razor.RunCompile(path, null, model);

            return(body);
        }
Exemplo n.º 16
0
 static TemplateManager()
 {
     Cleanup();
     Configuration = new TemplateServiceConfiguration();
     Service       = RazorEngineService.Create(Configuration);
     Engine.Razor  = Service;
 }
Exemplo n.º 17
0
        public static string RazorRender(Object info, string razorTempl, string templateKey, Boolean debugMode = false)
        {
            var result = "";

            try
            {
                var service = (IRazorEngineService)HttpContext.Current.Application.Get("NBrightDNNIRazorEngineService");
                if (service == null || debugMode)
                {
                    // do razor test
                    var config = new TemplateServiceConfiguration();
                    config.Debug            = debugMode;
                    config.BaseTemplateType = typeof(RazorEngineTokens <>);
                    service = RazorEngineService.Create(config);
                    HttpContext.Current.Application.Set("NBrightDNNIRazorEngineService", service);
                }
                Engine.Razor = service;
                var israzorCached = Utils.GetCache("rzcache_" + templateKey); // get a cache flag for razor compile.
                if (israzorCached == null || (string)israzorCached != razorTempl)
                {
                    result = Engine.Razor.RunCompile(razorTempl, GetMd5Hash(razorTempl), null, info);
                    Utils.SetCache("rzcache_" + templateKey, razorTempl);
                }
                else
                {
                    result = Engine.Razor.Run(GetMd5Hash(razorTempl), null, info);
                }
            }
            catch (Exception ex)
            {
                result = "<div>" + ex.Message + " templateKey='" + templateKey + "'</div>";
            }

            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// 取得信件的內容
        /// </summary>
        /// <param name="mailInfo"></param>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        static string GetXMLData(string txId)
        {
            #region 取回樣版檔

            var config = new TemplateServiceConfiguration
            {
                TemplateManager        = new ResolvePathTemplateManager(new[] { "XMLTemplate" }),
                DisableTempFileLocking = true
            };

            Engine.Razor = RazorEngineService.Create(config);
            string TemplateFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XMLTemplate");

            string fileName          = txId + ".cshtml";
            var    emailTemplatePath = Path.Combine(TemplateFolderPath, fileName);
            #endregion

            M2112 entity = new M2112()
            {
                MyName = "Danny"
            };
            string MailBody = Engine.Razor.RunCompile(emailTemplatePath, null, entity);

            return(MailBody);
        }
Exemplo n.º 19
0
        private string ParseTemplateWithModel <T>(string template, T model, string name)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(template))
                {
                    return(string.Empty);
                }
                var razorEngineconfig = new TemplateServiceConfiguration
                {
                    BaseTemplateType = typeof(HtmlTemplateBase <>)
                };

                using (var service = RazorEngineService.Create(razorEngineconfig))
                {
                    if (!CachedFileAccess.IsCompiled(name))
                    {
                        service.Compile(template, name, typeof(T));
                        CachedFileAccess.SetCompiled(name);
                    }
                    return(service.Run(name, typeof(T)));
                }
            }
            catch (RazorEngine.Templating.TemplateCompilationException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var e in ex.CompilerErrors)
                {
                    sb.AppendFormat("{0}\n", e.ToString().Replace(e.FileName, string.Empty));
                }
                throw new JSFileParserException(string.Format("Failure to parse template {0}. See Errors:\n{1}", _filename, sb.ToString()));
            }
        }
Exemplo n.º 20
0
        public string RenderFromMvc <TViewModel>(string path, TViewModel vm)
        {
            string templateKey = path;              // Just reuse the path as a unique key to the template
            var    viewPath    = AppRoot + path;
            //var razor = RazorEngine.Engine.Razor;
            // https://matthid.github.io/RazorEngine/TemplateBasics.html#Extending-the-template-Syntax
            var config = new RazorEngine.Configuration.TemplateServiceConfiguration();

            config.BaseTemplateType = typeof(RazorMvcTemplateBase <>);
            config.Resolver         = new RazorTemplateResolver(AppRoot, viewPath);
            //config.TemplateManager
            using (var razor = RazorEngineService.Create(config))
            {
                var tvm = typeof(TViewModel);
                if (!razor.IsTemplateCached(templateKey, tvm))
                {
                    var template = System.IO.File.ReadAllText(viewPath);
                    //template = FromMvcRazorToRazorEngine(template);
                    razor.AddTemplate(templateKey, template);
                }

                string html = razor.RunCompile(templateKey, typeof(TViewModel), vm);
                return(html);
            }
        }
Exemplo n.º 21
0
        public EmailManager()
        {
            try
            {
                MailClient = new SmtpClient()
                {
                    EnableSsl   = Convert.ToBoolean(ConfigurationManager.AppSettings["configuration.email.ssl"] ?? "False"),
                    Host        = ConfigurationManager.AppSettings["configuration.email.smtpServer"],
                    Port        = Convert.ToInt16(ConfigurationManager.AppSettings["configuration.email.port"] ?? "25"),
                    Credentials = new NetworkCredential(ConfigurationManager.AppSettings["configuration.email.user"],
                                                        ConfigurationManager.AppSettings["configuration.email.password"])
                };

                var emailLayoutPath    = System.Web.Hosting.HostingEnvironment.MapPath("~/~/CMS/Views/Emails/EmailLayout.cshtml");
                var emailLayoutContent = File.ReadAllText(emailLayoutPath, System.Text.Encoding.UTF8);

                var config = new RazorEngine.Configuration.TemplateServiceConfiguration()
                {
                    AllowMissingPropertiesOnDynamic = true
                };

                Engine.Razor = RazorEngineService.Create(config);

                Engine.Razor.AddTemplate("EmailLayout", emailLayoutContent);
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
            }
        }
        public virtual void OnAppStartup()
        {
            TemplateServiceConfiguration config = new TemplateServiceConfiguration();

            AppEnvironment activeAppEnvironment = AppEnvironmentProvider.GetActiveAppEnvironment();

            config.Debug                = activeAppEnvironment.DebugMode;
            config.Language             = Language.CSharp;
            config.EncodedStringFactory = new NullCompatibleEncodedStringFactory();

            IRazorEngineService service = RazorEngineService.Create(config);

            Engine.Razor = service;

            string defaultPageTemplateFilePath = PathProvider.StaticFileMapPath(activeAppEnvironment.GetConfig("DefaultPageTemplatePath", "defaultPageTemplate.cshtml"));

            if (File.Exists(defaultPageTemplateFilePath))
            {
                string defaultPageTemplateContents = File.ReadAllText(defaultPageTemplateFilePath);

                Engine.Razor.Compile(name: "defaultPageTemplate", modelType: typeof(IDependencyResolver),
                                     templateSource: new LoadedTemplateSource(defaultPageTemplateContents, defaultPageTemplateFilePath));
            }

            string ssoPageTemplateFilePath = PathProvider.StaticFileMapPath(activeAppEnvironment.GetConfig("SsoPageTemplatePath", "ssoPageTemplate.cshtml"));

            if (File.Exists(ssoPageTemplateFilePath))
            {
                string ssoPageTemplateContents = File.ReadAllText(ssoPageTemplateFilePath);

                Engine.Razor.Compile(name: "ssoPageTemplate", modelType: typeof(IDependencyResolver),
                                     templateSource: new LoadedTemplateSource(ssoPageTemplateContents, ssoPageTemplateFilePath));
            }
        }
Exemplo n.º 23
0
        public ActionResult Content(ExerciseContentViewModel viewModel)
        {
            // Make a razor engine service with the System.Web.Mvc namespace open
            var config     = new TemplateServiceConfiguration();
            var namespaces = config.Namespaces;

            namespaces.Add("System.Web.Mvc");
            var service = RazorEngineService.Create(config);

            // Make the UrlHelper and HtmlHelper extension methods available in (close to) the same
            // way as a normal view
            string fullSource = "@using System.Web.Mvc.Html; " +
                                "@using CodingTrainer.CodingTrainerWeb.ViewExtensions; " +
                                "@{var Url = Model.Url; var Html = Model.Html;} "
                                + viewModel.Exercise.Content;

            // Including the hash code in the key allows this to work even if the source changes
            // However, this will result in memory leaks. The fix for this is to write a new
            // caching provider - however, this is considered to be a minor issue, and is
            // acceptable for now - see this post by Matthias Dittrich
            // https://github.com/Antaris/RazorEngine/issues/232#issuecomment-128802285
            var key = $"ContentTemplate{viewModel.Exercise.ChapterNo}-{viewModel.Exercise.ExerciseNo}-{fullSource.GetHashCode()}";

            service.AddTemplate(key, new LoadedTemplateSource(fullSource));


            // Finally, compile and run the content source
            var result = service.RunCompile(key, typeof(ExerciseContentViewModel), viewModel);

            return(Content(result));
        }
        /// <summary>
        ///  Send notification email when the process starts
        /// </summary>
        /// <param name="processStartedDateTime">Process started time</param>
        public void SendInitialNotification(DateTime processStartedDateTime)
        {
            var config = new TemplateServiceConfiguration
            {
                BaseTemplateType       = typeof(HtmlSupportTemplateBase <>),
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { })
            };

            bool pushPriceToAirBnb     = Config.I.PushPriceToAirBnb;
            bool pushPriceToStreamLine = Config.I.PushPriceToStreamLine;

            var templatePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var template     = File.ReadAllText(Path.Combine(templatePath, "Templates/PricingPushInitialNotificationTemplate.cshtml"));

            using (var service = RazorEngineService.Create(config))
            {
                var body = service.RunCompile(template, "PricingPushInitialNotificationTemplate", null, new
                {
                    ProcessStartedAt = processStartedDateTime.ToString("yyyy-M-d HH:mm tt"),
                    PushToAirbnb     = pushPriceToAirBnb,
                    PushToStreamline = pushPriceToStreamLine
                });

                EmailNotification.Send(Config.I.NotificationsEmail, "Pricing Push Initialized", body);
            }
        }
        public void Initialize()
        {
            Log.InfoFormat(Properties.Resources.InitializationTrace);
            _deviceManager = Dependency.Resolve <IDeviceManager>();

            try
            {
                var pluginFolderPath = Path.Combine(new Uri(Path.GetDirectoryName(typeof(Plugin).Assembly.CodeBase)).LocalPath, "EmailTemplates");
                Log.InfoFormat(Properties.Resources.TemplatesPathTrace, pluginFolderPath);

                var config = new TemplateServiceConfiguration
                {
                    TemplateManager = new ResolvePathTemplateManager(new[] { pluginFolderPath })
                };

                Engine.Razor = RazorEngineService.Create(config);

                foreach (var template in Templates)
                {
                    Log.InfoFormat(Properties.Resources.CompileTemplateTrace, template.Key);
                    Engine.Razor.Compile(template.Key, template.Value);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(Properties.Resources.InitializationError, ex);
            }
        }
        /// <summary>
        /// Send notification mail with the results of price push to Streamline.
        /// </summary>
        /// <param name="logWrittenDateTime">Log written date and time.</param>
        public void SendNotificationToStreamLine(DateTime logWrittenDateTime)
        {
            var config = new TemplateServiceConfiguration
            {
                BaseTemplateType       = typeof(HtmlSupportTemplateBase <>),
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { })
            };

            var pricingPushLogger = new OperationsJsonLogger <PricePushResult>(Config.I.PricingPushAttemptsLogFile);
            var pricingPushlogs   = pricingPushLogger.GetLogRecordsForExactDateTime(logWrittenDateTime);
            var streamLineLogs    = pricingPushlogs.Where(p => p.Channel == Channel.StreamLine || p.Channel == Channel.Common);
            var templatePath      = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var template          = File.ReadAllText(Path.Combine(templatePath, "Templates/StreamLinePricingPushNotificationTemplate.cshtml"));

            using (var service = RazorEngineService.Create(config))
            {
                var body = service.RunCompile(template, "StreamLinePricingPushNotificationTemplate", null, new
                {
                    ProcessStartedAt    = logWrittenDateTime.ToString("yyyy-M-d HH:mm tt"),
                    ErrorsCount         = streamLineLogs.Where(p => p.LogType == PricingPushLogType.Error).Count(),
                    ParsingCSV          = streamLineLogs.Where(p => ((p.LogArea == PricePushLogArea.ParsingCSV || p.LogArea == PricePushLogArea.CSVFileNotFound) && p.LogType == PricingPushLogType.Error)),
                    PropertyDetails     = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.ParsingCSV && p.LogType == PricingPushLogType.Information),
                    LoginDetails        = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.Login && p.LogType == PricingPushLogType.Information),
                    LoginErrors         = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.Login && p.LogType == PricingPushLogType.Error),
                    SeasonGroupErrors   = streamLineLogs.Where(p => ((p.LogArea == PricePushLogArea.SeasonGroup || p.LogArea == PricePushLogArea.ChangeSeasonGroup) && p.LogType == PricingPushLogType.Error)),
                    SeasonErrors        = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.Season && p.LogType == PricingPushLogType.Error),
                    PropertyErrors      = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.Property && p.LogType == PricingPushLogType.Error),
                    PriceUpdationErrors = streamLineLogs.Where(p => p.LogArea == PricePushLogArea.PriceUpdate && p.LogType == PricingPushLogType.Error),
                });

                EmailNotification.Send(Config.I.PricingPushNotificationsEmail, "Streamline Pricing Push Report", body);
            }
        }
Exemplo n.º 27
0
        protected override string RenderTemplate(string content, PageContext pageData)
        {
            var serviceConfiguration = new TemplateServiceConfiguration
            {
                TemplateManager          = new IncludesResolver(FileSystem, includesPath),
                BaseTemplateType         = typeof(ExtensibleTemplate <>),
                DisableTempFileLocking   = true,
                CachingProvider          = new DefaultCachingProvider(t => { }),
                ConfigureCompilerBuilder = builder => ModelDirective.Register(builder)
            };

            serviceConfiguration.Activator = new ExtensibleActivator(serviceConfiguration.Activator, Filters, _allTags);

            Engine.Razor = RazorEngineService.Create(serviceConfiguration);

            content = Regex.Replace(content, "<p>(@model .*?)</p>", "$1");

            var pageContent = pageData.Content;

            pageData.Content = pageData.FullContent;

            try
            {
                content          = Engine.Razor.RunCompile(content, pageData.Page.File, typeof(PageContext), pageData);
                pageData.Content = pageContent;
                return(content);
            }
            catch (Exception e)
            {
                Tracing.Error(@"Failed to render template, falling back to direct content");
                Tracing.Debug(e.Message);
                Tracing.Debug(e.StackTrace);
                return(content);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        ///   Create instance of EmailService with specified providers
        /// </summary>
        /// <param name="mailProvider"></param>
        /// <param name="templateProvider"></param>
        /// <param name="emailTemplateConfiguration"></param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="EmailSettingsException"></exception>
        public EmailService(IMailProvider mailProvider, IMessageTemplateProvider templateProvider,
                            IEmailTemplateConfiguration emailTemplateConfiguration)
        {
            _log = LogManager.GetLogger(GetType());

            if (mailProvider == null)
            {
                throw new ArgumentNullException(nameof(mailProvider));
            }
            if (emailTemplateConfiguration == null)
            {
                throw new ArgumentNullException(nameof(emailTemplateConfiguration));
            }
            _emailSettings = new Settings().EmailSettings;

            if (_emailSettings == null)
            {
                throw new EmailSettingsException();
            }

            _mailProvider               = mailProvider;
            _templateProvider           = templateProvider;
            _emailTemplateConfiguration = emailTemplateConfiguration;
            _engineService              = RazorEngineService.Create((ITemplateServiceConfiguration)_emailTemplateConfiguration);
        }
Exemplo n.º 29
0
        public static IContainer Build()
        {
            var builder       = new ContainerBuilder();
            var frontAssembly = typeof(Global).Assembly;

            builder.RegisterInstance(LoggerConfig.Build()).AsImplementedInterfaces();

            var templateConfig = new TemplateServiceConfiguration
            {
                TemplateManager        = new DelegateTemplateManager(GetView),
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { })
            };

            builder.RegisterInstance(RazorEngineService.Create(templateConfig)).AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(frontAssembly).AsImplementedInterfaces().SingleInstance();

            var assemblies = Loader.LoadFromBinDirectory("Editor.*.dll");

            builder.RegisterAssemblyTypes(assemblies).AsSelf().AsImplementedInterfaces().SingleInstance();

            builder.RegisterType <SQLiteDbContext>().As <IDbContext>().InstancePerLifetimeScope();

            builder.RegisterApiControllers(frontAssembly);

            builder.RegisterWebApiModelBinderProvider();
            builder.RegisterType <SessionBinder>().AsModelBinderForTypes(typeof(Session));
            builder.RegisterType <DocumentSession>().As <IDocumentSession>().InstancePerDependency();
            builder.RegisterType <EditorWebSocket>().InstancePerDependency();

            return(builder.Build());
        }
Exemplo n.º 30
0
        public virtual string ExecuteHtml(string viewTemplate, OperationPackage package)
        {
            string date = $"{DateTime.Now:dd.MM.yy HH:mm:ss}";

            TemplateServiceConfiguration templateConfig =
                new TemplateServiceConfiguration
            {
                DisableTempFileLocking = true,
                CachingProvider        = new DefaultCachingProvider(t => { })
            };

            var serv = RazorEngineService.Create(templateConfig);

            Engine.Razor = serv;
            Engine.Razor.Compile(viewTemplate, "somekey");

            if (!package.DataSets.Any())
            {
                return("No information obtained by query");
            }

            var packageValues = PackageParser.GetPackageValues(package);

            var dataSet = packageValues.First();

            var model = new
            {
                dataSet.Headers,
                Content = dataSet.Rows,
                Date    = date
            };

            return(Engine.Razor.Run("somekey", null, model));
        }