Esempio n. 1
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);
                }
        }
Esempio n. 2
0
            public ITemplateSource Resolve(ITemplateKey key)
            {
                var name = key.Name;

                LoadedTemplateSource loadedTemplate;

                if (!this.TopLevelTemplates.TryGetValue(name, out loadedTemplate))
                {
                    var id = Path.GetFileNameWithoutExtension(name);

                    var extension = Path.GetExtension(name).TrimStart('.');

                    var layout = RenderingTransaction.Current.Layouts[id];

                    if (!layout.Extension.Equals(String.IsNullOrEmpty(extension) ? "cshtml" : extension, StringComparison.OrdinalIgnoreCase))
                    {
                        // TODO: throw new exception.
                    }

                    loadedTemplate = new LoadedTemplateSource(layout.SourceContent, layout.SourcePath);

                    // Do not need to add this loaded template to our list of cached top level templates
                    // because RazorEngine will remember it for us and never ask again.
                }

                return(loadedTemplate);
            }
        public string GenerateMessageBody(string template, object model)
        {
            string result = null;

            try
            {
                var engine = EngineFactory.CreateEmbedded(model.GetType());
                //result = engine.ParseString(template, model);

                ITemplateSource   source    = new LoadedTemplateSource(template);
                ModelTypeInfo     modelInfo = new ModelTypeInfo(model.GetType());
                CompilationResult compiled  = engine.Core.CompileSource(source, modelInfo);
                compiled.EnsureSuccessful();

                TemplatePage page = engine.Activate(compiled.CompiledType);
                page.PageContext = new PageContext {
                    ModelTypeInfo = modelInfo
                };

                result = engine.RunTemplate(page, model);
            }
            catch (TemplateCompilationException tex)
            {
                throw new MessageGenerationException($"Error generating message from template! {tex.CompilationErrors.FirstOrDefault()}", tex);
            }
            catch (Exception ex)
            {
                throw new MessageGenerationException("Unexpected error generating message from template!", ex);
            }

            return(result);
        }
Esempio n. 4
0
        public string Render(string path, string template, object data)
        {
            lock (Engine.Razor)
            {
                LoadedTemplateSource loadedTemplate;

                if (!this.TopLevelTemplates.TryGetValue(path, out loadedTemplate))
                {
                    loadedTemplate = new LoadedTemplateSource(template, path);

                    this.TopLevelTemplates.Add(path, loadedTemplate);
                }

                try
                {
                    var result = Engine.Razor.RunCompile(loadedTemplate, path, null, data);

                    return(result);
                }
                catch (TemplateCompilationException e)
                {
                    foreach (var error in e.CompilerErrors)
                    {
                        Console.Error.WriteLine(error.ErrorText);
                    }
                }

                return(null);
            }
        }
 public void RazorEngineService_GetInformativeRuntimeErrorMessage()
 {
     RunTestHelper(service =>
     {
         const string template = "@foreach (var i in Model.Unknown) { @i }";
         string file           = Path.GetTempFileName();
         try
         {
             File.WriteAllText(file, template);
             var source = new LoadedTemplateSource(template, file);
             var exn    = Assert.Throws <Microsoft.CSharp.RuntimeBinder.RuntimeBinderException>(() =>
             {
                 string result = service.RunCompile(source, "test", null, new object());
             });
             // We now have a reference to our template in the stacktrace
             var stack    = exn.StackTrace.ToLowerInvariant();
             var expected = file.ToLowerInvariant();
             Assert.IsTrue(
                 stack.Contains(expected),
                 "Could not find reference to template (" + expected + ") in stacktrace: \n" +
                 stack);
         }
         finally
         {
             File.Delete(file);
         }
     });
 }
Esempio n. 6
0
        private string GetRazorTemplate()
        {
            var razorCompiler = new DefaultRazorTemplateCompiler();
            var source        = new LoadedTemplateSource("Hello @Model.Title");

            return(razorCompiler.CompileTemplate(new RazorLightHost(null), source));
        }
 public AnubisDBMSSecurityEmailService(string templateDirectory)
 {
     _serviceConfiguration.BaseTemplateType = typeof(HtmlTemplateBase <>);
     _service = RazorEngineService.Create(_serviceConfiguration);
     var creacionUsuarioTemplateFile = Path.Combine(templateDirectory, "CreacionUsuario.html");
     var creacionUsuarioTemplate     = new LoadedTemplateSource("creacionUsuario", creacionUsuarioTemplateFile);
     //_service.AddTemplate("key", );
 }
