Skip to content

Instantly share code, notes, and snippets.

@todthomson
Created December 16, 2014 04:09
Show Gist options
  • Save todthomson/6bdc9d737e7a746f8e73 to your computer and use it in GitHub Desktop.
Save todthomson/6bdc9d737e7a746f8e73 to your computer and use it in GitHub Desktop.
using System.Web.Optimization;
using LOR.PDCA.Web.Infrastructure;
namespace Foo.Bar.Baz
{
public class AppendApplicationVersion : IBundleTransform
{
private readonly IAppSettings _appSettings;
public AppendApplicationVersion(IAppSettings appSettings)
{
_appSettings = appSettings;
}
public void Process(BundleContext context, BundleResponse response)
{
foreach (var file in response.Files)
{
file.IncludedVirtualPath = string.Concat(file.IncludedVirtualPath, "?vbuster=", _appSettings.ApplicationVersion);
}
}
}
}
using System.IO;
using System.Security.Cryptography;
using System.Web;
using System.Web.Hosting;
using System.Web.Optimization;
namespace Foo.Bar.Baz
{
public class AppendFileHash : IBundleTransform
{
public void Process(BundleContext context, BundleResponse response)
{
foreach (var file in response.Files)
{
using (var fs = File.OpenRead(HostingEnvironment.MapPath(file.IncludedVirtualPath)))
{
var hash = new SHA256Managed().ComputeHash(fs);
var version = HttpServerUtility.UrlTokenEncode(hash);
file.IncludedVirtualPath = string.Concat(file.IncludedVirtualPath, "?hbuster=", version);
}
}
}
}
}
using System.Diagnostics;
namespace Foo.Bar.Baz
{
// See: http://stackoverflow.com/questions/2104099/c-sharp-if-then-directives-for-debug-vs-release/15288676#15288676.
public interface IDebugging
{
bool RunningInDebugMode();
bool RunningInReleaseMode();
}
public class Debugging : IDebugging
{
private bool _debugging;
public bool RunningInDebugMode()
{
// #if DEBUG
// return true;
// #else
// return false;
// #endif
AreWeInDebugMode();
return _debugging;
}
public bool RunningInReleaseMode()
{
AreWeInDebugMode();
return !_debugging;
}
[Conditional("DEBUG")]
private void AreWeInDebugMode()
{
_debugging = true;
}
}
}
var js = new ScriptBundle("~/bundles/js").Include("~/Scripts/foo.js", "~/Scripts/bar.js");
// Set EnableOptimizations to false for debugging. For more information visit http://go.microsoft.com/fwlink/?LinkId=301862.
var debugging = new Debugging();
BundleTable.EnableOptimizations = debugging.RunningInReleaseMode();
// An "append file hash" bundle transform that adds the cache breaker in debug mode...
var appendFileHash = new AppendFileHash();
// Only append the file hash if in debug mode (as release mode has a built in version buster).
if (debugging.RunningInDebugMode())
{
bundle.Transforms.Add(appendFileHash);
}
bundles.Add(bundle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment