Skip to content

Instantly share code, notes, and snippets.

@neo125874
Forked from spooky/rebundler
Last active August 29, 2015 14:17
Show Gist options
  • Save neo125874/5e254b3bade52110bd63 to your computer and use it in GitHub Desktop.
Save neo125874/5e254b3bade52110bd63 to your computer and use it in GitHub Desktop.
bundle files from Dll's content & scripts(For MvcContrib portable area)
public class Rebundler
{
private readonly Assembly assembly;
private readonly string virtualPath;
private readonly HashSet<string> resourceNames = new HashSet<string>();
//constructor
public Rebundler(Assembly assembly, string virtualPath)
{
this.assembly = assembly;
this.virtualPath = virtualPath;
}
//auto include
public Rebundler Include(string fileExtension, bool autoGenerate)
{
if (autoGenerate)
{
var bundleFile = assembly.GetManifestResourceNames()
.Where(x => x.EndsWith(fileExtension));
foreach (var include in bundleFile)
{
resourceNames.Add(include);
}
}
return this;
}
public Rebundler Include(params string[] includes)
{
foreach (var include in includes)
{
resourceNames.Add(include);
}
return this;
}
public Bundle Rebundle()
{
var names = assembly.GetManifestResourceNames().Where(n => resourceNames.Any(n.EndsWith));
var path = HttpContext.Current.Server.MapPath("~/Static");
//automatically check and create folder
Directory.CreateDirectory(path);
var bundle = new Bundle(virtualPath);
foreach (var resource in names)
{
using (var stream = assembly.GetManifestResourceStream(resource))
{
if (stream == null)
continue;
var resourcePath = Path.Combine(path, resource);
using (var file = new FileStream(resourcePath, FileMode.Create))
{
stream.CopyTo(file);
file.Close();
}
if (resource.EndsWith(".css"))
{
//css url rewrite
bundle.Include("~/Static/" + resource, new CssRewriteUrlTransformWrapper());
}
else
{
bundle.Include("~/Static/" + resource);
}
}
}
return bundle;
}
}
public class CssRewriteUrlTransformWrapper : IItemTransform
{
//virtual directory path
public string Process(string includedVirtualPath, string input)
{
return new CssRewriteUrlTransform().Process("~" + VirtualPathUtility.ToAbsolute(includedVirtualPath), input);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment