Servicestack gap...read contents of an embedded resource

So I know I can use servicestack gap to embed resources into a dll…those resources must be loaded internally…so is there a method that is exposed or can be exposed as api so that I can read the contents of an embedded resource.

I’m trying to use servicestack razor as a fast email template engine, if I have the above I know I will be able to use a helper* to embed an inline css tag and I might not even need Premailer.NET to run on the after.

*much like this: http://stackoverflow.com/questions/14298604/how-to-include-css-styles-inline-in-razor-view only replacing the file lookup with embedded call.

This would be really good, otherwise I’d have to use slower razorengine library or always inline styles myself.

You can access embedded resources via the Virtual File System where you can read the contents of a file in a Service with:

var file = VirtualFileSources.GetFile("path/to/file.cshtml");
var razorHtml = file.ReadAllText();

Outside a Service you can use the HostContext.VirtualFileSources singleton.

If it helps here’s a generic Service that resolves and returns the contents of any File:

[Route("/files/{Path*}")]
public class GetFile
{
    public string Path { get; set; }
}

public class FileServices : Service
{
    public object Any(GetFile request)
    {
        var file = VirtualFileSources.GetFile(request.Path);
        if (file == null)
            throw HttpError.NotFound("File '{0}' does not exist".Fmt(request.Path));

        return new HttpResult(file) {
            ContentType = MimeTypes.GetMimeType(file.Extension)
        };
    }
}

Which you can call with:

/files/path/to/file.cshtml

Awesome, it looks like this will work well (and I won’t even need that service), for other’s ref:

  1. Need to change your css files build action to ‘Embedded Resource’

  2. Here is simple Embedcss function that can use.

    using System;
    using ServiceStack;
    using ServiceStack.Html;

    public static class HtmlHelpers
    {
    public static MvcHtmlString EmbedCss(this HtmlHelper htmlHelper, string relativePath)
    {
    try
    {
    var file = HostContext.VirtualFileSources.GetFile(relativePath);
    var cssText = file.ReadAllText();
    return htmlHelper.Raw($"\n{cssText}\n");
    }
    catch (Exception ex)
    {
    throw new Exception("EmbedCss - see Inner: ", ex);
    }
    }
    }

like: @Html.EmbedCss(“css/htmlreport.css”)

  1. If you want to support gmail client that still need https://www.nuget.org/packages/PreMailer.Net …but currently needs new release… https://github.com/milkshakesoftware/PreMailer.Net/issues/78
1 Like