Git Product home page Git Product logo

razorengine's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

razorengine's Issues

XML docs not included in NuGet package

RazorEngine has XML docs for many classes, but they do not show up in IntelliSense since the RazorEngine.xml file is not included in the NuGet package.

Make Include methods on TemplateBase virtual

Currently only Include(string name) is defined as virtual. I would like to override the other overloaded Include methods in order to change the name of the template being requested e.g. a request for 'EmailLogo' would be changed to 'TT_EmailLogo' which is a branded variation of that template. Could these methods on TemplateBase also be made virtual so they can be overridden?

Load test (200 users, 10 minutes) generates exception on parsing

Code:
public override string Parse(string template, T data, string templateBaseName)
{
var templateBaseType = TemplateBaseService.GetTemplateBaseType(templateBaseName);
var config = new TemplateServiceConfiguration
{
BaseTemplateType = templateBaseType
};
string result;
using (var service = new RazorEngine.Templating.TemplateService(config)) {
try {
result = service.Parse(template, data, null, null);
}
catch (Exception ex) {
result = ex.Message;
}
}
return result;
}

this is the stack trace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames)
at Microsoft.CSharp.CSharpCodeGenerator.FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea)
at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea)
at RazorEngine.Compilation.DirectCompilerServiceBase.Compile(TypeContext context) in C:\Users\Matt\RazorEngine\src\Core\RazorEngine.Core\Compilation\DirectCompilerServiceBase.cs:line 88

Object '/xxxx/xxxx.rem' has been disconnected or does not exist at the server.

Using the IsolatedTemplateServices I am randomly finding this exception being thrown.

System.Runtime.Remoting.RemotingException

Object '/5d79aa48_fe69_459e_9dbe_3f5ddac771f9/l_lfl70rxb_fcqf7noaihy9b_23.rem' has been disconnected or does not exist at the server.

Server stack trace:
at System.Runtime.Remoting.Channels.ChannelServices.CheckDisconnectedOrCreateWellKnownObject(IMessage msg)
at System.Runtime.Remoting.Channels.ChannelServices.SyncDispatchMessage(IMessage msg)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at RazorEngine.Templating.ITemplateService.Compile(String razorTemplate, Type modelType, String name)
at RazorEngine.Templating.IsolatedTemplateService.Compile(String razorTemplate, Type modelType, String name)
at MyOffers.Handlers.LandingPageHandler.LoadTemplate(String templateName)
at MyOffers.Handlers.LandingPageHandler.<>c__DisplayClass8.b__6(String s)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at MyOffers.Handlers.LandingPageHandler.ProcessRequest(HttpContext context)

Summarised code is:

public static IsolatedTemplateService templateService = new IsolatedTemplateService();

string templateText = File.ReadAllText(templateName);

templateService.Compile(templateText, typeof (PageModel), templateName);

This happens after leaving the IsolatedTemplateService alone for a period of time. I figured that the appdomain it was using to load the templates had somehow died, however after that creating a new instance of the template service, the exception remains.

In the end I have to reload the app to get it to work again.

How can I avoid this? Or atleast, how can i recover the situation if it happens?

Views referencing RazorGenerator templates work in debugger only

I'm trying to use RazorEngine against views that reference templated helpers that have been pre-compiled using RazorGenerator. When I do so, everything works 100% fine as long as I have the debugger attached (i.e. run with F5) but when I run standalone (i.e. run with Ctrl-F5) I get the exception below. I suspect that the assembly that RazorEngine is generating for my view doesn't include a reference to the System.Web.WebPages assembly -- is there a way that I can specify a list of assemblies to be included when my view is compiled?

Unhandled Exception: RazorEngine.Templating.TemplateCompilationException: Unable to compile template. The type 'System.Web.WebPages.HelperResult' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
'.

Other compilation errors may have occurred. Check the Errors property for more information.
at RazorEngine.Compilation.DirectCompilerServiceBase.CompileType(TypeContextcontext)
at RazorEngine.Templating.TemplateService.CreateTemplateType(String razorTemplate, Type modelType)
at RazorEngine.Templating.TemplateService.CreateTemplateType(String razorTemplate)
at RazorEngine.Templating.TemplateService.CreateTemplate(String razorTemplate)
at RazorEngine.Templating.TemplateService.Parse(String razorTemplate)
at ConsoleApplication2.Program.Main(String[] args) in d:\temp\ConsoleApplication2\Program.cs:line 20

