DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Data
  4. Razor Engine for Parsing Razor Pages Stored as String

Razor Engine for Parsing Razor Pages Stored as String

How the MVC Razor engine can be used to parse the razor view when the view is stored as text in a database or somewhere else outside an application.

Anjani Singh user avatar by
Anjani Singh
·
Dec. 19, 16 · Tutorial
Like (1)
Save
Tweet
Share
18.41K Views

Join the DZone community and get the full member experience.

Join For Free

In the previous blog, I covered how MVC Razor engine can be used separately to parse the razor view stored outside the application. This blog covers the case when View is not stored as cshtml page but is stored simply as text in Database or somewhere else. Only additional step, we have to add is to create a virtual view through VirtualPathProvider.

To demonstrate the real usage of this scenario, I have created a sample application which sends the email where the email template is stored as Razor View in Resource File. Similarly, the template can also be stored in Database. Razor View stored as string in Resource file is shown below.

<div> Dear @Model.Name,</div>

<p></p>

  Total Marks attended by you in Exam is <span style="color:green"> @Model.Marks</span> out of 100

<p>

</p>

Your Rank is <span style="color:green"> @Model.Rank</span>

@if (@Model.Rank == 1)
{
    <h2>Congrats, Please collect your Gold Medal from the Director's office</h2>
}
else if (@Model.Rank > 30)
{
    <h2 style="color:red">Please collect your transfer certificate from Director's Office after clearing all your Dues</h2>

}

This page uses Model of type Student which is defined as:

public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Marks { get; set; }

        public int Rank { get; set; }

        public string EmailId { get; set; }
    }

Stored View will use this Student model to render the HTML response.

I created a page for sending mail and previewing email which will use the above Razor template.

EmailPage

This page has two buttons for sending and previewing the email. Below actions will be called when clicking the “Preview Emails” and “Send Emails” buttons.

[HttpGet]
        public ActionResult PreviewEmail(int studentId)
        {
            string emailHTML = CreateEmail(studentId);
            return Json(new { HTML = emailHTML }, JsonRequestBehavior.AllowGet);  

        }

        public ActionResult SendMail(int studentId)
        {

            EmailService services = new EmailService();
            Email emailEntity = new Email();
            emailEntity.Subject = "Your Result Announced!";
            emailEntity.Content = CreateEmail(studentId);
            if (services.SendEmail(emailEntity))
            {
                return Json("Success");
            }
            return Json("Failure");

        }


For demonstration purposes, I will only use the preview feature of application.

On clicking this button, the PreviewEmail action will be called. You'll notice the CreateEmail Method is being called within the action. This Method is doing the main task of invoking the method for rendering the HTML from a stored Razor view.

private string CreateEmail(int studentId)
        {
            Student student = GetStudentById(studentId);

            //Create temporary view file
            string guid = Guid.NewGuid().ToString();
            string tempFilePath = "/Views" + "/Temp/" + guid + ".cshtml"; 
            // Delete temporary file after usage
            RazorViewGenerator helper = new RazorViewGenerator();
            string emailTemplate = EmailResources.EmailTemplate; // Read from Resource File or DB
            string emailHTML = helper.Parse(student, ControllerContext, tempFilePath, emailTemplate);
            return emailHTML;
        }



        private Student GetStudentById(int id)
        {
            Student student = new Student(); // All hard coded to demonstrate, in actual it may fetch from DB
            student.Id = id;
            student.Name = "Alice";
            student.Rank = 1;
            student.Marks = 78;
            student.EmailId = "alice@bob.com";
            return student;

        }


Currently, Student information is hardcoded to create the model but it will normally be fetched from the database. This Student model is being passed along with the temporary file path to the Parse method of RazorViewGenerator class.

The exact implementation of Parse with the RazorViewGenerator class is shown below. This method generates the actual HTML string from Razor:

public static Dictionary<string, string> pathMapDictionary = new Dictionary<string, string>();

        public string Parse(object ViewModel, ControllerContext controller,string tempFilePath,string template)
        {

            try
            {
                var sb = new StringWriter();
                ViewDataDictionary viewData = new ViewDataDictionary();
                pathMapDictionary.Add(tempFilePath, template); // Add template to dictionary which virtual path provider will access
                var tempData = new TempDataDictionary();
                viewData.Model = ViewModel;
                var razor = new RazorView(controller, tempFilePath, null, false, null);
                var viewContext = new ViewContext(controller, razor, viewData, tempData, sb);
                razor.Render(viewContext, sb);
                return sb.ToString();

            }
            catch (Exception exx)
            {

                throw;
            }

        }


The static variable pathMapDictionary,having path variable as key stores the string from resource file. Our VirtualPathProvider gets the path and access this dictionary to get corresponding template string. In the parse method, you can see that the path of the cshtml file is just a non-existing file path. In the previous Blog, there was real cshtml file at this location.

Now the main trick is done by the VirtualRazorPathProvider class implementing methods of VirtualPathProvider. It contains logic that whenever the file is tried being read at the “/Views/Temp” directory, it returns the required string just like the original file would have returned. This is being done by GetFile and Open method respectively, as shown in the code below.

public class VirtualRazorPathProvider : VirtualPathProvider
    {

        public VirtualRazorPathProvider()
            : base()
        {
        }

        public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            return null;
        }

        public override bool FileExists(string virtualPath)
        {
            if (virtualPath.StartsWith("/Views/Temp") || virtualPath.StartsWith("~/Views/Temp"))
                return true;

            return base.FileExists(virtualPath);
        }

        public override VirtualFile GetFile(string virtualPath)
        {
            if (virtualPath.StartsWith("/Views/Temp") || virtualPath.StartsWith("~/Views/Temp"))
                return new StringFile(virtualPath);

            return base.GetFile(virtualPath);
        }

        public class StringFile : System.Web.Hosting.VirtualFile
        {
            string path; // Path is the Key of Dictionary and is Associated value is Razor Template
            public StringFile(string path)
                : base(path)
            {
                this.path = path;
            }

            public override System.IO.Stream Open()
            {

                var stream = new System.IO.MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(RazorViewGenerator.pathMapDictionary[path]));
                // RazorViewGenerator.pathMapDictionary[path] returns email Template
                return stream;

            }
        }

    }


The VirtualRazorPathProvider class needs to be registered at Application_Start event of Global.asax file.

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            System.Web.Hosting.HostingEnvironment.RegisterVirtualPathProvider(new VirtualRazorPathProvider());
        }


The generated HTML is shown on the screen as shown below.You can create your own template and design as per your need.

EmailrenderedConcluding Points

We can have multiple different razor templates stored as a entry in Database or resource file. Consider a scenario where the different department has different design for the email template. Corresponding views can be used for sending email for each department. Also, The Email template can be managed directly by department, avoiding the need to give access to the complete application. Thus, it makes views loosely coupled from application. A little extra separation of View than MVC was intended for!

Strings Data Types Engine

Published at DZone with permission of Anjani Singh. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Handle Secrets in Docker
  • How We Solved an OOM Issue in TiDB with GOMEMLIMIT
  • Top 5 Data Streaming Trends for 2023
  • Introduction To OpenSSH

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: