ASP.NET MVC - Make Cached Styles Expired upon Release using Bundling - asp.net

This is how I include JavaScript files in my ASP.NET MVC application,
Bundles.Add(new ScriptBundle(ConfigBundles.Scripts).Include
(
"~/Content/Scripts/Libraries/framework-{version}.js",
"~/Content/Scripts/Libraries/controls-{version}.js"
));
My understanding is that whenever I do a new release where the referenced JavaScript files have changed, i just need to increment the version number so that user's web browsers know that they need to clear the existing cache and request the new file.
However, this same process does not seem to work for stylesheets - this is how I load them:
Bundles.Add(new StyleBundle(ConfigBundles.Styles)
.Include("~/Content/Styles/Site-{version}.css", new CssRewriteUrlTransform()));
However, this does not seem to work - when I change the name of the Site.css to include a version, the bundling doesn't seem to detect it. Furthermore, in most guides on bundling they just talk about using this feature with Scripts - I haven't seen anyone confirm that it can used with styles as well...
Am I going about this the right way?

Related

Bad resources path in ASP.NET MVC5 page

This is curious.
When I have this, for example, in my BundleConfig class:
bundles.Add(new StyleBundle("~/iCheck/css").Include(
"~/Content/iCheck/flat/green.css"));
bundles.Add(new ScriptBundle("~/iCheck/js").Include(
"~/Scripts/icheck.js"));
In a server, resources are retrieved from the correct location:
/Content/iCheck/flat/green.css
however, in other server, resources are retrieved using this URL:
/iCheck/css?v=ENsQ8JbHO7Zzp1Za0G2FBDKGGsGf_VDHd_S5fgCyCxA1
That causes images inside the CSS not to be found. How can I solve it? in both servers there is the same deployed version of the site. I don't understand why in one server the bundles behave different from others.
Bundling is enabled for Release builds but not for Debug.
The property BundleTable.EnableOptimizations will allow you to override the bundling setting in development.
To fix the relative paths within the CSS look at the CssRewriteUrlTransform.
.Include("~/Content/iCheck/flat/green.css", new CssRewriteUrlTransform())

mvc bundle and css management strategy

I developed a website, which can be used by different customers. As a result, we want to give different CSS styles and images to individual customers.
What we want is to manage CSS and images separately, so we won't need to deploy the site again just because we added some new CSS or images. As the site is under MVC, when accessing URLs such as:
www.mysite.com/customerA/myPage
www.mysite.com/customerB/myPage
we can find the customer id and find the right CSS and image to return.
The problem is that we want to bundle CSS, when the CSS or images are bundled, two issues will occur:
How the bundle detect underlying CSS file change? Is it possible?
Some users may already visited the URL and cached the bundled CSS, how can we disable the cached CSS, so it will get the new version?
The .NET bundling strategy is very intelligent in solving both of your issues. Once you create a bundle - example below:
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
And render this bundle out on your website, the output looks something like this:
<link href="/Content/css?v=xUfHQEnjwMk9UEexrvHPdvPxJduGrgz0bbI5qy5BGHY1" rel="stylesheet"/>
Notice the ?v=bigTextstring. Anytime a file in your bundle changes, the bundling framework will change the bigTextString after the ?v=. So, for your first question, yes, it will automatically detect file changes. You can get more information about how all of that process works if you visit this SO question. For your second question, the ?v= parameter, when changed, signals the client's browser that this is a different file than you had, you need to download it again.
Tommy has a great answer. I just wanted to elaborate on a few points.
First, as long as the bundle itself hasn't changed (added/removed scripts/styles or changed the location of those files), then you can freely update the files themselves without republishing the whole site. The bundler runs at runtime and looks at the last modified timestamp of the included files. If any of the files has changed, a new bundle will be generated with an updated cache-busting querystring param.
However, since the actual bundle configuration is code-based, if you add/remove items from the bundle or change the location of the file(s), such that you have to update the bundle configuration in BundleConfig.cs then you must republish, or at least also update the project DLL. This is because the code compiled within that DLL has changed.