Streamlining the ITemplateService API

Hi All,

Scott Nickel (https://github.com/scottnickel) has been investigating the possibility of streamling the ITemplateService API. Currently we offer a number of overloads for supporting generic arguments, e.g. Parse<T>(string template, T model).

This design was done for a number of reasons:

  1. We had defined a generic ITemplate<T> template, allow you to access the model in a statically typed way, and extend upon the generic definition, by subclassing TemplateBase<T>.
  2. We were using the generic XXX<T> methods to support dynamic, so we could easily cast back to ITemplate<dynamic> when setting dynamic models (and also anonymous models).
  3. We were using the generic arguments to support setting the template model, by casting back to an ITemplate<T>, instead of using reflection (via SetModelExplicit).

What could potentially be achieved, is the removal of these generic overloads in favour of a set of simpler overloads (e.g. Parse(string, object), Run(string, object), Compile(string, object, name), etc.).

But before I commit myself to making this change, I need to understand how this will likely affect you, the users of the library. Currently were still technically tagged as beta, and I'd like to move the project forward to release, but this is an opportunity to tackle a breaking API change before we hit a final release.

What do you think?

Template Exceptions Do Not quote cshtml line number

I am occasionally getting error messages from templates when things are broken, however the exception is reported as being on Execute(). This doesn't give developers any hint as to where the problem lies in what could be a quite complicated template.

Is there any scope for useful error messages?

Controlling the caching criteria

It'd be nice to be able to control the cache a bit more directly or even be able to replace the caching implementation.

I made an implementation (of 3.0b8 off nuget) that reads from .cshtml files on disk. The problem is if I keep an instance of TemplateService around it caches based on the file name - which isn't sufficient data to invalidate the cache from. This can manifest itself in weird places like TemplateBase.Include() because the TemplateBase keeps an instance of the TemplateService around that you can't kill its cache by just using a new instance.

I ended up working around it by basically implementing my own external caching layer based on file timestamps and selectively overriding the TemplateBase.Include and ResolveLayout methods to use my own resolution instead of the template service's Resolve (which would hold on to the cached partials by file name even if the underlying file had changed).

I guess I could have also done something to the template keys like append the timestamp to the filename but that has its own set of funny behaviors because you wouldn't write TemplateBase.Include("myfile.cshtml201204252201") in a template ;)

I could also be going about this all wrong. I'd be happy to write up some code to fix this if we can agree on an approach.

Share state between view and Layout view?

I would like to be able to set some variable from within a content view, which gets rendered by its Layout view.
For example, in Razor for MVC I can do this: ViewBag.Title = "My Content Page".
Then, from within Layout.cshtml I can render that string like so: <title>@ViewBag.Title</title>

I tried to mimic that behavior by setting a custom base template which has a dynamic ViewBag property initialized to a new ExpandoObject, but it looks like as if the Layout template gets executed before the content template itself (causing a "Cannot perform runtime binding on a null reference" error, probably because Title is not yet set from the content page)

Passing a dynamic object without a property that template is expecting gives the following error : 'System.Dynamic.DynamicObject' does not contain a definition for 'Property Name'

Passing a dynamic object without a property that template is expecting gives the following error : 'System.Dynamic.DynamicObject' does not contain a definition for 'PropertyName'.
Is there a way to have Razor disregard the properties that's not in the dynamic object?

Below is the example.

template = @"This is standard Email Template.
Name:@Model.FullName

By:@Model.Author.
@Model.PropertyName"

Parse Method:
Razor.Parse(template, new { FullName="F - name", Author="author.." })

Using @helper methods defined in external templates

When using Razor with MVC, you can add a template in the App_Code directory that contains @Helper methods, and access these helper methods from other templates using TemplateName.HelperName() syntax.

Is something like this possible with RazorEngine? I investigated the generated classes, but they appear to be named randomly so the helpers aren't accessible as static methods on nicely-named classes. But perhaps I'm missing the correct approach for this.

If it's not currently possible, what do you think of naming the classes to match the template name to enable this?

Desired Usage Example

What I'm getting at would enable something like this.

string sharedHelperTemplate = "@helper MyMethod(string name) { Hello @name }";
string template1 = "@SharedHelpers.MyMethod(Model.Name). Welcome to Template1.";
string template2 = "@SharedHelpers.MyMethod(Model.Name). Welcome to Template2.";
service.Compile(sharedHelperTemplate, typeof(object), "SharedHelpers");
string result1 = service.Parse(template1, model);
string result2 = service.Parse(template2, model);

Provide MFC implementation example

I have a MVC ViewEngine/View/RazorEngine web application in C# that I will be posting for inclusion in the 3.0 release.

THis includes Standard Class, Anonymous Class, Dynamic Class, and ViewBag implementation examples.

I will update with the new MvcTemplateBase when that is available, push, and sumbit a pull request.

Scott

Use MvcTemplateBase and UrlHelper is null

Hi,

I use the MvcTemplateBase in my project with the newest 3.0 Beta 7 and my debugging thows a null exception if it parsed the line in my template where I do @Url.Content("...").

So, I think my Url is null, but how do I get it to work?

Best regards

TemplateService.Compile(string, string) fails

Hi,

I just noticed that when I run TemplateService.Compile(string, string) - it fails with this message:

Unable to compile template. The name 'Model' does not exist in the current context

This also happens when I use TemplateService.GetTemplate(string, string)

Thank you

Subclassed models don't carry through to the Layout

It's easiest to describe this bug via an example...

The following works:

public class Model {}

View.cshtml:
@model Model
@{ _Layout = "Layout"; }
...

Layout.cshtml:
@model Model
...

The following doesn't work:

public class Model {}
public class Model2 : Model {}

View.cshtml:
@model Model2
@{ _Layout = "Layout"; }
...

Layout.cshtml:
@model Model
...

The first example works fine but when I try to parse the 2nd example, I get the following exception:

System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=l1lqrdfo
StackTrace:
at CompiledRazorTemplates.Dynamic.cddfefecbdb.Execute()
at RazorEngine.Templating.TemplateBase.RazorEngine.Templating.ITemplate.Run(ExecuteContext context)
at RazorEngine.Templating.TemplateBase.RazorEngine.Templating.ITemplate.Run(ExecuteContext context)
at RazorEngine.Templating.TemplateService.Run(ITemplate template)
at RazorEngine.Templating.TemplateService.Parse[T](String razorTemplate, T model, String name)
at ConsoleApplication2.Program.Main4() in d:\Temp\ConsoleApplication2\Program.cs:line 62
at ConsoleApplication2.Program.Main(String[] args) in d:\Temp\ConsoleApplication2\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

Can't get it to work under .NET 4.5 RC

I've tried to use binaries with .net 4.5 RC and it fails when I run the project. I also tried to recompile the sources for 4.5 and seems like there are breaking changes in the latest .net so it won't compile. Any chance of getting a new version for .NET 4.5 soon?

Thank you very much.

Where am I?

Hi all, just wanted to give you a heads up. Been stupidly busy with work lately so haven't had a chance to look at anything in the last month at all. Hopefully I am going to get round to this in the next couple of weeks, still need to review and push v3.0.9 and flesh out the documentation.

Watch this space :)

