IntelliSense for jQuery in WebMatrix

I recently had the opportunity to take a day-long class about jQuery from the good folks at Wintellect. The class went great, and I wrote all of my code for the class in WebMatrix. You might recall from my previous blogs that I am a big fan of WebMatrix, but at first there was one thing that was missing from WebMatrix's arsenal of cool features; in order for WebMatrix to really be useful as an editor for jQuery, I really wanted to have IntelliSense support for jQuery. Thankfully, even though IntelliSense support for jQuery is not built-in, adding IntelliSense for jQuery is extremely easy, and I thought that would make a great subject for today's blog.

To start things off, let's take a look at a jQuery sample that is little more than a Hello World sample:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery Test Page</title>
    </head>
    <body>
        <script src="http://ajax.microsoft.com/ajax/jQuery/jquery-2.0.0.min.js" type="text/javascript"></script>
        <script>
        $(function() {
           $("#bar").text($("#foo").text());
           $("#foo").text("This is some custom text");
        });
</script> <h1 id="foo">This is the first line</h1> <h2 id="bar">This is the second line</h2> </body> </html>

This example does very little: it loads the jQuery library from Microsoft's AJAX Content Delivery Network (CDN), and it uses jQuery to replace the text in a couple of HTML tags. (The example isn't really important - getting IntelliSense to work is the topic du jour.) This sample would look like the following illustration if you opened it in WebMatrix 3:

jQuery in WebMatrix

When you are using a JavaScript library for which there is no built-in support, Microsoft's developer tools allow you to add IntelliSense support by adding Reference Directives to your page, and the files that you would use for your reference directives are available at the same Microsoft CDN where you can get the jQuery library:

http://www.asp.net/ajaxlibrary/cdn.ashx

In order to use IntelliSense for jQuery, you need to download the appropriate jquery-n.n.n-vsdoc.js file for the version of jQuery that you are using and store that in your website. For example, if you are using jQuery version 2.0.0, you would add a script reference to the CDN path for http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.0.min.js, and you would download the http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.0-vsdoc.js file for your website.

Like many developers, I usually add a folder named scripts in the root of my website, and this is where I will typically store the jquery-n.n.n-vsdoc.js file that I am using. Once you have added the appropriate jquery-n.n.n-vsdoc.js file to your website, all that you need to do is add the appropriate reference directive to your script, as I demonstrate in the highlighted section of the following code sample:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery Test Page</title>
    </head>
    <body>
        <script src="http://ajax.microsoft.com/ajax/jQuery/jquery-2.0.0.min.js" type="text/javascript"></script>
        <script>
        /// <reference path="scripts/jquery-2.0.0-vsdoc.js" />
        $(function() {
           $("#bar").text($("#foo").text());
           $("#foo").text("This is some custom text");
        });
</script> <h1 id="foo">This is the first line</h1> <h2 id="bar">This is the second line</h2> </body> </html>

Once you have added the reference directive for your jquery-n.n.n-vsdoc.js file, IntelliSense will begin working for jQuery in WebMatrix, as shown in the following illustration:

jQuery IntelliSense in WebMatrix

In Closing...

One last thing that I would like to mention is that is always a good idea to load JavaScript libraries like jQuery from a CDN, and there are lots of CDNs to choose from. There are some additional steps that you can take to ensure that your website works with jQuery even if the CDN is down, but that subject is outside the scope of this blog. ;-]


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

Not that it will make any difference...

I am a big fan of movies; and to be honest, I am mostly a fan of classic movies. I have slowly collected a large number of classic movies over the years from several of my favorite actors/actresses: Cary Grant, Ginger Rogers, Jimmy Stewart, Katharine Hepburn, Errol Flynn, etc., etc., etc.

That being said, I am generally not a big fan of recent movies; more often than not the creative team is too short-sighted, and they frequently fall short of creating a truly great movie. Sometimes the problem is writing, sometimes it's direction, and other times it's the acting. But to be fair, sometimes the problem isn't with any of those contributors - sometimes it's a problem with post-production, and this is why I love to buy "Director's Cuts" for many films. Quite often there is a level of depth that is missing from the movie that was part of the director's original vision, and it makes the movie so much better when you add that detail back.

Here's a case in point: I actually like the movie Far and Away with Tom Cruise and Nicole Kidman. Once you get past their bad Irish accents, the movie is a somewhat-acceptable dramedy.

But there are a few scenes that were cut from the film, and unfortunately the DVDs that have been released have never added those scenes to the media. Without theses scenes, parts of the plot have abnormal jumps in the storyline, and it's too bad that a Director's Cut has never been released.

Here are some examples of what I mean:

  • Near the beginning of the movie was an extended sequence near the piano in the Christie's house where Stephen Chase has a private conversation with Shannon Christie. We see Stephen's character soften a little; we learn that he truly cares for Shannon, and that Stephen is not a complete jerk - he's just an arrogant by-product of elitist class.
  • Likewise there was a hilltop scene in Ireland after Shannon and Joseph Donnelly have left for America where Stephen is emotionally destroyed, and he expresses his sentiments to Daniel Christie. Once again this softens Stephen's character a little, and this adds a great deal of conflict to the movie as a spectator - you want to hate Stephen, and you feel like you should hate Stephen, but now you can't. That was a great piece of filmmaking that should have stayed in the movie because it added so much depth.
  • There was an extended scene later in the movie when Joseph was working for the railroad. The shortened scene that was kept simply shows Joseph in a job with no future, whereas the original scene showed Joseph as near-suicidal; Joseph believed not only that he had lost Shannon for good, but that Shannon might not have survived her gunshot wound. Because of this, Joseph was known as the "Crazy Mick" and sent on all of the dangerous missions - because Joseph no longer cared if he lived. This added a whole new dimension to the scene when Joseph discovers Shannon in Oklahoma, because it wasn't mere coincidence to him, he felt as if he was seeing a ghost.
  • There was a brief scene when Joseph and Shannon first arrive in America where they pass under a bridge and they see scores of homeless Irish living in squalor. Later in the movie this comes full-circle when Joseph and Shannon are tossed out in the streets, because they find themselves living in that same squalor, and we get to see just how far they have fallen.
  • There was another scene after Joseph and Shannon are tossed out in the streets where workers were needed for ditch-digging; Joseph volunteers so that he can earn money for the two of them, yet when he turns around at some point he sees Shannon working beside him digging in the ditch. This scene was extremely important to see how the two of them were truly becoming one unit in their struggles together, and it adds a great deal of depth to the scene later in the movie when Joseph and Shannon attempt to hide in the house they thought was unoccupied.