Esempio n. 8
0
        public void Compilation_Result_NotNull()
        {
            var compiler = new DefaultRazorTemplateCompiler();
            var source   = new LoadedTemplateSource("Hello @Model.Title");

            string result = compiler.CompileTemplate(new RazorLightHost(null), source);

            Assert.NotNull(result);
        }
Esempio n. 9
0
        public void Ensure_CompiledType_Is_TypeOf_TemplatePage()
        {
            var source    = new LoadedTemplateSource("Hello, @Model.Title");
            var model     = new { Title = "John" };
            var modelInfo = new ModelTypeInfo(model.GetType());

            Type type = testCore.CompileSource(source, modelInfo).CompiledType;
            var  page = Activator.CreateInstance(type);

            Assert.IsAssignableFrom <TemplatePage>(page);
        }
Esempio n. 10
0
        public void Ensure_CompileSource_Returns_Correct_CompilationResult()
        {
            var source    = new LoadedTemplateSource("Hello, @Model.Title");
            var model     = new { Title = "John" };
            var modelInfo = new ModelTypeInfo(model.GetType());

            CompilationResult result = testCore.CompileSource(source, modelInfo);

            Assert.NotNull(result);
            Assert.Null(result.CompilationFailures);
            Assert.NotNull(result.CompiledType);
        }
Esempio n. 11
0
        public string Render <TModel>(string templateFile, TModel model, object templateArgs = null)
        {
            var template    = File.ReadAllText(templateFile);
            var templateKey = GetMd5Hash(template);

            var dictionary = HtmlHelper.ObjectToDictionary(templateArgs);
            var viewBag    = new DynamicViewBag(dictionary);

            var source = new LoadedTemplateSource(template, templateFile);
            var result = Engine.Razor.RunCompile(source, templateKey, null, model, viewBag);

            return(result);
        }
Esempio n. 12
0
        public void Compiler_Throw_On_Corrupted_Template()
        {
            var content = "This is a corrupted. @UnknownType should throw";
            var source  = new LoadedTemplateSource(content);

            var razorTemplate = new DefaultRazorTemplateCompiler().CompileTemplate(new RazorLightHost(null), source);
            var context       = new CompilationContext(razorTemplate, new HashSet <string>());

            CompilationResult result = new RoslynCompilerService(metadataResolver).Compile(context);
            var action = new Action(() => result.EnsureSuccessful());

            Assert.NotNull(result.CompilationFailures);
            Assert.Throws(typeof(TemplateCompilationException), action);
        }
Esempio n. 13
0
        static int Main(string[] args)
        {
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
                // Console.WriteLine( "Switching to secound AppDomain, for RazorEngine..." );
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var current = AppDomain.CurrentDomain;
                // You only need to add strongnames when your appdomain is not a full trust environment.
                var strongNames = new StrongName[0];

                var domain = AppDomain.CreateDomain(
                    "MyMainDomain", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
                    strongNames);
                var exitCode = domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);
                // RazorEngine will cleanup.
                AppDomain.Unload(domain);
                return(exitCode);
            }

            var filenameInputJson = "sample/defines.json";
            var defineJsonText    = File.ReadAllText(filenameInputJson);
            var defines           = DynamicJson.Parse(defineJsonText);

            var config = new TemplateServiceConfiguration
            {
                Debug = true,
                EncodedStringFactory = new RawStringFactory()                           // 出力で HTML エンコードを行わない '>' '<' などをそのまま出力する。デフォルトでは html エンコード '>' -> '&gt;' として出力される
            };

            var service = RazorEngineService.Create(config);
            var result  = "";

            string templateFile = "sample/sample.cshtml";
            var    template     = new LoadedTemplateSource(File.ReadAllText(templateFile), templateFile);

            result =
                service.RunCompile(template, "templateKey1", typeof(DynamicObject), ( object )defines);


            Console.WriteLine(result);

            return(0);
        }