Unit Tests Failing?

Is anyone else getting errors running Unit Tests? Specifically Issues 6 & 21? with latest in 3.0 branch?

Release_3_0_TestFixture : Failed
Issue21_SubclassModelShouldBeSupportedInLayout : Failed
Issue6_ModelShouldBePassedToLayout : Failed

They pass if I roll back to the 3.08Beta commit on Jan 31, 2012 "Stepped version number to 3.0.8beta".

Should the template be updated when using Compile<T> twice?

I'm having trouble updating a cached template.
I'm using my item id as the template name/key:

Service.Compile<MyType>(obj.TemplateHtml, obj.Id.ToString());

I ran this command once when initially loading and again when re-loading after saving the template.

But it doesn't update and calls to Service.Run(templateId, model); result in the old version of the template.

Should I be doing anything differently?

Thanks

Getting Raw Html to work..

Hey,

I am trying to get Razor support happening in https://github.com/JakeGinnivan/pretzel

Here is my Linqpad script against 3.0.8 (latest nuget package)

void Main()
{
    try
    {
        var config = new FluentTemplateServiceConfiguration(c=>c.EncodeUsing<MvcHtmlStringFactory>());
        new TemplateService(config).Parse("<h2>@(new RazorEngine.Text.HtmlEncodedString(\"<strong>Bold!</strong>\"))</h2>").Dump();

    }
    catch (TemplateCompilationException ex)
    {
    ex.Errors.Dump();
        ex.Dump();
    }
}
public class MvcHtmlStringFactory : IEncodedStringFactory
{
public IEncodedString CreateEncodedString(string rawString)
{
    return new HtmlEncodedString(rawString);
}

public IEncodedString CreateEncodedString(object obj)
{
obj.Dump();
    if (obj == null)
    return new HtmlEncodedString(string.Empty);

    var htmlString = obj as HtmlEncodedString;
    if (htmlString != null)
    return htmlString;


    return new HtmlEncodedString(obj.ToString());
}
}

