Bundling jQuery 2.x and jQuery 1.x in ASP .Net MVC and staying NuGet fresh

Fork in the road
If you use Nuget to install jQuery into your application, you’ll need to take some extra steps to support multiple versions of jQuery.  By default, NuGet will uninstall previous versions of a package.  The way around this is to create another folder inside the scripts folder and put the older jQuery-1.. files in it. I got the idea for doing this from a post on StackOverflow

Right click on the Scripts folder and select Add->New Folder.  Give the folder a name that has some meaning to you, I used “compatibility”.  Select the jquery-1.* files and move them to the new folder.  You can copy them or move them, it doesn’t really matter.

Then install the latest version of jQuery using NuGet.  From the Tools menu, select Library Package Manager->Package Manager Console.  From the package manager window run the following:
Install-Package jQuery

You should see something like this:

Package Manager Console
Package Manager Console

It installed jQuery 2.1 and then it removed the jQuery 1.10 package.  It complained that it couldn’t find the intellisense file for the previous version. That’s because I had moved it to the new folder.

Now it’s time to update the bundles. When you create a new web project, ASP .Net will create some bundles for you. A bundle is a collection of scripts and stylesheets and does a neat little trick where at debug time you get the individual files as if you had specified each one in the web page. At runtime, the files are minified and consolidated into a single file. This compresses the payload and saves on loading time as the browser only needs to make a single request to get the files in the bundle. Any hoo, if you create a ASP .Net project in the current version of VS, you will get this bundle definition in BundleConfig.cs:

public class BundleConfig
    public static void RegisterBundles(BundleCollection bundles)
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        // Other code removed...

This call to bundles.Add creates a new bundle named “~/bundles/jquery” and uses the {version} regex placeholder, (\d+(?:.\d+){1,3}), to match the jQuery file without having to specify the version. You don’t have to worry about your code breaking due to an invalid reference to jQuery when NuGet updates jQuery.

What we do now is add a second bundle that will use the older version of jQuery. Since we copied those files to a new folder, NuGet is blissfully unaware of their continued existence and will not remove them. We just create a ScriptBundle with a new name and have it specify the folder that we put the old version of jQuery in.

