toddams/razorlight

Use Razor to build templates from Files / EmbeddedResources / Strings / Database or your...

Use Razor to build templates from Files / EmbeddedResources / Strings / Database or your custom source outside of ASP

RazorLight

Use Razor to build templates from Files / EmbeddedResources / Strings / Database or your custom source outside of ASP.NET MVC. No redundant dependencies and workarounds in pair with excellent performance and .NET Standard 2.0 and .NET Core 3.0 support.

Solidarity with Ukraine

Dear friends, my name is Ivan, I am the guy who created this library. I live in Ukraine, and if you are reading this message - I really hope you and your family are safe and healthy. 24 February Russia invaded my country with a series of missle atacks across entire Ukraine, from East to West. They started with destroying military infrastructure, and so-called "special operation", as they call it, in fact is a full scale war against us. They planned for a 3 days Blitzkrieg, but as we are standing for 9 days already, you can clearly see how strong ukrainians are. Citizens of the cities are joining the Teritorial Defence, office workers, waiters, lawyers, software engineers, we are ready to defend our land. Putin started to bomb civilians with air strikes and missles from Russian and Belarus. This is not about military infrastructure anymore. People are duying! Tomorrow the war can knock to your house, but Ukraine is the border between civilized West and Russia. Please stay safe and thank you for your support!

I am a volunteer who is helping our Teritorial Defence (TO) to get radio communication, first aid kits, clothes, etc abroad. All these really important goods are not in stock in Ukraine already, so I am doing my best to find it anywhere in the Europe. We have logistics, we have transport across the border, we have everything.

I am begging for your help

Please, don't stand aside, we need your help. If you are able to donate - you are contributing to saving peace, you are saving human lives. I am creating a discord channel, where I will post everything I buy, share the progress and keep a communication with you. Every penny I recieve will go to the Ukrainian Army and TO.

EUR (Inside EU and SEPA) Account holder: Ivan Balan Balan

BIC: TRWIBEB1XXX
IBAN: BE69 9672 7063 1578
Address:
Avenue Louise 54, Room S52 Brussels 1050 Belgium

EUR (Outside EU and SEPA) Account Holder: Ivan Balan Balan

SWIFT/BIC: TRWIBEB1XXX
IBAN: BE69 9672 7063 1578
Address:
Avenue Louise 54, Room S52 Brussels 1050 Belgium

USD (Inside the US only) Account holder: Ivan Balan Balan

Routing number: 084009519

Account number: 9600002966507311

Account type: Checking

Address:

19 W 24th Street New York NY 10010 United States

Table of contents

  • Quickstart
  • Template sources
    • Files
    • Embedded resources
    • Database (custom)
  • Includes (aka Partial)
  • Encoding
  • Additional metadata references
  • Enable Intellisense support
  • FAQ

Quickstart

Install the nuget package using following command:

`

The simplest scenario is to create a template from string. Each template must have a ` that is associated with it, so you can render the same template next time without recompilation.

snippet source | anchor

To render a compiled template:

snippet source | anchor

Template sources

RazorLight can resolve templates from any source, but there are a built-in providers that resolve template source from filesystem and embedded resources.

File source

When resolving a template from filesystem, templateKey - is a relative path to the root folder, that you pass to RazorLightEngineBuilder.

snippet source | anchor

EmbeddedResource source

For embedded resource, the key is the namespace of the project where the template exists combined with the template's file name.

The following examples are using this project structure: `

snippet source | anchor

Setting the root namespace allows you to leave that piece off when providing the template name as the key:

snippet source | anchor

Custom source

If you store your templates in database - it is recommended to create custom RazorLightProject that is responsible for gettings templates source from it. The class will be used to get template source and ViewImports. RazorLight will use it to resolve Layouts, when you specify it inside the template.

`

You can find a full sample here

Includes (aka Partial views)

Include feature is useful when you have reusable parts of your templates you want to share between different views. Includes are an effective way of breaking up large templates into smaller components. They can reduce duplication of template content and allow elements to be reused. This feature requires you to use the RazorLight Project system, otherwise there is no way to locate the partial.

` First argument takes a key of the template to resolve, second argument is a model of the view (can be null)

Encoding

By the default RazorLight encodes Model values as HTML, but sometimes you want to output them as is. You can disable encoding for specific value using @Raw() function

In order to disable encoding for the entire document - just set variable to true `

Enable Intellisense support

Visual Studio tooling knows nothing about RazorLight and assumes, that the view you are using - is a typical ASP.NET MVC template. In order to enable Intellisense for RazorLight templates, you should give Visual Studio a little hint about the base template class, that all your templates inherit implicitly