The output is:

<h2>&lt;strong&gt;Bold!&lt;/strong&gt;</h2>

I have tried a heap of combinations and I just cannot get a Raw Html string outputted. Please point me in the right direction...

I'm getting intermittent "No template exists with name" errors

It's very weird, normally everything works, every now and again, I get this error on several templates. I restart the ASP.Net dev server and it goes away, then after some code rebuilds it comes back. No errors are thrown while calling Service.Compile, but when I call Service.Run it comes back with the "no template exists" error.

I fetch and compile templates on application start, it takes about 10 seconds in a newly spun thread with parallel foreach - if the template is accessed while it's compiling - can that cause this issue?

Are the compiled templates saved to disk as files? Could there be name collisions? What could cause a template to compile but not run afterwards?

Without parallelization it takes 30+ seconds, would be cool if there was a way to avoid recompiling them on every server restart.

Stack Trace :   at RazorEngine.Templating.TemplateService.Run[T](String name, T model)
in c:\*path*\RazorEngine3\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 990

Thanks

Including extensions in a template

I am creating a model dynamically. I'm trying to include a extension method in a template but it inst recognising the extension class. I am receiving the following error message " 'string' does not contain a definition for 'ToUpperFirstLetter' "

Model Creation

dynamic model = new ExpandoObject();
((IDictionary<string, object>)model).Add("Forename", "john");

Template

@using Namespace.Extensions
@{
     ViewBag.Title = "Title";
}

Hello @Model.Forename.ToUpperFirstLetter()

Extension Class

namespace Namespace.Extensions
{
    public static class StringExtensions
    {
         public static string ToUpperFirstLetter(this string source)
         {
             return ....removed for abbreviation
         }
    }
}

Razor Parsing

ITemplate template = Razor.Resolve(template, model);
string result = template.Run(new ExecuteContext());

How do you specify custom ITemplate class?

In order to implement @html, @Raw or any other helper for MVC, you must write your own template class with Html and Raw properties.

Currently, internally, only TemplateBase and TemplateBase<> are supported.

So you can create a derived class, but you can't do anything with it.

What am I missing?

Best practices for web app

Hi,

I want to use RazorEngine in an MVC app.
I want to have several templates that could be used in several places in the application.
What are the best practices for using the library in a web app - should I just be using
using (var service = new TemplateService())

wherever I want to use the templates? Will caching work if the template service is called like that? Or should I have a singleton somewhere?

Also, I've read that the previous version had support for pre-compiling the templates, I couldn't find the method Compile in Razor, so is it not in the new version yet? What's the difference between caching and pre-compiling anyway?

Thank you

v3 - TemplateService.Parse very slow

Hi,

I'm pretty sure these aren't the speeds I'm supposed to be getting

dynamic o = new ExpandoObject();
o.hello = "world";
var template = "@Model.hello";

TemplateService.Parse(template, o);

This repeatedly takes about 500-600ms. Similar (super simple) templates take 800-1000ms.
Is it because v3 builds in debug mode by default? I tried to change and rebuild but got nothing in the bin\Release folder.

EDIT: Pre-compiled templates are pretty fast - 100ms or so. Maybe I need to name the parse?

Maybe I misconfigured something?

Thank you

Compatible with Razor 2.0?

Trying to get RazorEngine to work again after upgrading a project from System.Web.Razor 1.0.0 to System.Web.Razor 2.0.0 (In MVC 4 Beta).

At first I was getting:

