Skip to content

Instantly share code, notes, and snippets.

@spooky
Created December 10, 2012 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spooky/4250979 to your computer and use it in GitHub Desktop.
Save spooky/4250979 to your computer and use it in GitHub Desktop.
allows using embeded resources for bundling
public abstract class EmbededResourceBundle : Bundle
{
private Assembly assembly;
private readonly HashSet<string> resourceNames = new HashSet<string>();
private readonly string contentType;
public EmbededResourceBundle(Assembly assembly, string virtualPath, string contentType, params IBundleTransform[] transforms) : base(virtualPath, null, transforms)
{
this.assembly = assembly;
this.contentType = contentType;
}
public new Bundle Include(params string[] resources)
{
foreach (var resource in resources)
resourceNames.Add(resource);
return this;
}
public IEnumerable<string> GetItems()
{
return resourceNames;
}
public override IEnumerable<FileInfo> EnumerateFiles(BundleContext context)
{
return resourceNames.Select(resourceName => new FileInfo(resourceName));
}
public override BundleResponse GenerateBundleResponse(BundleContext context)
{
context.UseServerCache = false;
var builder = new StringBuilder();
var resources = assembly.GetManifestResourceNames();
var files = new List<FileInfo>();
foreach (var resourceName in resourceNames)
{
var name = resourceName.Replace("~/", string.Empty).Replace('/', '.');
try
{
var stream = assembly.GetManifestResourceStream(resources.Single(r => r.EndsWith(name)));
var content = new StreamReader(stream).ReadToEnd();
builder.Append(content);
files.Add(new FileInfo(resourceName));
}
catch (InvalidOperationException)
{
throw new Exception("Unable to find " + name + " in resources");
}
}
var response = ApplyTransforms(context, builder.ToString(), files);
response.ContentType = contentType;
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment