Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put HTML code into a .resx resource file?

Strange, that no one asked this before....

I am creating templated HTML emails for 4 languages. I want to put the HTML templates into my .resx files to have easy, internationalized access to them from code. Like so:

.resx file:

<data name="BodyTemplate" xml:space="preserve">
    <value><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <html>
        <head>
            <meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
            <title>Title</title>
            ...
        </body>
        </html>
    </value>
</data>

But, obviously, the compiler complains about the HTML inside the .resx file. Is there a way to use HTML (or XML at all) in .resx files. How?

I am using .NET version 4 and dotLiquid as templating Engine, if that matters.

like image 518
Marcel Avatar asked Feb 17 '15 09:02

Marcel


2 Answers

Suggestion: Create the file you want, name it the way you want, e.g "my_template.html" then add this file to your project.

Click on it, then select in the properties window "Build Action" and set it to "Embedded Resource".

Whenever you want to access this file, you can use something like this (no with proper using block:

    public static string ReadTextResourceFromAssembly(string name)
    {
        using ( var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( name ) )
        {
            return new StreamReader( stream ).ReadToEnd();
        }
    }

Tailor it to your needs. The method above obtains the resource, say you have put your resource in your project MyProject in a subdirectory "HtmlTemplates and called it "my_template.html", then you can access it by the name MyProject.HtmlTemplates.my_template.html

You can then write it out to file or use it directly, etc.

This has some major benefits: You see your html file in your project, it has the html extension, so editing it in Visual Studio has syntax highlighting and all tools applied to .html files.

I have a bunch of those methods for my unit tests, this one extracts the data to a file:

    public static void WriteResourceToFile(string name, string destination)
    {
        using ( var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream( name ) )
        {
            if ( stream == null )
            {
                throw new ArgumentException( string.Format( "Resource '{0}' not found", name), "name" );
            }

            using ( var fs = new FileStream( destination, FileMode.Create ) )
            {
                stream.CopyTo( fs );
            }
        }
    }
like image 77
Samuel Avatar answered Oct 20 '22 01:10

Samuel


Put encoded html in the .resx file and then getting back the html using

@Html.Raw(Server.HtmlDecode(...resource...));
like image 34
Programmer Avatar answered Oct 20 '22 01:10

Programmer