[FileLoadException: Could not load file or assembly 'System.Web.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
RazorEngine.Compilation.DefaultCompilerServiceFactory.CreateCompilerService(Language language) +0
RazorEngine.Templating.TemplateService.CreateTemplateType(String razorTemplate, Type modelType) +1143
RazorEngine.Templating.TemplateService.CreateTemplate(String razorTemplate, T model) +166
RazorEngine.Templating.TemplateService.Parse(String razorTemplate, T model) +187
RazorEngine.Razor.Parse(String razorTemplate, T model) +184

I added a binding redirect to the app:

  <dependentAssembly>
    <assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-1.0.0.0" newVersion="2.0.0.0" />
  </dependentAssembly>

Now, I get:

[MissingMethodException: Method not found: 'System.Collections.Generic.Dictionary2<System.String,BlockParser> System.Web.Razor.Parser.CSharpCodeParser.get_RazorKeywords()'.] RazorEngine.Compilation.CSharp.CSharpCodeParser..ctor() +0 RazorEngine.Compilation.RazorEngineHost.DecorateCodeParser(ParserBase incomingCodeParser) +138 System.Web.Razor.RazorTemplateEngine.CreateParser() +57 System.Web.Razor.RazorTemplateEngine.GenerateCodeCore(ITextDocument input, String className, String rootNamespace, String sourceFileName, Nullable1 cancelToken) +79
System.Web.Razor.RazorTemplateEngine.GenerateCode(TextReader input, String className, String rootNamespace, String sourceFileName, Nullable1 cancelToken) +126 System.Web.Razor.RazorTemplateEngine.GenerateCode(TextReader input) +85 RazorEngine.Compilation.CompilerServiceBase.GetGeneratorResult(RazorEngineHost host, String template) +187 RazorEngine.Compilation.CompilerServiceBase.GetCodeCompileUnit(String className, String template, ISet1 namespaceImports, Type templateType, Type modelType) +982
RazorEngine.Compilation.DirectCompilerServiceBase.Compile(TypeContext context) +442
RazorEngine.Compilation.DirectCompilerServiceBase.CompileType(TypeContext context) +189
RazorEngine.Templating.TemplateService.CreateTemplateType(String razorTemplate, Type modelType) +1526
RazorEngine.Templating.TemplateService.CreateTemplate(String razorTemplate, T model) +166
RazorEngine.Templating.TemplateService.Parse(String razorTemplate, T model) +187
RazorEngine.Razor.Parse(String razorTemplate, T model) +184

This is with the latest RazorEngine nuget package.

Is RazorEngine not compatible with System.Web.Razor 2.0.0?

Model with Nullable

Hallo.

If one property of the model is Nullable, like int?,
then the Run method will throw a NullReferenceException.

regards,

<razorEngine> configuration section not being fully loaded

The code examines the configuration section for specific values:

DefaultLanguage

I am attempting to add for my template and this is ignored.

There is an XmlTemplateServiceConfiguration that has code to handle this [AddNamespaces()], but this class is not used anywhere in the code.

I have modified the code for my purposes to properly load the configuration section element.

I can provide this code if necessary, but I didn't know where you were going with the XmlTemplateServiceConfiguration class.

Scott

Encoding issue

I can't figure out how to get strings with quotes to come out correctly. I have a property on a class that I want to show in the output of my razor file but the engine is encoding it the wrong way no matter what I do. I'm using the 3.0.8.0 RazorEngine assembly.

This is what its outputting. Two quotes, then a line break (huh?), followed by two more quotes. There shouldn't be two double quotes nor should there be a line break. What in the world is going on?

@Raw(item.Value) produces this:
""
this is my constant value ""

@(item.Value) produces this:
& quot; & quot;
this is my constant value & quot; & quot;

Razor snippet:
@Raw(item.Value)
@(item.Value)

C# class property snippet:

public string Value
{
    get
    {
        int number;
        if (Int32.TryParse(_value, out number))
            return _value;

        if (_value.IsNullOrEmpty())
            return "\"\""; // empty double quotes
        else
            return String.Format("\"{0}\"", _value);
    }
    set
    {
        _value = value;
    }
}

@Include includes the wrong model.

In version 2.0 I had no trouble making a template that included other templates but in version 3.0 the Model from the Parse function is passed down to all the templates i have run.

Razor.Compile("NameB: @Model.Name", (new { }).GetType(), "TemplateB");
Razor.Run("TemplateB", new { Name = "testB" });

Razor.Compile("NameA: @Model.Name\r@Include(\"TemplateB\")", (new { }).GetType(), "TemplateA");
Razor.Run("TemplateA", new { Name = "testA" });

return Razor.Parse("Name: @Model.Name\r@Include(\"TemplateA\")", new { Name = "testRoot" });

Output: Name: testRoot NameA: testRoot NameB: testRoot

Expected output: Name: testRoot NameA: testA NameB: testB

Null string throws Object reference not set to an instance of an object

hi,

in previous version, when i pass a null string to the parser, it will render and output as if it were an empty string. but in version 3 of razorengine, it throws an object reference not set to an instance of an object.

here's the sample code:

        using (var service = new TemplateService())
        {
            const string template = "<h1>Hello @Model.Person.Forename</h1>";
            const string expected = "<h1>Hello </h1>";

            var model = new {Person = new Person {Forename = null}};
            string result = service.Parse(template, model);

            Assert.That(result == expected, "Result does not match expected: " + result);
        }

currently, my workaround is to not use anonymous objects and just define a class as a container for the objects i want to pass along to the parser. is there a better workaround?

thanks for the really neat engine.

jake

Unable to compile template. 'object' does not contain a definition for 'name' and no extension method 'name' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

I am receiving this error no matter what I do to parse any template. I have tried various methods including passing a type to the parse method. Nothing seems to work, maybe I am doing it wrong? fyi I am using 3.0.8 with .net 4

Here is my code
MvcHelper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RazorEngine;
namespace RazorEngineTest.Helpers
{
    public static class MvcHelper
    {
        public static IHtmlString RenderTemplate(this HtmlHelper helper, string template)
        {
            return helper.Raw(RazorEngine.Razor.Parse(template));
        }

        public static IHtmlString RenderTemplate<T>(this HtmlHelper helper, string template, T model)
        {
            return helper.Raw(RazorEngine.Razor.Parse(template, (object)model));
        }
    }
}

Render Model class

namespace RazorEngineTest.Models
{
    public class RenderModel
    {
        public string Template { get; set; }
        public object ModelData { get; set; }
    }
}

View Controller

return View(new RenderModel() { Template = "Hello @Model.name", ModelData = new { name="Brian" } });

The View

@using RazorEngineTest.Helpers
@model RazorEngineTest.Models.RenderModel
@{
    ViewBag.Title = "Render";
}

@Html.RenderTemplate(Model.Template, Model.ModelData)

Layout cannot reference model

See: https://gist.github.com/1402784

Result:
Unhandled Exception: RazorEngine.Templating.TemplateCompilationException: Unable to compile template. The name 'Model' does not exist in the current context

The model does not seem to be passed to the layout as it is choking on the name 'Model'.

What is the correct way to reference the model from a Layout page?

MvcHtmlString still gets HtmlEncoded

I'm sharing a partial view with a full MVC3 view and a RazorEngine template. It needs to be strongly typed, so I pulled the latest from github this morning to get support for @model.

The problem is my view has an HtmlHelper in it that returns an MvcHtmlString. I have the helper working fine (cobbled together below, will change to MvcTemplateBase if that makes the cut), but the problem is RazorEngine is escaping it and I'm seeing raw HTML in the result. RazorEngine 2.1 did not do this. Any idea where I should look?

This is the basic code I'm using:

public string SomeMethod<T>(string templateDocument, T model)
{
    //Razor.SetTemplateBase(typeof(MyCustomTemplateBase<>));
    var config = new TemplateServiceConfiguration
    {
        BaseTemplateType = typeof(MyCustomTemplateBase<>)
    };

    using (var service = new TemplateService(config))
    {
        try
        {
            return service.Parse(templateDocument, model);
        }
        catch (TemplateCompilationException ex)
        {
            // exception says "see errors" but the errors aren't actually caught and logged automatically
            throw new Exception(string.Join("\n", ex.Errors), ex);
        }
    }
}

public abstract class MyCustomTemplateBase<T> : TemplateBase<T>
{
    public TemplateWriter RenderPart<T>(string path, T model = default(T))
    {
        var text = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(path));
        var tmpl = this.TemplateService.GetTemplate(text, model, path);
        return this.Include(path, model);
        //return RazorEngine.Razor.Parse(System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath(path)), model);
    }

    private HtmlHelper _Html = null;
    public HtmlHelper Html
    {
        get
        {
            if (this._Html == null)
            {
                var container = new InternalViewDataContainer<T>(this.Model);
                var context = new ViewContext(
                    new ControllerContext(),
                    new InternalView(),
                    new ViewDataDictionary(),
                    new TempDataDictionary(),
                    new System.IO.StringWriter(new System.Text.StringBuilder()));
                this._Html = new HtmlHelper<T>(context, container);
            }
            return this._Html;
        }
    }

    private class InternalView : IView
    {
        public void Render(ViewContext context, System.IO.TextWriter writer) { }
    }

    private class InternalViewDataContainer<T> : IViewDataContainer
    {
        public InternalViewDataContainer(T model)
        {
            ViewData = new ViewDataDictionary<T>(model);
        }
        public ViewDataDictionary ViewData { get; set; }
    }
}