`


FAQ

Coding Challenges (FAQ)

How to use templates from memory without setting a project?

The short answer is, you have to set a project to use the memory caching provider. The project doesn't have to do anything. This is by design, as without a project system, RazorLight cannot locate partial views.

:x: You used to be able to write:

... but this now throws an exception, saying, "_razorLightProject cannot be null".

:heavy_check_mark:

Affects: RazorLight-2.0.0-beta1 and later.

Original Issue: https://github.com/toddams/RazorLight/issues/250

How to embed an image in an email?

This isn't a RazorLight question, but please see this StackOverflow answer.

How to embed css in an email?

This isn't a RazorLight question, but please look into PreMailer.Net.

Compilation and Deployment Issues (FAQ)

Most problems with RazorLight deal with deploying it on a new machine, in a docker container, etc. If it works fine in your development environment, read this list of problems to see if it matches yours.

Additional metadata references

When RazorLight compiles your template - it loads all the assemblies from your entry assembly and creates MetadataReference from it. This is a default strategy and it works in 99% of the time. But sometimes compilation crashes with an exception message like "Can not find assembly My.Super.Assembly2000". In order to solve this problem you can pass additional metadata references to RazorLight.

`

I'm getting errors after upgrading to ASP.NET Core 3.0 when using runtime compilation

Please see: https://docs.microsoft.com/en-us/aspnet/core/razor-pages/sdk?view=aspnetcore-3.1#use-the-razor-sdk

Starting with ASP.NET Core 3.0, MVC Views or Razor Pages aren't served by default if the RazorCompileOnBuild or RazorCompileOnPublish MSBuild properties in the project file are disabled. Applications must add an explicit reference to the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package if the app relies on runtime compilation to process .cshtml files.

I'm getting a Null Reference Exception after upgrading to RazorLight-2.0.0-beta2 or later.

The most common scenario is that some people were using RazorLight's ability to render raw strings as templates. While this is still somewhat supported (you can't use advanced features like partial views), what is not supported (right now) is using the caching provider with raw strings. A workaround is to use a dummy class.

I'm getting "Cannot find compilation library" when I deploy this library on another server

Add these property groups to your entry point csproj. It has to be the entry point project. For example: ASP.NET Core web project, .NET Core Console project, etc.

`

I'm getting "Can't load metadata reference from the entry assembly" exception

Set PreserveCompilationContext to true in your *.csproj file's PropertyGroup tag.

`

Additionally, RazorLight allows you to specifically locate any MetadataReference you can't find, which could happen if you're running in SCD (Self-Contained Deployment) mode, as the C# Compiler used by RazorLight needs to be able to locate mscorlib.dll. This might be a useful trick if future versions of the .NET SDK tools ship with bad MSBuild targets that somehow don't "preserve compilation context" and you need an immediate fix while waiting for Microsoft support.

I'm getting "Cannot find reference assembly 'Microsoft.AspNetCore.Antiforgery.dll'" exception on .NET Core App 3.0 or higher

By default, the 3.0 SDK avoids copying references to the build output. Set PreserveCompilationReferences and PreserveCompilationContext to true in your *.csproj file's PropertyGroup tag.

`

For more information, see https://github.com/aspnet/AspNetCore/issues/14418#issuecomment-535107767 (which discusses the above flags) and https://github.com/microsoft/DockerTools/issues/217#issuecomment-549453362 (which discusses that Runtime Compilation feature was marked obsolete in ASP.NET Core 2.2, and removed from the default template in ASP.NET Core 3.0).

RazorLight does not work properly on AWS Lambda or Azure Functions

Serverless solutions are not supported yet. However, for Azure Functions, some users have reported success on Azure Functions 3.0.3. As of 6/3/2020, Azure Functions SDK team has acknowledged a bug in Azure Functions RemoveRuntimeDependencies task, affecting Azure Functions 3.0.4-3.0.6 releases.

For Azure Functions 3.0.4-3.0.5, the known workaround is to disable "Azure Functions dependency trimming". To disable dependency trimming, add the following to your root / entrypoint project:

In addition, Azure Functions has an open pull request outstanding to update runtimeAssemblies.json: https://github.com/Azure/azure-functions-vs-build-sdk/issues/422

Unsupported Scenarios

RazorLight does not work with ASP.NET Core Integration Testing

RazorLight is not currently designed to support such integration tests. If you need to test your RazorLight tests, current recommendation is to simply create a project called <YourCompanyName>.<YourProjectName>.Templating and write your template rendering layer as a Domain Service, and write tests against that service. Then, you can mock in your integration tests any dependencies on RazorLight.

If you happen to get this working, please let us know what you did.

Issues

Quick list of the latest Issues we found

MarkKharitonov

MarkKharitonov

Icon For Comments6

Hi, My use case - I am calling a small exe tool wrapping RazorLight from Powershell. I have just a few templates, but a lot of model objects. In order to keep the Powershell code well organized I end up calling the tool for the same templates multiple times. As a result the performance is abysmal.

However, if I could persist the generated assembly, then there would be a way to reuse it across the different calls.

Unfortunately, I failed to find how to do it.

What am I missing?

P.S. I asked the same question on SO - https://stackoverflow.com/questions/73081390/is-there-an-off-the-shelf-implementation-of-the-razorlights-icachingprovider-th

mikart143

mikart143

Icon For Comments1

So this builder is basically broken. When adding ExcludedAssemblies via method ExcludeAssemblies() the DefaultMetadataReferenceManager will not receive those elements, because it was added to services (via services.TryAddSingleton<IMetadataReferenceManager, DefaultMetadataReferenceManager>();) before finishing setting the RazorLightOptions. The constructor in DefaultMetadataReferenceManager with IOptions will receive outdated data (empty list in it). So my suggestion is to remove AddRazorLight(this IServiceCollection services) and replace this with AddRazorLight(this IServiceCollection services, Action<RazorLightOptions> opts); This way we will be able to init all options before registering all other services.

passronny

passronny

Icon For Comments1

hi I am using razorlight in .net core2.2 MVC web project, i have registered the services of razorlight in the Startup.cs class as shown below

` var engine = new RazorLightEngineBuilder() .UseEmbeddedResourcesProject(System.Reflection.Assembly.GetEntryAssembly()) //.UseFileSystemProject($"{RootPath}\Views") .EnableDebugMode(true) .UseMemoryCachingProvider() .Build();