Esempio n. 14
0
        public ITemplateSource Resolve(ITemplateKey key)
        {
            if (dictTmp.ContainsKey(key))
            {
                return(dictTmp[key]);
            }

            var viewPath = compiler.ResolvePath(key.Name);

            if (!compiler.IsExists(key.Name))
            {
                throw new ViewNotFoundException(key.Name, viewPath);
            }

            var viewContent = compiler.GetFileContent(viewPath);
            var result      = new LoadedTemplateSource(viewContent, viewPath);

            dictTmp.Add(key, result);

            return(Resolve(key));
        }
        public void FluentTemplateServiceConfiguration_CanConfigureTemplateService_WithAdditionalNamespaces()
        {
            var config = new FluentTemplateServiceConfiguration(
                c => c.IncludeNamespaces("System.IO"));

            using (var service = RazorEngineService.Create(config))
                using (var writer = new StringWriter())
                {
                    const string template = @"@Directory.GetFiles(Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.Personal)), ""*.*"").Length";

                    int expected = Directory.GetFiles(Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.Personal)), "*.*").Length;

                    var key    = service.GetKey("testTemplate");
                    var source = new LoadedTemplateSource(template);
                    service.AddTemplate(key, source);
                    service.Compile(key);
                    service.Run(key, writer);
                    var result = writer.ToString();
                    Assert.AreEqual(expected.ToString(), result);
                }
        }
Esempio n. 16
0
        //private IRazorEngineService _engine;
        //private RazorFileTemplate _razorFileTemplate;
        //public CustomTemplateBase(IRazorEngineService engine, RazorFileTemplate razorFileTemplate) : base()
        //{
        //    _engine = engine;
        //    _razorFileTemplate = razorFileTemplate;
        //}

        public string Partial(string partialName, object obj)
        {
            var path = partialName;

            if (this.ViewBag.InputFolder != null)
            {
                path = FileUtils.GetPartialPath(this.ViewBag.InputFolder, path);
            }
            if (File.Exists(path))
            {
                try
                {
                    //compile partial template
                    var fileContent = FileUtils.ReadFileContent(path);
                    var templateKey = Razor.GetKey(partialName);
                    if (!Razor.IsTemplateCached(templateKey, null))
                    {
                        var templateSource = new LoadedTemplateSource(fileContent);
                        Razor.AddTemplate(templateKey, templateSource);
                        Razor.Compile(templateKey, obj.GetType());
                    }
                    Include(partialName, obj, null).WriteTo(this.CurrentWriter);
                    return(string.Empty);
                }
                catch (TemplateCompilationException tex)
                {
                    return(string.Format("Partial Render Error{0}\r\n{1}", path, MRazorUtil.GetError(tex)));
                }
                catch (Exception ex)
                {
                    return(string.Format("Partial Render Error{0}\r\n{1}", path, ex.Message));
                }
            }
            else
            {
                return("Partial file Not Found " + path);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Parses a string
        /// </summary>
        /// <param name="content">Template to parse</param>
        /// <param name="model">Template model</param>
        /// <param name="modelType">Type of the model</param>
        /// <returns></returns>
        public static string ParseString(this IRazorLightEngine engine, string content, object model, Type modelType)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new ArgumentNullException(nameof(content));
            }

            ITemplateSource templateSource = new LoadedTemplateSource(content);

            ModelTypeInfo     modelTypeInfo = new ModelTypeInfo(modelType);
            CompilationResult result        = engine.Core.CompileSource(templateSource, modelTypeInfo);

            result.EnsureSuccessful();

            TemplatePage page = engine.Activate(result.CompiledType);

            page.PageContext = new PageContext()
            {
                ModelTypeInfo = modelTypeInfo
            };

            return(engine.RunTemplate(page, model));
        }
        public void FluentTemplateServiceConfiguration_CanConfigureTemplateService_WithSpecificEncoding()
        {
            var config = new FluentTemplateServiceConfiguration(
                c => c.WithEncoding(Encoding.Raw));

            using (var service = RazorEngineService.Create(config))
                using (var writer = new StringWriter())
                {
                    const string template = "<h1>Hello @Model.String</h1>";
                    const string expected = "<h1>Hello Matt & World</h1>";

                    var model  = new { String = "Matt & World" };
                    var source = new LoadedTemplateSource(template);
                    var key    = service.GetKey("testTemplate");

                    service.Compile(source, key);
                    service.Run(key, writer, model: model);

                    var contents = writer.ToString();

                    Assert.AreEqual(expected, contents);
                }
        }
Esempio n. 19
0
        /// <summary>
        /// 渲染数据
        /// </summary>
        /// <param name="key">缓存键</param>
        /// <param name="template">模板</param>
        /// <param name="model">数据模型</param>
        public string FormatS(string key, LoadedTemplateSource template, object model)
        {
            var ret = "";

            try
            {
                var  km = razor.GetKey(key);
                Type tp = null;
                var  bl = razor.IsTemplateCached(km, tp);
                if (bl)
                {
                    ret = razor.Run(km, tp, model, ViewBag);
                }
                else
                {
                    ret = razor.RunCompile(template, km, tp, model, ViewBag);
                }
            }
            catch (Exception ex)
            {
                Ex = ex.ToString();
            }
            return(ret);
        }