Templates exchanged between concurrent users

Hi,

We have a case where we send emails to users using razor engine in a web service. Its so happening that two users who did some processing at the exact same time got each others email message. We read comments on your blogs in which you mention the design issue with razor engine.

"The key change that prompted this was the overwhelming need to run RazorEngine in parallel/multi-threaded scenarios. Because of how RazorEngine v2 was laid out under the hood, there were a number of mistakes that were made in its design, and thread-safety was a big one. Currently, attempting to run RazorEngine v2.1 in a multi-threaded way nearly always ends badly, you’ll get a hideous amount of mangled template output and/or failed compiles. This has prompted me to redesign the API to support multi-threaded scenarios natively."

We cannot wait for the release of v3. Is there a neat stop-gap solution that you suggest to overcome this issue?

Thanks,
Shez

@Html.Raw doesn't work

I'm trying to render a string variable that contains html tags using @Html.Raw. This doesn't work. How to I render this variable without it being encoded?

Keep a cache of compiled templates

Hi

It is more a request than an issue.

I would like to be able to save the compiled templates between two runs f my application.

The main reason is that I'm using Razor to generate letters and reports in a Windows application. Compiling complex templates can takes some times, and it slow down the first generation even if the templates did'nt change very often.

Tks

ViewBag initialization not possible outside of template