services.AddSingleton<IRazorLightEngine>(engine); `

i have also created a generic class that converts my views to string , one of the methods is below

` public async Task GenerateNotificationContent(string messageBody, string pathToView) { var model = new CustomEmailMessageModel { MessageBody = messageBody
};

return await razorLightEngine.CompileRenderAsync($"{pathToView}", model); } `

the views that i want are in the Views folder of the project, so when calling the above method i provide the path to the view that i want e.g Views/Subfolder/View but im getting the below error

RazorLightProjectItem of type RazorLight.Razor.EmbeddedRazorProjectItem with key Views/Subfolder/view.cshtml could not be found by the RazorLightProject of type RazorLight.Razor.EmbeddedRazorProject and does not exist in dynamic templates. See the "KnownDynamicTemplateKeys" and "KnownProjectTemplateKeys" properties for known template keys.

what am i doing wrong

toddams

toddams

Announcement
Icon For Comments1

Dear friends, my name is Ivan, I am the guy who created this library. I live in Ukraine, and if you are reading this message - I really hope you and your family are safe and healthy. 24 February Russia invaded my country with a series of missle atacks across entire Ukraine, from East to West. They started with destroying military infrastructure, and so-called "special operation", as they call it, in fact is a full scale war against us. They planned for a 3 days Blitzkrieg, but as we are standing for 9 days already, you can clearly see how strong ukrainians are. Citizens of the cities are joining the Teritorial Defence, office workers, waiters, lawyers, software engineers, we are ready to defend our land. Putin started to bomb civilians with air strikes and missles from Russian and Belarus. This is not about military infrastructure anymore. People are duying! Tomorrow the war can knock to your house, but Ukraine is the border between civilized West and Russia. Please stay safe and thank you for your support!

I am a volunteer who is helping our Teritorial Defence (TO) to get radio communication, first aid kits, clothes, etc abroad. All these really important goods are not in stock in Ukraine already, so I am doing my best to find it anywhere in the Europe. We have logistics, we have transport across the border, we have everything.

I am begging for your help Please, don't stand aside, we need your help. If you are able to donate - you are contributing to saving peace, you are saving human lives. I am creating a discord channel, where I will post everything I buy, share the progress and keep a communication with you. Every penny I recieve will go to the Ukrainian Army and TO.

I have attached my bank details in a readme of the repository, if you are able to donate any amount, literally every penny can save a human life.

Thank you so much! Stay safe

slav40o

slav40o

Icon For Comments0

Hi there, I have small proposal for the FileSystemRazorProjectItem.cs.

Currently it is using FileInfo and not IFileInfo interface as input parameter. I've created custom RazorLightProject class that has specific search terms for embedded resource files in multiple assemblies. The problem is that I'm using custom IFileInfo implementation and cannot create FileSystemRazorProjectItem.

For now I am using with TextSourceRazorProjectItem while testing this library, but I think that it will be better to be more abstract and use IFileInfo in the file class.

AndreyMisnikov

AndreyMisnikov

Icon For Comments2

Hello!

If I define razor light engine as RazorLightEngine engine = new RazorLightEngineBuilder() .UseEmbeddedResourcesProject(typeof(RazorModel)) .SetOperatingAssembly(typeof(RazorModel).Assembly) .UseMemoryCachingProvider() .Build();

and then use engine.CompileRenderStringAsync(razorTemplateKey, content, model)

I have the issue with encoding when my content contains Russian. Is it possible to specify some kind of encoding for Engine by default?

I have created a lot of templates in my project with localization and as temporary fix I use content = "@using RazorLight @{ DisableEncoding = true; }" + content;

I would like to have an option to set some property to engine and be able to work with any language.

adrian-ubalde

adrian-ubalde

Icon For Comments0

Hello RazorLight team 👋 ,

A recent security vulnerability scan of my application (which has a dependency on Snyk scan tool, has detected a Remote Code Execution security vulnerability (please see attached screenshot for details).

There is a security vulnerability on the system.text.encodings.web package (detailed here on the Snyk website and in the dotnet website) which the I was looking to see if there is an available patch for this vulnerability on the Nuget website but I didn't see one. I'm wondering if there are any plans to create a patch for this vulernability?

Thank you in advance.

Kind regards, Adrian

image

junalmeida

junalmeida

dotnet:runtimehost:azurefunctions
Icon For Comments41

Describe the bug RazorLight is throwing the following exception when running engine.CompileRenderAsync

To Reproduce It seems like an incompatibility between dependencies, but I couldn't figure out exactly which one.

Expected behavior It seems the said WriteTo method in ViewBuffer class is a reference of the interface IHtmlContent, in the assembly Microsoft.AspNetCore.Html.Abstractions v2.1.0. The weird part is that this nuget package is apparently abandoned, the link to the project points to an archived repository, and I expect to see AspNetCore being on version 3.1, not 2.1.

Information (please complete the following information):

  • OS: Windows 10
  • Platform: Net Core 3.1
  • RazorLight version: 2.0.0-rc.3
  • Are you using the OFFICIAL RazorLight package? yes
  • Visual Studio version: Visual Studio Community 2019 16.10.1 ]
afucher

afucher

feature-proposal
Icon For Comments8

Describe the bug I'm trying to use this package but when I publish using -p:PublishSingleFile=true, my application throws an error when the code touch this library.

To Reproduce Steps to reproduce the behavior:

  1. Build a project using RazorLight
  2. Publish the project using the argument -p:PublishSingleFile=true, for example: dotnet publish . -c Release -r win-x64 -p:PublishSingleFile=true
  3. Run the project, and make the application run the specific part that use RazorLight

Expected behavior I expected that my application works.

Information (please complete the following information):

  • OS: Windows 10
  • Platform .NET 5.0.100
  • RazorLight version 2.0.0-rc.3
  • Are you using the OFFICIAL RazorLight package? Yes
  • Visual Studio version: N/A, I'm using Rider.

Additional context

RedX2501

RedX2501

Icon For Comments0

Looking up a lot of documentation it seems that much of the new workflow in razor with .Net Core and Blazor has the temlates being pre-compiled.

My use-case is a bit different, the user can provide their on templates which are rendered at runtime.

This has the problem that as soon as he has 2 or more templates he will probably have common functionality that he might want to use in both scripts.

With @{ await IncludeAsync(...);} it is already possible to reuse code fragment which is nice. Unfortunately you can't stored the returned value in a variable.

What I'd like to do though is to reuse (static) functions to be able to store the value. It used to be possible as indicated by this StackOverflow question and answer: https://stackoverflow.com/questions/6347447/shared-mvc-razor-functions-in-several-views

With him providing the templates to an already compiled software means that he can't extend the Model or write some new class to share the functions. Two common "solutions" I found for the problem.

I thought that it might work out of the box here with file system projects if I was lucky and all templates were inside the same dll but it seems the generated code is not like that.

So am I missing something and this feature is available but just under-documented?

If not I'd like to ask if you also think this feature request is sensible and whether we could plan to introduce it.

agross

agross

feature-proposal
Icon For Comments1

Is your feature request related to a problem? Please describe.

I need to share ViewBag properties across templates.

Describe the solution you'd like

I like to define those properties once in a _ViewStart.cshtml file:

And use the GlobalVariable in my templates:

Additional context

Seems like ViewStart-related code is commented in TemplateRenderer.

jbaumbach

jbaumbach

Icon For Comments11

Describe the bug When attempting to compile a string template and a complex model, we get the error:

To Reproduce

  • .Net Framework 4.7.2
  • Project is an ASP.NET solution with .cshtml views, which work fine
  • Use a non-trivial string template with references to C# POCOs (a simple "Hello World" string works fine)

Expected behavior

  • The CompileRenderStringAsync() function returns the result

Information (please complete the following information):

  • OS: Windows 10 (dev environment)
  • Platform: .NET Framework 4.7.2
  • RazorLight version: 2.0.0-rc.3 (latest)
  • Are you using the OFFICIAL RazorLight package? https://www.nuget.org/packages/razorlight (I installed it with Package Manager as recommended on your main page)
  • Visual Studio version: VS Professional 2019 Version 16.8.2 (latest)

Additional context Clearly the library is referenced - there would be no way to call the .CompileRenderStringAsync() method otherwise. And it does build and compile fine.

I tried these things:

  1. Added the <PropertyGroup> settings you mentioned (all of them) in the ASP.NET .csproj file. It didn't change anything - and also those might apply only to .Net Core?

I don't think this is an issue with your library necessarily - it's just unclear how to figure this out.

knuxbbs

knuxbbs

Icon For Comments13

Is your feature request related to a problem? Please describe. As pointed in #396 , there is very little guidance to an user who wants to use your Razor views and pages as templates to another purposes.

Describe the solution you'd like First of all, seems like this library doesn't work with pre-compiled views (#35), which is the default output for ASP.NET Core applications. This should be highlighted in the repository's README, as well as the need to set your views as EmbeddedResources.

Second, the guidance about using RazorLightEngine as a injected service should be in main page, not in an outdated wiki page. This, in fact, should be the standard way to use the library, and should be further encouraged.

knuxbbs

knuxbbs

Icon For Comments5

Is your feature request related to a problem? Please describe. There isn't any sample using cshtml files, only strings. I think that the majority of users come to this repo to found a solution that uses the capabilities of Razor views and pages.

Describe the solution you'd like Create a project which uses a Razor Class Library to share templates with another project.

jzabroski

jzabroski

Icon For Comments0

@jzabroski - all Im find in this and that's not very helpful

To be more specific, I have the StaticFiles Service enabled I have a file in my wwwroot and want to reference an image in my layout.cshtml.

I see in TemplatePageBase the Href method is commented out... https://github.com/toddams/RazorLight/blob/badbd178564ba59934368161c7c140fa5906eee1/src/RazorLight/TemplatePageBase.cs#L304-L320

Any more detailed examples would be most helpful.

Originally posted by @Simonl9l in https://github.com/toddams/RazorLight/issues/70#issuecomment-718320075

jzabroski

jzabroski

Icon For Comments1

Is your feature request related to a problem? Please describe. We could use examples of how to use RazorLight against various TFMs, including net472. One question of how to do this is where does the output of the HTML get sent to. CefSharp provides a flexible medium for displaying HTML.

Describe the solution you'd like Implement Example Hello, World app using CefSharp.Wpf nuget package.

See: https://www.nuget.org/packages/CefSharp.Wpf/85.3.121-pre

Ideally, a full Example app would have things like radio buttons to toggle various modes of using RazorLight, such as "file system project", "embedded resources project", string templates bypassing project system, "use (template) caching", etc.

A screen capture of the app could then be uploaded to YouTube to demonstrate to users how to use RazorLight well.

Additional context CC @HamiltonManalo

georgeemr

georgeemr

awaiting-customer-response
Icon For Comments14

I'm unable to read the cshtml from a compiled dll that net core 3.1 creates when deploy the app.

To Reproduce

Expected behavior HTML of view

but get message: Project can not find template with key ....

What do I missing?

ldubrois

ldubrois

awaiting-customer-response
Icon For Comments6

Describe the bug We are using RazorLight in a project, with PropertyInjector as a PreRenderCallback. We are injecting a service in a Razor view (using the form @inject) ; this service requires a IServiceProvider. When using the IServiceProvider in the class, we a have a Object Disposed exception.

To Reproduce Use injection with a class requiring an IServiceProvider and try to invoke it.

Expected behavior The exception should not occurs.

Information (please complete the following information):

  • OS: Windows : 10
  • Platform : .net core 3.1
  • RazorLight version : 2.0.0-beta9
  • Are you using the OFFICIAL RazorLight package? yes
  • Visual Studio version : Visual Studio 2019 Pro

Additional context It seems from the documentation provided by Microsoft, that a IServiceProvider lifetime is "scope", and this is why we are getting an exception.

Replacing the PropertyInjector by a very simple code solve the problem (by removing the scopes)

Thanks,

sam31897

sam31897

Icon For Comments14

Hi RazorLight team,

I am currently planning to use this library to create html reports for my company. However, I need a stable v2.0.0 version. I can not use v1.1.0 because the project will be in netstandard2.0.

Thanks, sam31897

Tyrrrz

Tyrrrz

Icon For Comments30

Describe the bug

Because RazorLight has a FrameworkReference to Microsoft.AspNetCore.App, the user is expected to have the corresponding runtime. This is a show stopper for console or WPF apps as users of those will not have it installed (and shouldn't need to).

To Reproduce

  1. Create a WPF app
  2. Add RazorLight
  3. Publish it
  4. Try running on a machine where neither ASP.NET Core runtime nor SDK is installed

image

Expected behavior

It should work with just the base .NET Runtime.

Information (please complete the following information):

  • OS: Win10 x64
  • Platform .NET Core 3.1
  • RazorLight version 2.0-beta9
  • Are you using the OFFICIAL RazorLight package? yes
  • Rider 2020.1.3
Tyrrrz

Tyrrrz

Icon For Comments10

Describe the bug

When you use IncludeAsync along with embed resource provider, it will always append .cshtml to the end of the key. I'm trying to include a CSS file to embed it inside the page, but I can't, unless it ends in .cshtml.

To Reproduce Steps to reproduce the behavior:

Expected behavior

Should properly include Core.css instead of trying to resolve Core.css.html.

Information (please complete the following information):

  • OS: Win10 x64
  • Platform .NET Core 3.1
  • RazorLight version 2.0-beta9
  • Are you using the OFFICIAL RazorLight package? yes
  • Rider 2020.1.3

Additional context Add any other context about the problem here.

amro93

amro93

Icon For Comments5

Describe the bug simply using this template == null) ...."

expected: when the ViewBag properties does not exists the condition in the template should returns true

actual: when the ViewBag properties does not exists the condition in the template will throw an exception

To Reproduce Steps to reproduce the behavior:

Expected behavior A clear and concise description of what you expected to happen.

Information (please complete the following information):

  • OS: [ e.g Ubuntu 16.04, Windows Server 2016, etc ]
  • Platform [.NET Framework 4.x / .NET Core 2.x , etc]
  • RazorLight version [ e.g 2.0-beta1 ]
  • Are you using the OFFICIAL RazorLight package? https://www.nuget.org/packages/razorlight
  • Visual Studio version [ e.g Visual Studio Community 17.8.5 ]

Additional context Add any other context about the problem here.

mikoskinen

mikoskinen

qa-confirmation-needed
Icon For Comments12

Describe the bug RazorLight 2.0.0-beta8 (and some of the previous versions) has dependencies to .NET Core 3.0 packages which are broken. These packages contains DLLs which are missing modifies dates. This causes errors when trying to package a project which depends on RazorLight.

To Reproduce

  1. Create a new .NET Core 3.1 console app
  2. Add RazorLight 2..0.0-beta8
  3. Set PreserveCompilationContext to true.
  4. Publish the project

Now if you check the bin\Debug\netcoreapp3.1\refs folder, you should see the broken DLLs which are missing "Date modified":

image

Expected behavior

After following the above steps all the DLLs in refs-folder should have "Date modified" set.

Additional context

This isn't actually RazorLight's fault as there is a bug in dotnet pack which is the root issue: https://github.com/NuGet/Home/issues/7001. If any file in refs is missing the date AND your computer's time zone has positive offset, the pack command will fail.

One could maybe say that the root issue is actually the invalid Nuget packages, which are discussed here: https://github.com/dotnet/extensions/issues/2750

The problem should be fixed if the dependencies are updated to the latest ones (3.1.5).

itniels

itniels

Icon For Comments9

Describe the bug When calling the RazorLight render methods from a .NET 4.7.2 Web project, it fails to resolve assemblies.

  • Microsoft.AspNetCore.Html.Abstractions
  • System.Immutable
  • etc..

Every time one is fixed a new one arises.. Our system cannot use the packages specific to RazorLight as they are way outdated, so due to the references in RazorLight it cannot be used by Framework 4.7.2.

To Reproduce Create a NETSTANDARD2.0 project with razorlight and call it from a .net 7.7.2 asp.net web application.

I have a full repro on my github here: RazorLightTest

Expected behavior It renders a template.

Information (please complete the following information):

  • OS: Windows10
  • Platform .NET Framework 4.7.2
  • RazorLight version [ e.g 2.0-beta8 ]
  • Are you using the OFFICIAL RazorLight package? Yes
  • Visual Studio version: 16.6.2

Additional context Hi @jzabroski :) As requested a full repro of this issue as simplified as i can. https://github.com/itniels/RazorLightTest

Versions

Quick list of the latest released versions

v2.1.0 - Jul 15, 2022

Issues By Milestone

#481 System.UriFormatException: Invalid URI: The hostname could not be parsed (Fixed by @Xtansia #489 )

PRs By Milestone

  • Docs updated by @mwasson74 , @vdurante
  • Verify dependency updated by @SimonCropp
  • Tests added by @jzabroski

v2.0.0 - Mar 18, 2022

RTM.

v2.0.0-rc.6 - Feb 16, 2022

💖 Improvements

#467 : Support for .NET 6.0 (Fixes #460)

2.0.0-rc.2 - Nov 18, 2020

#391 - Change exception type/message when project item does not exist (@maxbanas) - to help people troubleshoot issues like #378 #392 - Change targeting for .Net standard 2.0 (@Vincentvwal) - Fixes #390

Generated from: https://github.com/toddams/RazorLight/milestone/11?closed=1

2.0.0-rc.1 - Nov 17, 2020

  • Removed Obsolete InplaceStringBuilder and replaced with stringbuilder. #380 (@ADNewsom09)
    • required for .NET 5.0 support to work
  • .NET 5.0 support #389 (@nm-a)

v2.0.0-beta9 - Jun 24, 2020

#349 - Fixes #349 dotnet pack bug causes .netcoreapp3.1 TFM projects issues @(@jzabroski)

v2.0.0-beta8 - Jun 21, 2020

#335 - Fixed spelling errors in the code (@SimonCropp) #309 - Added regression tests for common Razorlight renderer cases (@weyert) #346 - Introduce Verify for section approval tests (@SimonCropp) #308 - Fixed "The name 'section' does not exist in the current context in .net core 3" (@jzabroski)

v2.0.0-beta7 - Mar 27, 2020

  • Fixes #322 via commit 2d9c031 (@jzabroski )

v2.0.0-beta6 - Mar 26, 2020

  • Fixes #311 (via @HakanL PR #312): Incorrect template key when using constructor that takes assembly.
  • Release Management improvement: Cleaned up Sandbox, Sample and RazorLight.Precompile projects to have IsPackable=False

v2.0.0-beta5 - Mar 18, 2020

  • Fixes #287 via #310 (@matthewwren viz a viz @chancie86 )

v2.0.0-beta2 - Dec 19, 2019

What's new

  • #123 Template now shares model with layout.
  • #107 Embedded project can now accept Assembly + root namespace as a string, instead of Type of root object
  • #152 Allow FileSystemProject to set Extension ( @KorsG )
  • #180 Add ability to exclude assemblies from metadata references ( @mscrivo )
  • #278 Add netcore 3.0 support ( @gjunge )

Bug fixes:

  • #103 - Fixed race condition compilation bug
  • #134 - Fixed rendering issues with included templates
  • #135 - Fixed ViewBag doesn't work in nested templates (@deckertron9000)
  • #141, #147, #133 - Resolve MetadataReferences without using DependencyContext on Full .NET Framework (@colinbull )
  • #153 - Fixed MemoryCachingProvider file naming (@KorsG )
  • @Raw() will not throw NullReferenceException on null or empty value (@ReinisV1 )

Breaking changes

  • EngineFactory will trigger build error. Marked completely Obsolette. Use RazorLightEngineBuilder instead
  • When template you want to render does not exist, TemplateNotFoundException will be throws instead of InvalidOperationException

2.0-alpha3 - Sep 23, 2017

What is new?

String rendering is back!

We added rendering of the strings back! And now they are cached, so you will not be affected by bad performance.

Note: if you store your templates in database - it is recommended approach to define custom RazorLightProject that fetches templates from database and create RazorLightEngine passing your implementation to it. This way, engine will your RazorLightProject to resolve layouts. String rendering is just another option for some exclusive use cases when you have microservice structure and pass templates between nodes, so you might not need it at all.

Here is an example of RazorLightProject that uses EntityFramework to get templates from database- https://github.com/toddams/RazorLight/blob/dev-2.0/samples/RazorLight.Samples/Program.cs

`