Esempio n. 20
0
            public string GetResult([NotNull] HttpRequestMessage request, [CanBeNull] object model)
            {
                var lastWriteTimeUtc = File.GetLastWriteTimeUtc(templatePath);

                if (cachedLastWriteTimeUtc != lastWriteTimeUtc)
                {
                    lock (locker)
                    {
                        if (cachedLastWriteTimeUtc != lastWriteTimeUtc)
                        {
                            var template       = File.ReadAllText(templatePath);
                            var templateSource = new LoadedTemplateSource(template, templatePath);
                            templateKey = new NameOnlyTemplateKey(templatePath + Guid.NewGuid(), ResolveType.Global, null);
                            razor.AddTemplate(templateKey, templateSource);
                            razor.Compile(templateKey, modelType);
                            cachedLastWriteTimeUtc = lastWriteTimeUtc;
                        }
                    }
                }
                var viewBag = new DynamicViewBag();

                viewBag.AddValue("__request", request);
                return(razor.Run(templateKey, modelType, model, viewBag));
            }
Esempio n. 21
0
 public string Render(LoadedTemplateSource template, ExpandoObject content)
 {
     return(Engine.Razor.RunCompile(template, "razorTemplate", null, content));
 }
Esempio n. 22
0
        /// <summary>
        /// Handles a form submission (sends an email).
        /// </summary>
        /// <param name="context">
        /// The form submission context.
        /// </param>
        /// <param name="configuration">
        /// The handler configuration.
        /// </param>
        public override void HandleForm(FormSubmissionContext context, object configuration)
        {
            // Prepare the message.
            var message = PrepareEmailMessage(context, configuration as IEmailSenderRecipientConfiguration);

            if (message == null)
            {
                return;
            }

            // Variables.
            var config          = configuration as DesignedEmailConfiguration;
            var form            = context.Form;
            var data            = context.Data;
            var dataForMessage  = data;
            var files           = context.Files;
            var filesForMessage = files;
            var payload         = context.Payload;
            var extraContext    = context.ExtraContext;
            var plainTextBody   = default(string);
            var htmlBody        = default(string);

            // Combine all the email recipients into a single array.
            var emailDataRecipients = message.To.ToArray()
                                      .Concat(message.CC.ToArray())
                                      .Concat(message.Bcc.ToArray())
                                      .Select(x => x.Address).Distinct()
                                      .OrderBy(x => x).ToArray();

            // Create the email data to be passed to the Razor view.
            var emailData = new EmailData(GetFormValues(context))
            {
                MailMessage     = message,
                SenderEmail     = config.SenderEmail,
                RecipientEmails = emailDataRecipients,
                Subject         = config.Subject,
                Message         = config.Message,
                Helper          = new EmailDataHelper(message)
            };

            // Generate the email subject.
            var path     = GetViewPath(config.SubjectRazorPath);
            var contents = path == null
                ? RazorViewIncorrectMarkup(config.HtmlEmailRazorPath)
                : File.ReadAllText(path);

            var templateSource = path == null
                ? null
                : new LoadedTemplateSource(contents, path);
            var key = GetViewKey(path, contents);

            message.Subject = path == null
                ? config.Subject
                : (RazorService.RunCompile(templateSource, key, emailData.GetType(), emailData) ?? "")
                              .Trim()
                              .Replace("\r", string.Empty)
                              .Replace("\n", string.Empty);

            // Generate the HTML for the message.
            path     = GetViewPath(config.HtmlEmailRazorPath);
            contents = path == null
                ? RazorViewIncorrectMarkup(config.HtmlEmailRazorPath)
                : File.ReadAllText(path);

            templateSource = new LoadedTemplateSource(contents, path);
            key            = GetViewKey(path, contents);
            htmlBody       = RazorService.RunCompile(templateSource, key, emailData.GetType(), emailData);

            // Generate the text for the message.
            path = GetViewPath(config.TextEmailRazorPath);
            if (path != null)
            {
                contents       = File.ReadAllText(path);
                templateSource = new LoadedTemplateSource(contents, path);
                key            = GetViewKey(path, contents);
                plainTextBody  = RazorService.RunCompile(templateSource, key, emailData.GetType(), emailData);
            }

            // Add plain text alternate view.
            var mimeType  = new ContentType(MediaTypeNames.Text.Plain);
            var emailView = AlternateView.CreateAlternateViewFromString(plainTextBody ?? "", mimeType);

            message.AlternateViews.Add(emailView);

            // Add HTML alternate view.
            mimeType  = new ContentType(MediaTypeNames.Text.Html);
            emailView = AlternateView.CreateAlternateViewFromString(htmlBody ?? "", mimeType);
            message.AlternateViews.Add(emailView);

            // Send email.
            using (var client = new SmtpClient())
            {
                client.Send(message);
            }
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            ////////////////////////////////////////////////////
            string localData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            if (!System.IO.Directory.Exists(localData + "\\ResTBDesktop"))
            {
                System.IO.Directory.CreateDirectory(localData + "\\ResTBDesktop");
            }
            //string scriptPath = localData + "\\ResTBDesktop\\Script";
            //if (!System.IO.Directory.Exists(scriptPath))
            //    System.IO.Directory.CreateDirectory(scriptPath);
            string htmlPath = localData + "\\ResTBDesktop\\result.html";


            //Console.WriteLine($"output html: {htmlPath}");
            ////////////////////////////////////////////////////

            int  projectId   = -1;
            bool showDetails = false;
            bool onlySummary = false;
            bool isOnline    = false;

            string cultureString = "en";
            var    p             = new FluentCommandLineParser();

            p.Setup <int>('p', "project")
            .Callback(record => projectId = record)
            .WithDescription("Project ID (int)")
            .Required();

            p.Setup <bool>('d', "detail")
            .Callback(record => showDetails = record)
            .WithDescription("Show Details in Summary")
            .SetDefault(false);

            p.Setup <bool>('s', "summaryonly")
            .Callback(record => onlySummary = record)
            .WithDescription("Show Summary Only")
            .SetDefault(false);

            p.Setup <string>('c', "culture")
            .Callback(record => cultureString = record)
            .WithDescription("Language Setting")
            .SetDefault("es-HN");

            p.Setup <bool>('o', "online")
            .Callback(record => isOnline = record)
            .WithDescription("DB is online")
            .SetDefault(false);

            var parsedArgs = p.Parse(args);

            if (parsedArgs.HasErrors == true)
            {
                Console.WriteLine(parsedArgs.ErrorText);
                return;
            }

            Globals.ISONLINE = isOnline;    //set for Connection string

            CultureInfo culture;

            try
            {
                //CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureString);
                culture = new CultureInfo(cultureString);
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;

                //CultureInfo.DefaultThreadCurrentUICulture = culture;
                //CultureInfo.DefaultThreadCurrentCulture = culture;
            }
            catch (Exception)
            {
                Console.WriteLine($"ERROR: culture invalid. Provided value: {cultureString}");
                return;
            }

            Console.WriteLine("Kernel started...");
            Console.WriteLine($"\tProject Id = {projectId}, showDetails = {showDetails}, " +
                              $"summaryOnly = {onlySummary}, culture = {cultureString}, isOnline = {isOnline}");
            ////////////////////////////////////////////////////
            // CALCULATION

            if (!onlySummary)
            {
                try
                {
                    ResultWrapper.CreateDamageExtents(projectId);               //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                    Console.WriteLine("\n\tCreate Damage Extents finished.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("\nError while creating damage extents.\n\n" + ex.ToString());
                    return;
                }
            }

            ProjectResult projectResult = ResultWrapper.ComputeResult(projectId, showDetails);

            Console.WriteLine("\n\tCompute Project Result finished.");

            string fullFileName = @"Kernel/Views/Summary.cshtml";               //REMINDER: Copy CSHTML to output dir

            DynamicViewBag viewBag = new DynamicViewBag();

            viewBag.AddValue("attachCss", true);
            viewBag.AddValue("details", showDetails);
            viewBag.AddValue("print", true);

            var    templateSource = new LoadedTemplateSource(File.ReadAllText(fullFileName), fullFileName);
            string result         = "";

            var t = Task.Run(() =>
            {
                Thread.CurrentThread.CurrentCulture   = culture;
                Thread.CurrentThread.CurrentUICulture = culture;

                Console.WriteLine("Task thread ID: {0}", Thread.CurrentThread.ManagedThreadId);
                result =
                    Engine.Razor.RunCompile(templateSource, "templateKey", null, model: projectResult, viewBag: viewBag);   //RENDER HTML with RAZOR ENGINE

                Console.WriteLine($"\tTask: culture = {culture.TwoLetterISOLanguageName} / {culture.Name}");
            });

            t.Wait();

            File.WriteAllText(htmlPath, result);               //TODO: Save HTML to output dir

            Console.WriteLine("\nKernel finished.\n");
        }