The Parse/Run APIs do not provide a way to pass in ViewBag contents.

Only ViewBag properties set/get from the page will work.

I have extended the interfaces/classes with overloads to provide this functionality.

This will allow an application to initialize ViewBag contents before executing the template and the template @ViewBag will contain the initialized values.

Let me know if you would like me to upload those changes.

Scott

Model properties cannot be inferred from a model parameter

This works as expected:
public string ApplyTemplate(dynamic model)
{
string template = @"

@foreach(int x in Model.Numbers){}
";
string applied = Razor.Parse(template, new { Numbers = new int[] { 1, 2, 3 } });
return applied;
}

However if I do this:
public string ApplyTemplate(dynamic model)
{
string template = @"

@foreach(int x in Model.Numbers){}
";
string applied = Razor.Parse(template, model);
return applied;
}

and call the code from a separate class like this:
var result = _service.ApplyTemplate(new { Numbers = new int[] { 1, 2, 3 } });

I get:
Unable to compile template. 'object' does not contain a definition for 'Numbers' and no extension method 'Numbers' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Putting the model from the inline call in a variable and then comparing them both doesn't seem to reveal a difference between the two objects.

No HttpContext or WebPageContext in Template class

I am trying to generate Razor Templates as html fixures for unit testing. I need to be able to load the files outside any httpcontext and render the templates. This solution in Issue #26 assumes that I have an HttpContext and a WebPageContext it seems. Does anyone have any suggestions how I would go about this? For everyone's reference i am putting the solution from issue 26 here inline:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RazorEngine;
using RazorEngine.Templating;
using System.Web.Mvc;
using System.Web.WebPages;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace System.Web.Mvc
{

[RequireNamespaces("System.Web.Mvc.Html")]
public class HtmlTemplateBase<T>:TemplateBase<T>, IViewDataContainer
{
    private HtmlHelper<T> helper = null;
    private ViewDataDictionary viewdata = null;
    private System.Dynamic.DynamicObject viewbag = null;
    private UrlHelper urlhelper = null;

    public dynamic ViewBag
    {
        get
        {
            return (WebPageContext.Current.Page as WebViewPage).ViewBag;
        }
    }

    public HtmlHelper<T> Html
    {
        get
        {
            if (helper == null)
            {
                var p = WebPageContext.Current;
                var wvp = p.Page as WebViewPage;
                var context = wvp != null ? wvp.ViewContext : null;
                helper = new HtmlHelper<T>(context, this, RouteTable.Routes);
            }
            return helper;
        }
    }

    public UrlHelper Url
    {
        get
        {
            if (urlhelper == null)
            {
                urlhelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
            }
            return urlhelper;
        }
    }

    public ViewDataDictionary ViewData
    {
        get
        {
            if (viewbag == null)
            {
                var p = WebPageContext.Current;
                var viewcontainer = p.Page as IViewDataContainer;
                viewdata = new ViewDataDictionary(viewcontainer.ViewData);

                if (this.Model != null)
                {
                    viewdata.Model = Model;
                }

            }

            return viewdata;
        }
        set
        {
            viewdata = value;
        }

    }

}

}