Additional metadata references

When RazorLight compiles your template - it loads all the assemblies from your entry assembly and creates MetadataReference from it. This is a default strategy and it works in 99% of the time. But sometimes compilation crashes with an exception message like "Can not find assembly My.Super.Assembly2000". In order to solve this problem you can pass additional metadata references to RazorLight.

`

2.0.0-beta1 - Dec 22, 2017

What's new?

Breaking changes

  • Added new type: RazorLightEngineBuilder that comes to replace EngineFactory, as too many overloads are annoying
  • EngineFactory masked as Obsolete.
  • EngineFactory.RazorEngine is moved to DefaultRazorEngine.Instance
  • ICompilationService.CompileAndEmit renamed to CompileAsync and returns Task
  • DefaultCachingProvider renamed to MemoryCachingProvider

Note: there was a major refactoring, you may find some classes are moved to another namespaces

New features

  • Templates that are resolved from FileSystem are now invalidated from MemoryCache when you change it.

  • You can now create an engine without a project, if you want to only create templates from strings - #110

  • It is possible now to create engine without caching provider

  • Add ability to set operating assembly (uses EntryAssembly if not specified)

  • Disable encoding for the entire document with template property "DisableEncoding" - #106

Bug fixes

  • Fix ViewBag not passed to the engine #97
  • Close stream after read - #120
  • Fix concurrent template build fails - #103

2.0-alpha2 - Sep 18, 2017

What is new?

  • Added support for includes via @{ await IncludeAsync("key", model); }
  • Disable encoding

As always, you can avoid encoding using @Raw() function Or disable encoding for entire document

Breaking change

  • is now called

2.0-alpha1 - Sep 18, 2017

2.0 alpha version is out

This is not a full list of changes, only key notes about the changes and important info

  • There are a lot of breaking changes. Project literally has been made from scratch
  • IRazorLight interface is still there. There is no "Parse" method. Use "CompileRenderAsync" instead (method names might change in future releases)
  • EngineFactory no longer static
  • No IEngineConfiguration yet.
  • No MVC version with @Inject yet.
  • No ViewStarts yet
  • FileSystem templates are not tracked and therefore are not invalidated from cache yet when you change them
  • No string caching (Most people used it to for templates that are taken from database. Recommended approach is to create custom RazorLightProject class that will load your templates from database. That's all you need and this way, your templates will be cached). I will create a sample tomorrow with EntityFramework and NpgSql

So what is implemented?

  • Basic Razor support
  • Model
  • Layout,
  • Sections
  • Caching

1.1.0 - May 01, 2017

  • Fixed bug with Configuration.Namespace not applied to the template
  • Downgrade dependency on Codeanalysis.CSharp to 1.3.0 to avoid nuget version conflicts with ASP.NET MVC

1.0.1 - Apr 14, 2017

What's new

  • #49 TemplateCompilationException now includes line and column number where an error occured
  • #46 Added new overload for Parse() method. Now you can set a PreCenderCallback for each page individually. (Before you could only add callbacks to IEngineConfiguration that are applied for each page)

Bug fixes

  • Fix #47 (ExpandoObject as model type throws RuntimeBinderException)

1.0.0 - Apr 05, 2017

What's new:

  • Update nuget packages to 1.1
  • Minor bug fixes

1.0.0-rc2 - Feb 20, 2017

What's new:

  • Project migrated to MSBuild / *.csproj
  • For the convenience, compilation errors are now shown in Exception Message. No need to inspect CompilationErrors.
  • EngineFactory now returns IRazorLightEngine (was RazorLightEngine)
  • Minor bug fixes

1.0.0-rc1 - Oct 13, 2016

Out first Release Candidate!

This release comes out with some improvements and refactorings. We are planning to roll up a stable version soon

  • ParseString() is extracted to an extension method (under RazorLight.Extensions namespace)
  • PreRenderCallbacks moved to IEngineConfiguration
  • While searching for Layout file - instead of InvalidOperationException - RazorLightException is thrown
  • No more AggregateExceptions. I'm erasing annoying AggregateExceptions from code. Please, open an issue If you see it again somewhere

1.0.0-beta6 - Sep 27, 2016

This small release brings fixed for #15 and #18

1.0.0-beta5 - Aug 31, 2016

Full .NET Support arrived!

  • Now you can use RazorLight with a Full .NET Framework v4.5.1 and higher

ASP.NET MVC Core integration

New package brings ASP.NET MVC Core integration which allows you to inject services into your templates via built in Dependency Injection container

  • Add package

    Install-Package RazorLight.MVC

  • Add RazorLight services in Startup.cs

  • Retreive IRazorLightEngine instance from controller constructor

  • Inject services to your templates

Small fixes

@Include now works in Layout and ViewStart pages as well (#12)

1.0.0-beta4 - Aug 27, 2016

This release brings you Include feature

Example

First argument takes a key of the template to resolve, second argument is a model of the view (can be null)

1.0.0-beta3 - Aug 12, 2016

New features

  • Use Raw() method to output model value without encoding ( #7 )

Changes

  • Fix #5
  • Rename PageCacheItem and PageCacheResult to PageLookupItem and PageLookupResult
  • Removed IMemoryCache from DefaultPageLookup
  • Added new IPageFactory with caching - CachingPageFactory
  • PageLookupResult default constructor removed. Use PageLookupResult.Failed instead

1.0.0-beta2 - Aug 11, 2016

Changes

  • Pass ITemplateConfiguration to EngineFactory #3

  • Pass a ViewBag to Parse method. #4

Note: Viewbag is accessible both from the template page and it's layout.

Code

Template

1.0.0-beta1 - Aug 07, 2016

This release brings Layout, _Viewstart pages support, sections and custom template namespaces. API is completely reworked.

New features

  • Use ITemplateManager(string key) to resolve a templates. For files, Key - is a relative path to the view. For embeded resources - it's a name of the resourse.

  • Layout pages

  • Sections

Layout.cshtml:

View.cshtml:

  • ViewStart pages. (Same as with ASP.NET MVC.)
  • Custom namespaces. To add custom namespaces to your templates, use ITemplateConfiguration.Namespaces (ISet<string)

Breaking changes:

  • ConfigurationOptions removed. Use ITemplateConfiguration instead.
  • AdditionalMetadataReferences and LoadDependenciesFromEntryAssembly are removed. Use IMetadataResolver to provide an additional metadata references to RazorLight compilation service
  • Parameterless constructor of RazorLightEngine was removed. Use static EngineFactory class instead.

Before:

After:

  • ParseFile method is removed. Use Parse method instead with a FileSystemTemplateManager to resolve a template (ParseString method is still there)

Notes

  • To comply with Nuget versioning guidlines, version was changes from 0.0.1 to 1.0.0-beta1
  • Package is under active development and there might be breaking changes in a new releases. I expect to ship 3-4 betas and then go to stable, sorry for inconvenience, to create something good you must create at least something and then find the room for improvements

0.0.1 - Jul 24, 2016

First release with initial features:

  • Parse string
  • Parse files
  • Caching
  • Recompile cached view on file content change
  • Anonymous types models
  • Strongly typed views
  • Loading models from extenral assemblies

Library Stats (Aug 08, 2022)

Subscribers: 56
Stars: 1.3K
Forks: 235
Issues: 61

NET Core implementation of T-Digest

This is a nearly line-for-line port of the original Java reference implementation by Ted Dunning

NET Core implementation of T-Digest

NET Core API Endpoints

A project for supporting API Endpoints in ASP

NET Core API Endpoints

NET Core Microservices [Video]

This is the code repository for Packt

NET Core Microservices [Video]

NET Core Ethereum client

Kovan (only fast sync and may fail if pWASM transactions appear)

NET Core Ethereum client
IoT

1.7K

NET Core IoT Libraries

NET Core can be used to build applications for GPIO pins, serial ports or similar hardware

NET Core IoT Libraries

✨ imgup [dotnet-imgup]

NET Core global CLI tool to upload images on published to nuget

✨ imgup [dotnet-imgup]

NET Core Extensions and Helper NuGet packages

A simple and fast (fastest?) object to object mapper that does not use reflection

NET Core Extensions and Helper NuGet packages

✨ namechk [dotnet-namechk]

NET Core global CLI tool to check for the availability of NuGet package names

✨ namechk [dotnet-namechk]

community-id-dotnet-core

net core implementation of the Community ID flow hashing standard as described by

community-id-dotnet-core

NETCore Challenge

Simple CRUD with no authentication

NETCore Challenge

Net Core Api blog application, its is not finished

Seed of all models with Bogus(the Faker nuget package for dotnet)

Net Core Api blog application, its is not finished