Referencing files minified by Web Essentials in Visual Studio 2013

I have minified CSS and JS files that are auto-generated by Web Essentials, and auto-updated every time I update and save the original files.
What would be the best way to automatically toggle the actual (script/import) references within HTML between original (in Dev/Test) and minified (in Production) files?
This is within an MVC ASP.NET web app.
One idea would be to have server-side tags that render either ".min" or empty string based on an environment variable. But I'm wondering if there's a better, smarter, easier, more efficient way of handling this.
Thanks in advance.
Update:
My style bundle is defined like this:
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site{version}.css"));
And I reference it like this:
#Styles.Render("~/Content/css")
However, this renders the following:
<link href="/Content/css?v=" rel="stylesheet"/>
It works fine if I take "{version}" out of bundle definition, but renders an empty "v=" if I include "{version}".
Update 2:
I just realized that due to certain complexities of the application, I can't use the bundling solution. What other options do I have?
Bundling will help you in this instance. You should already be able to see an example in your BundleConfig.cs file in App_Start.
Here is a tutorial on how to conifgure it http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
From that tutorial, this is how you actually configure the bundles themselves, the files that will be in them, etc. This includes any jquery in the scripts folder into a bundle called ~/bundles/jquery.
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Code removed for clarity.
BundleTable.EnableOptimizations = true; // <-- this line overrides the debug check to show you the minified version even in debug mode... remove it for normal .min in debug/un-minned when not in debug behaviour
}
You then reference these from your views using
#Scripts.Render("~/bundles/jquery")
This will then render a script tag with the .min version of the jquery if you're not in debug or leave it out if you are. There needs to be a .min version and an un-minified version in the same scripts folder (which you should have if Web Essentials is creating the .min for you.
You could actually stop using Web Essentials to do the minification if you use ScriptBundles as they will minify the javascript for you when it packages it into the bundle.
For your update
The "~/Scripts/jquery-{version}.js" means match any file in the scripts folder that starts with jquery- and ends with .js and has some version number between. If the files don't have a version number in them, then don't try and use the {version} substitution.
They do it with jquery in this case so that if you upgrade the version of jquery that you are using, you don't have to go back into your BundleConfig and manually change the file name for your jquery reference.
If your file was named site1.3.7.css, then this would probably work.
bundles.Add(new StyleBundle("~/Content/css")
.Include("~/Content/site{version}.css"));
but it sounds more likely that you just need site.css.
bundles.Add(new StyleBundle("~/Content/css")
.Include("~/Content/site.css"));
I'm not sure what you think prevents you from using them but you can link to files in CDNs and minify or not minify. Even just have individual files in a bundle to get the benefit of minification outside of debug without "bundling" them. So there's probably a way.

ASP.Net MVC Script Bundle results in 404

