Error using RazorEngine Templating TemplateCompilationException

in an asp.net mvc / sql project I’v added hangfire following the asp.net mvc tutorial (http://hangfire.readthedocs.org/en/latest/tutorials/send-email.html). I’m using RazorEngine v3.4.2 (there are two RazorEngine projects on NuGet).

My emails are enqueued alright but I get a “RazorEngine.Templating.TemplateCompilationException” (see below).

Code to enqueue mail:

Hangfire.BackgroundJob.Enqueue(() => SendSurveyResponse(userEmail, lFromEmail);
public static void SendSurveyResponse(string userEmail, string lFromEmail)
{
    var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
    var engines = new ViewEngineCollection();
    engines.Add(new Postal.FileSystemRazorViewEngine(viewsPath));
    var emailService = new Postal.EmailService(engines);

var email = new ViewModels.Email.ResponseAttachedEmail
{
	ToEmail = userEmail,
	FromEmail = lFromEmail,
	Subject = "Survey response",
};
    emailService.Send(email);

}
RazorEngine.Templating.TemplateCompilationException

Unable to compile template. Assuming assembly reference 'System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' matches 'System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', you may need to supply runtime policy Other compilation errors may have occurred. Check the Errors property for more information.

RazorEngine.Templating.TemplateCompilationException: Unable to compile template. Assuming assembly reference 'System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' matches 'System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', you may need to supply runtime policy

Other compilation errors may have occurred. Check the Errors property for more information.
   at RazorEngine.Compilation.DirectCompilerServiceBase.CompileType(TypeContext context) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Compilation\DirectCompilerServiceBase.cs:line 106
   at RazorEngine.Templating.TemplateService.CreateTemplateType(String razorTemplate, Type modelType) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 275
   at RazorEngine.Templating.TemplateService.GetTemplate[T](String razorTemplate, Object model, String cacheName) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 393
   at RazorEngine.Templating.TemplateService.GetTemplate(String razorTemplate, Object model, String cacheName) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 371
   at RazorEngine.Templating.TemplateService.Parse(String razorTemplate, Object model, DynamicViewBag viewBag, String cacheName) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 456
   at Postal.FileSystemRazorView.Render(ViewContext viewContext, TextWriter writer)
   at Postal.EmailViewRenderer.RenderView(IView view, ViewDataDictionary viewData, ControllerContext controllerContext, ImageEmbedder imageEmbedder)
   at Postal.EmailViewRenderer.Render(Email email, String viewName)
   at Postal.EmailService.Send(Email email)
   at MyTestProject.Web.Controllers.AccountController.SendSurveyResponse(String userEmail, String lFromEmail, String lToFirstName, Int32 lResponseId, DateTime lResponseBegin, String lRespondent, String lStore, String lPathToFile) in c:\Projects\MyTestProject\MyTestProject.Web\Controllers\AccountController.cs:line 617

If I omit the RazorEngine emails are enqueue and handled by the hangfire server and emails are sent off.

public static void SendSurveyResponse(string userEmail, string lFromEmail)
{
     var email = new ViewModels.Email.ResponseAttachedEmail
    {
        ToEmail = userEmail,
        FromEmail = lFromEmail,
        Subject = "Survey response",
    };
        email.Send();
}

/Morten

Have you checked that property? Are you embedding images or other attachments in your emails? Can you show me the template?

The email has no embedded images. Has one pdf attachment, however, I get the same result with or without attachment.


@model ViewModels.Email.ResponseAttachedEmail
Content-Type: text/html; charset=utf-8
To: @(Request.Url.ToString().Contains("localhost") == true ? Config.AppSettings.SystemAdministratorEmail : Model.ToEmail)
From: @Model.FromEmail
Subject: @Model.Subject

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
@Html.Partial("_HeadElementContent")
<body style="margin:0; padding:10px 0;" bgcolor="#fcfcfc" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">

    <br>

    <!-- 100% wrapper (grey background) -->
    <table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0" bgcolor="#fcfcfc">
        <tr>
            <td align="center" valign="top" bgcolor="#fcfcfc" style="background-color: #fcfcfc;">

                <!-- 600px container (white background) -->
                <table border="0" width="600" cellpadding="0" cellspacing="0" class="container" bgcolor="#ffffff">
                    <tr>
                        <td class="container-padding" bgcolor="#ffffff" style="background-color: #ffffff; padding-left: 30px; padding-right: 30px; font-size: 14px; line-height: 20px; font-family: Helvetica, sans-serif; color: #333;">
                            <br>

                            <!-- ### BEGIN CONTENT ### -->
                            <div style="font-weight: bold; font-size: 18px; line-height: 24px; color: #5cb85c;">
                                Survey response
                            </div><br>
                            
                            Hello @Model.ToFirstName,<br>
                            please find attached a copy of response #@Model.ResponseId from @Model.ResponseBegin.ToString("dd-MMM-yyyy HH:mm") registered by @Model.Respondent at @Model.Store.
                            <br><br>
                            
    
                            <!-- ### END CONTENT ### -->
                            @Html.Partial("_EmailSignature1")
                            <br><br>

                        </td>
                    </tr>
                </table>
                <!--/600px container -->

            </td>
        </tr>
    </table>
    <!--/100% wrapper-->
    <br>
    <br>
</body>
</html>

Please note, that if I just email.send() the mail is enqueue, handled by hangfire server sent and received (all viewable in hangfire server).

Copy of exception form vs2013 debugger:

RazorEngine.Templating.TemplateCompilationException was unhandled by user code
  HResult=-2146233088
  Message=Unable to compile template. Assuming assembly reference 'System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' matches 'System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', you may need to supply runtime policy

Other compilation errors may have occurred. Check the Errors property for more information.
  Source=RazorEngine
  Template=@model ViewModels.Email.ResponseAttachedEmail
Content-Type: text/html; charset=utf-8
To: @(Request.Url.ToString().Contains("localhost") == true ? Config.AppSettings.SystemAdministratorEmail : Model.ToEmail)
From: @Model.FromEmail
Subject: @Model.Subject

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
          "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
@Html.Partial("_HeadElementContent")
<body style="margin:0; padding:10px 0;" bgcolor="#fcfcfc" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">

    <br>

    <!-- 100% wrapper (grey background) -->
    <table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0" bgcolor="#fcfcfc">
        <tr>
            <td align="center" valign="top" bgcolor="#fcfcfc" style="background-color: #fcfcfc;">

                <!-- 600px container (white background) -->
                <table border="0" width="600" cellpadding="0" cellspacing="0" class="container" bgcolor="#ffffff">
                    <tr>
                        <td class="container-padding" bgcolor="#ffffff" style="background-color: #ffffff; padding-left: 30px; padding-right: 30px; font-size: 14px; line-height: 20px; font-family: Helvetica, sans-serif; color: #333;">
                            <br>

                            <!-- ### BEGIN CONTENT ### -->
                            <div style="font-weight: bold; font-size: 18px; line-height: 24px; color: #5cb85c;">
                                Survey response
                            </div><br>
                            
                            Hello @Model.ToFirstName,<br>
                            please find attached a copy of response #@Model.ResponseId from @Model.ResponseBegin.ToString("dd-MMM-yyyy HH:mm") registered by @Model.Respondent at @Model.Store.
                            <br><br>
                            
    
                            <!-- ### END CONTENT ### -->
                            @Html.Partial("_EmailSignature1")
                            <br><br>

                        </td>
                    </tr>
                </table>
                <!--/600px container -->

            </td>
        </tr>
    </table>
    <!--/100% wrapper-->
    <br>
    <br>
</body>
</html>

  StackTrace:
       at RazorEngine.Compilation.DirectCompilerServiceBase.CompileType(TypeContext context) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Compilation\DirectCompilerServiceBase.cs:line 106
       at RazorEngine.Templating.TemplateService.CreateTemplateType(String razorTemplate, Type modelType) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 275
       at RazorEngine.Templating.TemplateService.GetTemplate[T](String razorTemplate, Object model, String cacheName) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 393
       at RazorEngine.Templating.TemplateService.GetTemplate(String razorTemplate, Object model, String cacheName) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 371
       at RazorEngine.Templating.TemplateService.Parse(String razorTemplate, Object model, DynamicViewBag viewBag, String cacheName) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Templating\TemplateService.cs:line 456
       at RazorEngine.Razor.Parse(String razorTemplate, Object model, String cacheName) in c:\_git\RazorEngine\src\Core\RazorEngine.Core\Razor.cs:line 302
       at Postal.FileSystemRazorView.Render(ViewContext viewContext, TextWriter writer)
       at Postal.EmailViewRenderer.RenderView(IView view, ViewDataDictionary viewData, ControllerContext controllerContext, ImageEmbedder imageEmbedder)
       at Postal.EmailViewRenderer.Render(Email email, String viewName)
       at Postal.EmailService.CreateMailMessage(Email email)
       at Postal.EmailService.Send(Email email)
       at MyProject.Web.Controllers.AccountController.SendSurveyResponse(String toEmail, String fromEmail, String toFirstName, Int32 responseId, DateTime responseBegin, String respondent, String store, String attachment) in c:\...\MyProject.Web\Controllers\AccountController.cs:line 617
  InnerException:

xx

Postal have different issues when is executed outside of HTTP request (no HttpContext.Current available) as in Hangfire. Here is the one:

Please submit a bug report or send a pull request to the Postal library itself, as that project is outside of my control.

Thanks,
It works when I remove both calls to @Html.Partial and the @(Request.Url.ToString().Contains… call.

…but why does it work (on my local iis express) when I simply do email.send and not use the setup emailservice?

Those helpers use HttpContext.Current property that is completely unavailable in background jobs, which are running outside of a request, in background.