public class BundleConfig
    public static void RegisterBundles(BundleCollection bundles)
        bundles.Add(new ScriptBundle("~/bundles/jqueryold").Include(

        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        // Other code removed...

The final step is to update the shared layout view that MVC puts the jQuery script reference in.

With a new project, you will edit the Views\Shared_Layout.cshtml file. The default jquery reference will look like something this:

    @RenderSection("scripts", required: false)

What we need to do is the replace the @Scripts.Render line with a conditional block of code that checks for older versions of Internet Explorer.

    <!--[if lt IE 9]>
    <!--[if gte IE 9]><!-->
    @RenderSection("scripts", required: false)

We use IE’s Conditional Comments to detect previous versions of IE. This a feature specific to IE versions 5 through 9. All other browsers will treat the Conditional Comments as regular HTML comments.

<!--[if lt IE 9]>

With this line, IE 5-9 (and 10 in compatibility view) will treat this as the start of a block of code. All other browsers will treat this as the start of a comment block. The block is closed when it hits “–>”.

    <!--[if gte IE 9]><!-->

With this block, we are saying if IE is greater than or equal to version 9, to use this block. The “<!–>” on that line tells IE 10 and the other browsers to close out this comment block which makes that block of code available to the browser. This will allow you to stay current by letting NuGet updating jQuery, while still keeping some level of compatibility with older versions. This is one of the times where IE extending HTML in a proprietary way is useful.

The fork in the road image was modified from an creative commons licensed image posted by Eric Hamiter to his Flickr collection.

Sometimes 42 is the right answer

Prime Meridian

I was skimming the Codist blog when I read the following

One of my favorite data errors was when the latitude would be randomly in the 1000s even though the longitude was correct. MapKit would toss a fit so since I can’t know what the right value is, I just use 42 which puts the pin at the wrong location but at least it’s not crashing.

I just started laughing. Been there, done that, want it on a t-shirt.  When collecting positional data from other sources, sometimes you just get bad data in.  And in this case, 42 is the Ultimate Answer.

A while back I had written a data collection service that was collecting vehicle positions from onboard GPS device.  Every now and then, the locations became random.  This app was running in the continental US,  any latitude/longitude values outside that range for that area were just ignored.  In my case, any wrong location was unusable data.

The Prime Meridian image comes from Lindsay Holmwood’s Flickr feed.

A file versioning helper class in C# to make a backup copy of a file and keep the last N copies of that file

Cicero denouncing Cataline

While testing my configuration editor app, one of the QA guys asked if it made a backup copy of the file being edited.  My reply was “not yet”.  And I thought about it a bit and decided to implement the backup feature and to kick it up a notch.

In prehistoric times, VMS would automagically version your files when you saved them.  When you saved a file, the file system  would append a version number starting at 1.  You could open any version of a file by including the version number.  If you left out the version number, you got the latest version.  This goes back to the days when monitors supported both colors, green and not green.  To clear out older versions, you would periodically need to run the purge command.

Prehistoric times for web developers

Prehistoric times for web developers

I wanted something close to that in my code, except without having to manually purge the file system.  I wrote a simple static class that takes the name of the file and the number of versions to keep.

public static class FileHelper
    /// <summary>
    /// Make a numbered backup copy of the specified files.  Backup files have the name filename.exe.yymmdd##, where yymmdd is the date and ## is a zero justified sequence number starting at 1
    /// </summary>
    /// <param name="fileName">Name of the file to backup.</param>
    /// <param name="maxBackups">The maximum backups to keep.</param>
    public static void MakeBackup(string fileName, int maxBackups)
        // Make sure that the file exists, you don't backup a new file
        if (File.Exists(fileName))
            // First backup copy of the day starts at 1
            int newSequence = 1;

            // Get the list of previous backups of the file, skipping the current file
            var backupFiles = Directory.GetFiles(Path.GetDirectoryName(fileName), Path.GetFileName(fileName) + ".*")
                .Where(d => !d.Equals(fileName))
                .OrderBy(d => d);

            // Get the name of the last backup performed
            var lastBackupFilename = backupFiles.LastOrDefault();

            // If we have at least one previous backup copy
            if (lastBackupFilename != null)
                // Get the last sequence number back taking the last 2 characters and convert them to an int. And add 1 to that number
                if (Int32.TryParse(Path.GetExtension(lastBackupFilename).GetLast(2), out newSequence))

                // If we have more backups than we need to keep
                if (backupFiles.Count() >= maxBackups)
                    // Get a list of the oldest files to delele
                    var expiredFiles = backupFiles.Take(backupFiles.Count() - maxBackups + 1);

                    foreach (var expiredFile in expiredFiles)

            // Create the file name for the newest back up file.
            var latestBackup = String.Format("{0}.{1:yyMMdd}{2:00}", fileName, DateTime.Now, newSequence);

            // Copy the current file to the new backup name and overwrite any existing copy
            File.Copy(fileName, latestBackup, true);
// String Extension that was used in the code but left out when I first published
public static class StringExtension
    public static string GetLast(this string source, int tail_length)
       if(tail_length >= source.Length)
          return source;
       return source.Substring(source.Length - tail_length);

You would use this method like this:

FileHelper.MakeBackup("web.config", 5);

The first time you called it, you would get web.config.14031401. The next time would get web.config.14031402. When web.config.14031406 was created, web.config.14031401 would be deleted to keep the number of backups limited to 5.

[Updated August 17th, 2015]
When I posted this, I left out a string extension methiod that I use to get the last N characters from a string.  That code is now included.

We had a great TVUG meeting this week


A couple of nights ago, @PeterLanoie did a great presentation on IIS administration.  This was at the March TVUG meeting.  We had a good sized crowd and there were plenty of questions and discussions from the audience.  Peter had some cool tricks to show off.  Like how to use an App_Offline.htm file to take a site offline while making updates.

We spent a lot of time going over session management, multiple levels of configuration files, deployments, and how to handle those types of thing when you have a web farm.  As developers, we don’t always have the experience or knowledge to optimize IIS for large traffic sites.

Peter spent over two hours drilling in deep on these topics.  It’s great when a user group member can step up to the plate and Peter knocked this one out of the park.


If you are in the Albany, NY area, check out TVUG.  That’s the Tech Valley .Net User Group, located right in the middle of Tech Valley, NY.  We usually meet on the second Tuesday of the month.  We have a mailing list that you can sign up for and we have a MeetUp page.  You can also find us on Facebook and Twitter.

Validating a GUID input, TryParse vs RegEx

Once again I’m validating some text inputs, this time I need to verify that a user has entered a GUID in a valid format.  While I can’t verify that the user has entered the correct GUID, I can check to make sure that I have the right characters in the string.

The choice is between a method in the .Net Framework for parsing GUID values or using a regular expression. The commonly accepted formats for a GUI are the following

  • {0C885DD3-7DD9-484B-9B20-3E6552BCA144}
  • 0C885DD3-7DD9-484B-9B20-3E6552BCA144
  • 0C885DD37DD9484B9B203E6552BCA144

You usually see it written as 32 hexadecimal characters, separated by hypens into 5 groups.  There are some other variations, but this is what you see for text representations of GUIDs.

Going via the .Net Framework, we can use the Guid.TryParse() method. This method takes two parameters, the string to parse and an out parameter that gets the parsed GUID.  TryParse() returns true if it can parse the string, false if the string input is not a valid GUID format.  It happily takes GUIDs in all three formats list above.

The regular expression that I found for GUID validation is, as with almost all regular expressions, a hideous mess of seemingly random characters.  A well crafted regular expression should look like line noise from a 300 baud modem.  This regular expression would validate a GUID:


That’s not very friendly when you first see it. Lets break it down:


The ^ and $ characters match the start and the end of string, everything else takes place with the string to match. We are basically saying, use the entire string input to validate against.


This says match the “{” character and the question mark states that it is optional


This says match 8 characters using all of the digits and the letters from A to F. It’s case insensitive and there is an optional “-“.


This says match 4 characters with an optional hyphen, 3 times in a row.


This matches the final block of 12 characters (with optional hyphen)


We end with an optional match for “}”.

The source for this regular expression was one submitted by Nicolas Berardi on the RegExLib site.  There were a few other GUID validation strings on that site, his looked the best. I did change his expression, it was also allowing for “(” and “)” in addition to the curvy brackets.  I don’t think that makes the GUID valid, so I removed it. The “{” and “}” are not part of the IETF 4122 standard, if you are matching UUIDs, then you may want to take out the part that allows for those characters.

The problem is that it would validate text inputs that shouldn’t validate.  If your GUID string had a single hyphen, it would pass the regex test, but would fail when used by the .Net Framework.  It was also much slower than the TryParse() code, roughly 25 times slower on average.

For user interaction, the performance hit would be negligible. If you were doing a batch import program and were validating the data, you’re going to take a performance penalty hit when you use regular expressions.

The following code shows both implementations with some samples to parse:

The last two sample strings should fail the parsing. The last one only is short one character, the one before it has only one hyphen. The TryParse method works correctly for all of the values, the RegEx fails on the one with a single hyphen. You should be able to tweak the expression by testing for 5 hyphens or for no hyphens. Then you would get this easy to remember version:


For C# code, I’ll stick with TryParse(). The RegEx version, I’ll save for Javascript.  If you wanted to validate GUID text entry in a browser, the same expression can be used.

For the record, having the user enter in GUID values is a mind boggling UX failure. In this case, this is for an admin tool where the admin user would be copying and pasting in the GUID value from an email.

In case dotnetfiddler falls down, the source code is available on Github Gist.

Getty Images now providing a huge selection of images free for non-commercial use

Getty Images is how made available a large selection of images from their gallery free for non-commercial use in social media. For free. Which is pretty cool. There are times when you want to add an image to illustrate a point and a screen shot isn’t always applicable. And you may not have an image that you own that fits the theme.

It’s pretty simple to use. You just browse or search the Getty Catalog until you find an image that you want to use. If you hold hover your mouse over the image, you’ll see a pop-up window with additional details for that image. If that images has a link button, “</>”, then it’s available for linking on your blog or web site.

Getty Image pop-up

When you click the embed button, a new window will popup.  This window will have the HTML code needed to display the image.  It’s wrapped inside of an <iframe> and will have all of the branding required for the acceptable usage of the image.

The HTML code required to display the image

As long as you are OK with the Getty branding at the bottom of the image, you now have a high quality source of free to use images for your blog.  Just paste that <iframe> block into your blog post and you are set to go.  Sometimes there is such a thing as a free lunch.

Today I remembered that every URL is an URI, but not vice versa

I was writing some validation code for a desktop app and there are some fields require web page URLs.  My first thought was to a regular expression to validate the input, then this quote came to mind.

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
Jamie Zawinski

Regular expressions can solve many problems, but if there is a method in the .Net Framework that will solve the problem, I’ll use that first.

I started off using the IsWellFormUriString method from the Uri class.

I created a string extension method called ValidateUrl() and tried it with the following examples

  1. http://foo.com
  2. htp.foo.com
  3. ftp://foo.com
  4. what://foo.com

You can see the results of those examples with the following .Net Fiddle:

The first is valid and we expected that. The 2nd is not valid and is expected. The 3rd is valid and I didn’t account for that in the code. The last one, what://foo.com, that was unexpected. That is obviously not a valid URL. Or at least not valid for the purposes of my app.

But I wasn’t check to see if the URL was valid, I was checking to see if the URI was valid. A URI consists of a scheme name (“http”, “ftp”, “mail”, etc), followed by the “:” character, and then by the path the resource. The Uri.IsWellFormedUriString method does not validate the scheme name, it’s just validating that the resource was assembled correctly.

Validating for a web page URL would be on me. I can use Uri.IsWellFormedUriString, but I would need to add an additional check to verify that the URI started with http:// or https://. With that modification, the example from above becomes this Fiddle:

And with the same inputs, I now get the results that I need. The one that starts with “ftp:” is a valid URL, I’m returning it as invalid because that meets the requirements of my app. Your mileage may vary.

While testing the code, I came across an example of a valid URL that IsWellFormedUriString will return as invalid. It fails on URLs with embedded unicode characters. Like this one:


This apparently broke in .NET 4.5 and was logged as bug. And according to the notes attached to that bug, it’s not going to be fixed any time soon. For this project, I know that the URLs that could be entered in by the user would not have unicode characters, so I don’t have to worry about that.

If I did have to handle unicode characters, that’s when I would use a regular expression. Someone already went in search of the perfect URL validation regex and found one from Diego Perini that handles all sorts of use cases.

Weighing in at 502 characters, this handles just about any valid URL.


In that format, that regex is what you would call write-once code. Diego posted a commented version of it as a gist, you can read that without your eyes bleeding.