I've searched SO - found many of the same question, though none of the answers helped.
I've built a bunch of sites and not ran into this issue before.
Essentially, my script bundle results in a 404 for each of the files in my javascript folder.
My structure (at the moment, i've changed it a bunch!) looks like this:
I do this so i can guarantee that ASP.Net doesn't change the order - i can ensure certain scripts are ahead of others. It's how i've always done it and it normally works well.
My bundle script - at the moment - is:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.FileSetOrderList.Clear();
// stlyes
StyleBundle cssBundle = new StyleBundle("~/bundles/css");
cssBundle.IncludeDirectory("~/content/css", "*.css", true);
bundles.Add(cssBundle);
//scripts
ScriptBundle jsBundle = new ScriptBundle("~/bundles/jscript");
jsBundle.IncludeDirectory("~/content/javascript", "*.js", true);
bundles.Add(jsBundle);
}
I have tried a whole bunch of virtual paths.
My CSS loads perfect. My Js - i get a list of 404's; one for each of the */js files.
Any ideas?
My console looks like this - which also shows me that bundles.FileSetOrderList.Clear(); isn't actually clearing its list else i would have jquery before angular (as is my intent)
UPDATE
If i BundleTable.EnableOptimizations = true; in my bundles then it's all bundled, minified and works - though this sucks for development debugging - what on earth is preventing it working in debug mode?!
This post seems to describe the same problem ASP.Net MVC 5 sub-directory bundling issues and is a known issue with version 1.1.1 of the Bundling framework.
If you don't want to have to downgrade or upgrade to a version where this is working, you always have the option of explicitly adding files to the bundle that you want to come first. Let's say you have your files in the same folder.
/javascript/lib/ascript.js
/javascript/lib/ascript2.js
/javascript/lib/jquery.js
/javascript/lib/yscript.js
You can be explicit about the files you want first via Include(), and then still lump the rest together via IncludeDirectory().
bundles.Add(new ScriptBundle("~/bundles/jscript").Include(
"~/javascript/lib/jquery.js",
.IncludeDirectory("~/javascript/lib", "*.js")
The bundling is smart enough to not double include jQuery.js if it has been explicitly added first. Similarly, you can have multiple .IncludeDirectory calls on your various subdirectories if you want to still keep them sub-foldered.
If you set the enable optimization flag to true, it will overwrite the debug=false and bundle it. just use the below code snippet in your bundle.config file to remove bundling in debug mode.
#if !DEBUG
BundleTable.EnableOptimizations = true;
#endif
I think that it is the nested folders. I'm pretty sure the bundles only look in that direct folder. Have you used that folder structure with bundling before and it worked successfully?
As mentioned I kept getting jquery 404 not found.
This isn't a great answer but this is what I settled with until I find a better answer.
My issue was with the following, this worked very happily locally in development.
bundles.Add(new ScriptBundle("~/jquery").Include(new[]
{
"~/scripts/jquery-1.12.0.min.js",
}));
I tried variations and looked at the other options, in the end I changed it to the following for production. Googles CDN has always been reliable, there is other CDN options if you google around.
bundles.Add(new ScriptBundle("~/jquery", "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"));

Durandal Caching Issue / Versioning Strategy

What's a good strategy for versioning Durandal js and html files?
I noticed that, during development, your browser cache must be disabled in order for you to receive up to date files on each refresh. This is a must for during development.
However, my concern is that when I go to production with my continuous deployment strategy (deploying multiple times per day), that users' browsers will be caching older versions of my app which might lead to unpredictable behaviour.
The approach that springs to mind would be to version the js and html urls somehow so that there is a version number embedded into every request. But I am unsure as to how to make that work internally within the Durandal framework.
Ok, here is the direction that I am heading in. Basically there is something built into requirejs to handle this.
At the top of my main.js, in the call to requirejs.config I can set a urlArgs property that will be appended to every call requirejs makes for a module.
requirejs.config({
paths: {
'text': 'durandal/amd/text'
},
urlArgs: 'v=1.0.0.0'
});
When I want to force production users to get a new version of the requirejs modules I can just increment the version number which will invalidate the browsers cache.
(In my project I have a way of injecting the version number of the assembly containing my main ASP.NET MVC assembly into this property, but the code for that would have distracted from the simplicity of the above example).
Hope this helps someone!
For .NET, add the main-built.js file as a script bundle in App_Start/BundleConfig:
public static void RegisterBundles(BundleCollection bundles)
{
//...
bundles.Add(new ScriptBundle("~/Scripts/main-built").Include(
"~/App/main-built.js"));
//...
}
Reference the script bundle on your index page:
#if (HttpContext.Current.IsDebuggingEnabled)
{
<script type="text/javascript" src="~/Scripts/require.js" data-main="App/main"></script>
}
else
{
<!-- Remember to run the weyland optimizer to create the main-built.js -->
#Scripts.Render("~/Scripts/main-built")
}
As long as you have the default Web.Release.Config file, Visual Studio will automatically remove debug attributes while also minifying and versioning your bundles upon publishing.

Resources