RazorEngine class names are not guranteed unique

So the implementation of the dictionary of cached razor templates is required to be unique by name:

       internal ITemplate GetTemplate(string template, Type modelType, string name)
       {
        if (!string.IsNullOrEmpty(name))
            if (templateCache.ContainsKey(name))
                return templateCache[name];

        var instance = CreateTemplate(template, modelType, name);

        if (!string.IsNullOrEmpty(name))
            if (!templateCache.ContainsKey(name))
                templateCache.Add(name, instance);

        return instance;
    }

but then a random string based on a GUID is used for the class names. This random string is not tested to see if there is a conflict prior to code compilation:

    public static string GenerateClassName()
    {
        Guid guid = Guid.NewGuid();
        return Regex.Replace(guid.ToString("N"), @"[^A-Za-z]*", "");
    }

I have had collisions on names for classes.

Template call from a Template escapes the html

I have a class that exposes the RazorEngine so templates can call templates. Like:

@using TemplateEngine
<h1>hello world</h1>@TemplateEngine.Partial(null, null, "html2")

where html2 is:

<h2>hello world also</h2>

I'm expecting

Expected: "<h1>hello world</h1><h2>hello world also</h2>"
  But was:  "<h1>hello world</h1>&lt;h2&gt;hello world also&lt;/h2&gt;"

Is there an option I'm not setting?

Templete for model as Object

Hallo.

All Methods with the Parameter "object model" dont work and
the Generic Paramter "T model"w where T is object dont work
either.

My only current workaroung:

Object model = new { Name = "Matt" };
var service = new TemplateService();
service.Compile(template, model.GetType(), "tmp");
var result = service.Run("tmp", model)

regards,

@Html (HtmlHelper instance) cannot be resolved

I am trying to call various @html helper methods and the template will not compile saying:

"Unable to compile template. The name 'Html' does not exist in the current context"

Use a very simple template like this:

string template = "@using System.Web.Mvc @Html.Raw("some html stuff")";
Razor.Parse(template);

I added an instance of HtmlHelper to ViewBag and accessed the .Raw() method through there, but it still HtmlEncodes the output.

Thanks,

Scott

Does not contain a definition for 'First'

I am trying to introduce Linq extensions into a project I am using and continue to get the error:

'System.Collections.Generic.List' does not contain a definition for 'First'

when executing the .First() extension method.

I've tried updated various web.config settings per the documentation, but can't seem to remedy the error.

I did interrogate TemplateService _config private variable and it appears the these three namespace are configured:

System
System.Collections.Generic
System.Linq

but no changes I make to web.config seem to alter that configuration - so I may be chasing a rabbit.

Any help would be greatly appreciated.

Best regards and thanks for this excellent project.

Hal

SecurityException when used IsolatedTemplateService

When I use IsolatedTemplateService with "sandbox" I get a SecurityException with description "Request failed" and no details that would help me understand the problem.
I create a sandbox with the following code:

private AppDomain CreateAppDomain()
{
    var permissionSet = new PermissionSet(null);
    permissionSet.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
    permissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
    var assemblies = AppDomain.CurrentDomain.GetAssemblies()
    .First( x => x.GetName().Name ==  "RazorEngine" )
    .Evidence.GetHostEvidence<StrongName>();
            
    return AppDomain.CreateDomain("RazorTestHost", AppDomain.CurrentDomain.Evidence,
    AppDomain.CurrentDomain.SetupInformation, permissionSet, assemblies);
}

If I use IsolatedTemplateService with default AppDomainFactory It works fine, but I need some restrictions on executable code.

Bug: using a resolved Layout inside a strongly typed TemplateBase throws an ArgumentException

I have two razor views: Content.cshtml & Layout.cshtml.
I configured the TemplateService with a resolver that resolves the _Layout (which is set to "Layout.cshtml").
When I parse Content.cshtml while having the TemplateService configured to use a strongly typed TemplateBase<>, an exception is thrown from the CompilerServiceBase class in the method BuildTypeName:

"The template type is a generic defintion, and no model type has been supplied.".

The model type has indeed not been specified, since the Resolve method was called from the Resolver delegate without passing a model:

new DelegateTemplateResolver(x => _templateProvider.LoadTemplate(x)).

In summary: parsing a view (using a strongly typed TemplateBase) that has its _Layout property set to another view causes an ArgumentExeption: "The template type is a generic defintion, and no model type has been supplied.".

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.