The last two deleted scenes that I described show the many months that Joseph and Shannon suffered together, instead of the awkward jump in the theatrical release between the scene when Joseph and Shannon were thrown out of their apartment (with Joseph beat to a pulp) and the scene when Joseph is begging to help someone load firewood (with Joseph now healed and exclaiming that they haven't eaten in days). Without that detail, the theatrical release is missing a great deal of its emotional impact.

Unfortunately, none of the scenes that I have described have ever been released on a DVD, so they are somewhat lost to the world. My descriptions of these additional details won't bring them back, and it's too bad that Imagine Films won't release these scenes in some format. If anyone knows Ron Howard, you might want to suggest that he release a 25th Anniversary Edition of Far and Away when that date eventually rolls around, but in the meantime - my lamentations won't make a bit of difference.

Using FrontPage 2003 to Bulk Rename Images Using VBA

Despite the plethora of other tools and editors that I use to create websites, there are times when I simply have to dust off my copy of (gasp!) Microsoft FrontPage 2003. It may be a dinosaur, but there are some things that it does really well, and periodically I simply need to use it.

An often-mocked and yet critically essential feature that FrontPage 2003 provided was affectionately called "Link Fix Up," which was a feature that would replicate file renames across your entire website. In other words, if you had a file that was named "foo.html," you could rename it to "bar.html" and FrontPage 2003 would update every hyperlink in every file in your entire website which pointed to that file. Needless to say, this feature was often indispensable when I was working with extremely large websites.

Other applications may have similar features, but when you combine that feature with FrontPage 2003's built-in Visual Basic for Applications (VBA) functionality, you have a really powerful combination that can quickly seem indispensable.

With all of that being said, here's a scenario where using FrontPage 2003's "Link Fix Up" functionality with VBA really paid off, and I thought that it would make a great blog (in case anyone else runs into a similar issue and still has a copy of FrontPage 2003 lying around somewhere.)

Problem Description and Solution

I created a mixed-media website some years ago where I had thousands of images that were named like IMG5243.1024x768.png, IMG2745.1280x1024.png, IMG6354.800x600.png, etc. Some part of the file name obviously contained the image dimensions, which was useful at the time that I created the website, but that information was no longer necessary, and the filenames made the Obsessive Compulsive side of my behavior start to act up. (Too many characters.) With that in mind, I decided that I would rename all of those images back to simpler names like IMG5243.png, IMG2745.png, IMG6354.png, etc.

This is where FrontPage 2003's "Link Fix Up" functionality would come in handy; trying to crawl every webpage in my website to update the thousands of image links would have been incredibly painful, whereas FrontPage 2003 would take care of keeping the image links up-to-date for free, provided that I could come up with a way to automate the renaming process. (Enter VBA.)

Here is where I quickly ran into a problem - I hadn't standardized my file naming syntax. (Shame on me.) A lot of filenames had other parts or character strings that were going to cause problems, for example: IMG5243.1024x768_cropped.png, IMG2745.edited_1280x1024.png, IMG6354.new_800x600_small.png, etc. This meant that I was going to have to crawl through each filename character by character and look for image dimensions. This is not difficult through VBA, but it added a bit of complexity because I would have to locate any "x" character in a filename and then starting working my way to the right and left to see if it was surrounded by numbers. In other words, I would have to traverse every file name like "aaa_123x456_aaa.jpg" and "aaa.123x456.aaa.jpg" in order to remove "123x456," while leaving "aaa.wxy.jpg" untouched. Of course, there were also topics to be considered after I removed the numbers, like malformed image names like "aaa__aaa.jpg" and "aaa..aaa.jpg" that had unnecessary character duplications.

VBA Bulk File Renaming Macro

All that being said, here is the VBA macro that I created, which worked great; I was able to have this macro rename my thousands of images in a matter of seconds, and FrontPage 2003 made sure that every image URL in my HTML/ASP files were kept up-to-date.

Sub RemoveImageSizesFromFilenames()
  Dim intSectionCount As Integer
  Dim intXPosition As Integer
  Dim intCharPosition As Integer
  Dim intDictionaryCount As Integer
  Dim objWebFile As WebFile
  Dim strExt As String
  Dim strOldName As String
  Dim strNewName As String
  Dim strUrlStub As String
  Dim strSections() As String
  Dim strWidth As String
  Dim strHeight As String
  Dim objDictionary As Object
  Dim objItem As Object
  Dim varKeys As Variant
  Dim varItems As Variant
  
  ' Define the list of file extensions to process.
  Const strValidExt = "jpg|jpeg|gif|bmp|png"
  
  ' Create a dictionary object to hold the list of old/new filenames.
  Set objDictionary = CreateObject("Scripting.Dictionary")
  
  ' Verify that a website is open; exit if not.
  If Len(Application.ActiveWeb.Title) = 0 Then
    MsgBox "A website must be open." & vbCrLf & vbCrLf & "Aborting.", vbCritical
    Exit Sub
  End If
  
  ' Loop through the files colleciton for the website.
  For Each objWebFile In Application.ActiveWeb.AllFiles
    ' Retrieve the file extension for each file.
    strExt = LCase(objWebFile.Extension)
    ' Verify if the filename is part of the valid list.
    If InStr(strValidExt, strExt) Then
      ' Retrieve the current file name
      strOldName = LCase(Left(objWebFile.Name, Len(objWebFile.Name) - Len(strExt) - 1))
      ' Verify a multi-part filename.
      If InStr(strOldName, ".") Then
        ' Split the multi-part filename into sections.
        strSections = Split(strOldName, ".")
        ' Loop through the sections.
        For intSectionCount = 0 To UBound(strSections)
          ' Verify that each section actually has characters in it.
          If Len(strSections(intSectionCount)) > 1 Then
            ' Check for a lowercase X character.
            intXPosition = InStr(2, strSections(intSectionCount), "x")
            ' Make sure that the X character does not start or end the string.
            If intXPosition > 1 And intXPosition < Len(strSections(intSectionCount)) Then
              ' Make sure that the X character has numbers to the left and right of it.
              If IsNumeric(Mid(strSections(intSectionCount), intXPosition - 1, 1)) And IsNumeric(Mid(strSections(intSectionCount), intXPosition + 1, 1)) Then
                ' Initialize the width/height strings.
                strWidth = ""
                strHeight = ""
                ' Loop through the string to find the height.
                For intCharPosition = intXPosition + 1 To Len(strSections(intSectionCount))
                  If IsNumeric(Mid(strSections(intSectionCount), intCharPosition, 1)) Then
                    strHeight = strHeight & Mid(strSections(intSectionCount), intCharPosition, 1)
                  Else
                    Exit For
                  End If
                Next
                ' Loop through the string to find the width.
                For intCharPosition = intXPosition - 1 To 1 Step -1
                  If IsNumeric(Mid(strSections(intSectionCount), intCharPosition, 1)) Then
                    strWidth = Mid(strSections(intSectionCount), intCharPosition, 1) & strWidth
                  Else
                    Exit For
                  End If
                Next
                ' Remove the width/height string from the current filename section.
                strSections(intSectionCount) = Replace(strSections(intSectionCount), strWidth & "x" & strHeight, "")
              End If
            End If
          End If
        Next
        ' Reassemble the file sections.
        strNewName = Join(strSections, ".")
        If Right(strNewName, 1) = "." Then strNewName = Left(strNewName, Len(strNewName) - 1)
        ' Cleanup several unnecessary character sequences.
        If StrComp(strOldName, strNewName, vbTextCompare) <> 0 Then
          strOldName = strOldName & "." & strExt
          strNewName = strNewName & "." & strExt
          strNewName = Replace(strNewName, "_.", ".", 1, -1)
          strNewName = Replace(strNewName, "._", "_", 1, -1)
          strNewName = Replace(strNewName, "..", ".", 1, -1)
          strNewName = Replace(strNewName, "__", "_", 1, -1)
          strUrlStub = Left(objWebFile.Url, Len(objWebFile.Url) - Len(strOldName))
          ' Add the old/new file URLs to the dictionary.
          objDictionary.Add strUrlStub & strOldName, strUrlStub & strNewName
        End If
      End If
    End If
  Next
  
  varKeys = objDictionary.Keys
  varItems = objDictionary.Items
  
  ' Loop through the collection of URLs to rename.
  For intDictionaryCount = 0 To (objDictionary.Count - 1)
    ' Avoid collisions with existing URLs.
    If Application.ActiveWeb.LocateFile(varItems(intDictionaryCount)) Is Nothing Then
      ' Get current URL.
      Set objWebFile = Application.ActiveWeb.LocateFile(varKeys(intDictionaryCount))
      ' Rename the URL.
      objWebFile.Move varItems(intDictionaryCount), True, False
    End If
  Next
  
End Sub

In Closing...

There are a couple of additional details about this macro that you should consider:

First of all, this macro intentionally avoids overwriting the destination filename if it already exists. For example, if you have two files named IMG1234.100x100.jpg and IMG1234.200x200.jpg, simply removing the image size characters from each file name would result in a collision for the name IMG1234.jpg. What the macro currently does is to rename the first file, then it leaves any possible collisions unchanged. You could easily modify this script to prompt the user what to do, or you could configure it to rename each file with a syntax like IMG1234a.jpg / IMG1234b.jpg / IMG1234c.jpg, but I'll leave that up to you.

Second, I wrote this macro for a specific set of file types and filenames, but you could modify the macro for a variety of scenarios. For example, one developer that I knew liked to test his content on his production server by creating preview files with names like foo.preview.html and bar.preview.aspx. This allowed the production files to coexist on the same server with the preview files, although the production files would have the production-ready filenames like foo.html and bar.aspx. Once he was ready to push the preview files into production, he would simply rename the necessary files. This system worked for a small set of files, but it didn't scale very well, so the amount of labor on his part would increase as the website grew more complex. (Of course, he should have been using a development website for his preview testing, but that's another story.) In any event, this macro could easily be modified to remove the ".preview." string from every file name.


Note: This blog was originally posted at http://blogs.msdn.com/robert_mcmurray/

Your Tablet PC is Not a Camera

It never ceases to amaze me the number of people who walk around with a tablet PC and try to use it as a camera.

I don't care how many megapixels a tablet PC has - it's not a real camera, and people look pretty silly trying to hold up a tablet in order to use it as one. Not to mention the fact that people with tablet PCs are typically blocking everyone else's view.

Please do yourself and the rest of the world a favor - if you need to take a photo, buy a real camera.