Skip to content
Firebug's console object is great, but it only works with FireFox

Avoid non-FireFox browser issues with Firebug’s console object

The Firefox Firebug add-in is a superb JavaScript debugger. If you’re writing, learning, or debugging JavaScript (and if you’re doing the first two, you’re certainly doing the third!), Firebug should be in the top drawer of your JavaScript toolbox.

One of the Firebug features I use a lot is its console object. The console object lets you emit messages from your code to Firebug’s console. For example, console.log( n ); emits informational message n to the Firebug console while console.error(n); emits error message n to the Firebug console. This console is very handy, especially in your JavaScript unit testing code. While Firebug doesn’t have a steep learning curve, some of its features can sneak up on you. If you haven’t yet dug into Firebug’s console, do so soon!

A challenge that the Firebug console presents is that to use it requires that you pepper your code with Firebug-specific code that will cause the code to break in other non-Firefox browsers. For production work, you’ll probably want to comment out or remove console lines.  However, I want to run my JavaScript unit tests in several browsers and don’t want to have to change the test code to do so.

Firebug’s creator, Joe Hewitt, posted a nice little chunk of code (shown below) that maps Firebug’s various console methods to no-ops for non-FIreFox browsers. With Joe’s code in place, JavaScript tests can run in any browser. For qUnit JavaScript unit testing code, add Joe’s code to the module’s setup method (more on qUnit in an upcoming post).

Joe Hewitt’s prophylactic Firebug console code
  1if (!window.console || !console.firebug)
  2{
  3    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
  4    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
  5
  6    window.console = {};
  7    for (var i = 0; i < names.length; ++i)
  8        window.console[names[i]] = function() {}
  9}

One final note: I occasionally teach JavaScript. Joe’s graceful little solution to the awkward cross-browser problem posed by using Firebug’s console object makes a great little quiz for JavaScript beginners. It’s not a lot of code, but what little code there is is interesting code. When someone can explain Joe’s code clearly, I know they are ready for the next notch in their JavaScript programming belt.

How to serve SVC files

Deploying a WCF service to IIS 6.0

I needed to deploy a WCF Web service to a Windows 2003 server today. I was happy to realize that .NET 3.5 and .NET 3.5 SP1 were both installed, so I thought I was home free. Hardly. Here are the steps I needed to take to get the WCF 3.5 service running on the Windows 2003 server.

Making IIS recognize the .SVC extension

The first problem I had was that I got a 404 error when I tried to load the .SVC file in a browser. I knew I had the file name specified correctly and previous experience with JSON and IIS lead me to believe that IIS didn’t know about the .SVC file type. A little checking made me quickly realize that the .SVC file wasn’t mapped to the ASPNET_ISAPI.DLL in Windows 2003 Server’s IIS 6.0.

Before I did that manually, I read this MSDN article and learned about the ServiceModelReg.exe. This exe registers script maps in IIS. I ran it on the server and it finished very quickly. The MSDN article recommends checking the SVC ISAPI mapping after having run this program, but the mapping was now in place for me. If it’s not for you, there are instructions at the end of the article that show how to map the .SVC extension to the ASPNET_ISAPI.DLL. (For what it’s worth, I did need these mapping instructions when attempting to host the service on my Windows 7 development box.)

Preventing anonymous access to the service

I thought I was home free. Alas, another error. When I attempted to load the .SVC file with the browser again, the file was now found but the error returned was  ‘Anonymous’ Authentication but it is not enabled for the IIS application that hosts this service." Hmm. I knew that I had anonymous access configured for the virtual directory—something seemed very screwy. A little googling lead me to this article on Nicholas Allen’s Indigo Blog. He clearly explained exactly the scenario I was experiencing. 

To fix the problem, I disabled anonymous access on the virtual directory and then added the following <security> node to Web service’s binding configuration.

Figure 1. Nicholas Allen’s fix to disable anonymous access
  1<basicHttpBinding>
  2    <binding name="allowBigData" maxReceivedMessageSize="2000000">                     
  3        <readerQuotas maxArrayLength="2000000" maxBytesPerRead="2000000"/>
  4        <security mode="TransportCredentialOnly">
  5            <transport clientCredentialType="Windows" />    
  6        </security>
  7    </binding>
  8</basicHttpBinding>

Be sure to read Nicholas’s article closely—gotchas lurk if you’re using WSHttpBinding.

Thanks to Nicholas and MSDN, my service works now!

rp

Using jQuery to work with ASP.NET-munged HTML elements

ASP.NET (pre-ASP.NET 4.0, that is) makes it a point of munging control IDs by forcing a fully-qualified naming scheme on both the resulting HTML element’s ID and Name attributes. For example, a TextBox named textboxName, when placed in a user control used on a content page with a master page gets rendered like this at runtime:

Figure 1. HTML element with munged ID and Name attributes.
  1<input name="ctl00$ContentPlaceHolder1$ctl00$textboxName" 
  2       id="ctl00_ContentPlaceHolder1_ctl00_textboxName" 
  3	      type="text" />

It’s often desirable to dynamically associate either behaviors or cosmetic styling to these elements, but because of the munged ID, locating these elements, especially with bare-naked CSS selected is challenging (unless you hard-code special case CSS class names).

jQuery makes the selection of such elements quite easy. Because the munged IDs always end with the control’s base name, you know that the resulting HTML ID will end with that control name. Here’s how to use jQuery to select these elements based on the ending value of their ID.

First, add a reference to jQuery in the master page’s <head> section. (In this example, I’m pulling jQuery from the Microsoft Ajax Content Delivery Network.)

Figure 2. Add a reference to jQuery in the section of the master page.
  1<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js" 
  2        type="text/javascript"></script>     

To locate an HTML element with a munged ID, use the jQuery AttributeEndsWith selector. This selector finds all elements where the given ID ends with a specific value.

Figure 3. Add this JavaScript to the content page.
  1<script type="text/javascript">
  2    $( function() {
  3        $( "input[ id$='textboxName']" ).val( "prove this." );
  4    });
  5</script>

The example above selects the input element that ends with “textboxName” and sets its value to ‘”prove this.”

jQuery’s AttributeEndsWith performs a brute-force traversal of all of the tags specified (and applies a regular expression against the ending value provided) so this technique may have some potential performance issues, but my experience with it hasn’t shown any glaring degradation.

rp

Getting to know Resharper: Generate a constructor

Resharper, the terrific Visual Studio productivity plugin, reduces adding a constructor for class, with as many arguments as you need, to just a few mouse clicks.Here’s how to use this Resharper feature.

Figure 1a. Class without a constructor.
  1public class Artist
  2{
  3    public int ArtistId { get; set; }
  4    public string Name { get; set; }
  5    public int Rank { get; set; }
  6}

Put the cursor somewhere in the body of a class that needs a constructor and press Alt/Ins (or use the Resharper>Code>Generate menu option). This displays Resharper’s Generate context menu (as shown below). Click “Constructor.”

ContextMenu

Coding with Resharper is almost like pair programming but minus the gum-chewing, Jonas Brother-listening, obnoxious coder next to you.

This shows the Generate constructors dialog below. Select the members you want as arguments to the constructor with the checkboxes (selecting the class name selects all of the fields for use as constructor parameters). You can also select the access rights (public, private, et al) as well as whether you want an XML comment block added. Resharper is context sensitive–when using it to inject a constructor in an abstract class it’s smart enough to mark that constructor protected. Why? Read this. For my money, providing this level of awareness is how Resharper elevates itself from being a simple code paster to being a true ally in helping you write better code. It’s almost like pair programming but minus the gum-chewing, Jonas Brother listening, obnoxious coder next to you.

The “Advanced” button lets you specify what arguments are passed on to a base constructor (if any are available).

generate

Assuming that the ArtistId and Name fields were selected, when you click “Finish” the constructor shown below is immediately added to the class.

Figure 1b. Class with constructor automatically added.
  1public class Artist
  2{
  3    public Artist( string name, int artistId )
  4    {
  5        Name = name;
  6        ArtistId = artistId;
  7    }
  8
  9    public int ArtistId { get; set; }
 10    public string Name { get; set; }
 11    private int Rank { get; set; }
 12}

As you can see, Resharper makes it ridiculously easy to automate constructor creation, with optional parameters and value assignments. Although my examples show Resharper working with C#, there is a VB.NET version of Resharper available.

Using Linq to create an ADO.NET connection string

I know I’m a little late to the party, but I am quickly falling in love with Linq. Once you start adopting its functional mindset, it is so expressive and direct.

I once heard someone way that once you really get Linq, you’ll won’t ever need to write a For/Each loop again. Probably an overstatement, but still I was intrigued. I set out last night to see how Linq could negate the need for For/Each.

I set out to find a way to create ADO.NET connection strings. In the past, I would have probably used foreach to iterate over a collection using StringBuilder and String.Format to build up the connection string. I dispensed with all that old-school thought and created the connection string as shown below in Figure 1. As a bonus, I also learned (thanks to a little prompting from Resharper) a shortcut for initializing a collection.

The Linq code in lines 10 and 11 is where the cool stuff happens. Each element from the dictionary is selected to create a value pair and the Linq Aggregate() operator is used to concatenate all of the value pairs. All very sweet!

Figure 1. Using Linq to create an ADO.NET connection string
  1var o = new Dictionary< string, string >()
  2	{
  3		{ "Data Source",           "DUFFSQLSERVER2008" },
  4		{ "Initial Catalog",       "Chinook" },
  5		{ "Persist Security Info", "True" },
  6		{ "User ID",               "xxxxx" },
  7		{ "Password",              "xxxxx" }
  8	};    
  9
 10var ConnectionString = o.Select( i => i.Key + "=" + i.Value ).
 11                         Aggregate( ( a, b ) => a + ";" + b );
 12
 13Console.WriteLine( ConnectionString );

I used LinqPad to create and test this code. I just started using LinqPad and can’t believe I ever coded without it. Beyond being a great test bed for Linq, it is a superb snippet compiler. LinqPad is a free download and should be in every coder’s toolbox.

linqpad

JavaScript: The Joe Walsh of programming languages

This is the first in a series of posts to provide C# and VB coders with a quick look at JavaScript. In this installment, I’ll look at JavaScript’s dynamic typing and its interesting (ie, not what you’d expect!) variable scoping

 

When ASP.NET debuted one of the improvements it brought to Web development was the way in which it hid away lots of painful, aggravating JavaScript. For a long time we thought that was a virtue. None of us liked JavaScript back then. It was fiddly, hard-to-debug, and required black magic incantations to work correctly.

Then along comes Ajax and does for JavaScript what the Eagles did for Joe Walsh. The promise of rich (or at least richer) user interfaces was quite alluring and that and better JavaScript-centric tools and books quickly made us reconsider JavaScript. While JavaScript still has warts and hairs, its singular role as the ubiquitous browser programming language trumps those problems. JavaScript is clearly with us for the long haul.

As ubiquitous as JavaScript is, I often bump into very bright VB and C# coders who don’t know much about JavaScript. This is the first is a series of articles that explains JavaScript for VB and C# programmers. I’m not going to try to provide the definitive JavaScript tutorial; the Internet doesn’t need another one of those. There tons of great JavaScript resources available (see the reference links at the end of this post). What I am going to present in this series a few JavaScript basics that have helped me. I’ll also introduce you to some JavaScript tools and techniques that work well for me.

Elusive language

For a VB or C# coder, JavaScript is a sneaky, elusive language. Syntactically, it grows from the same curly-brace, semi-coloned roots that C#, C, and even Java does. However, to master JavaScript you quickly need to learn that JavaScript is very much a different language than either C# or VB. The differences are subtle because JavaScript, especially the JavaScript written by rookie JavaScript coders, can indeed behave very much like imperative C# or VB. But, as we’ll see, behind the JavaScript curtain lurks some functional aspects that are very powerful, but easy to overlook. We’ll get to those later; let’s first focus on a few basics.

For the purposes of these posts, I’m going to assume at least a passing syntactical knowledge of C#. If you’re a VB coder with minimal or no C# knowledge, the examples I’ll provide here should be short enough that you’ll be able to intuitively grok the syntax.

Dynamic typing

Let’s start first with a simple JavaScript example. Figure 1 below shows a simple JavaScript function that apparently returns the sum of two numeric values. And indeed it does if both arguments passed to it are numeric values. With this code, you can quickly see the initial syntactical similarity that JavaScript has to C# and Java.

Figure 1. A simple JavaScript example
  1var z = sum( 4, 8 );
  2
  3function sum( value1, value2 )
  4{
  5    return value1 + value2;
  6}

However, unlike VB and C#, JavaScript is dynamically typed. As such, notice that in the code in Figure 1 JavaScript types aren’t explicitly declared for any variables or functions. Neither z, nor value1, value2 nor even the type that is returned by sum() are, or can be, declared. Note that .NET 3.5’s C# and VB’s var keyword, despite its looks, does statically type a variable. JavaScript is doing no such thing with its var. JavaScript’s var is truly dynamically. Given JavaScript’s dynamic typing, z can be a numeric value but then later be a string, as shown below in Figure 2:

Figure 2. JavaScript is dynamically typed
  1 z = sum( 4, 8 );
  2
  3 z = “Neil” 

Give this dynamic typing, it’s possible to call sum() with arguments of types other than numeric as shown below in Figure 3:

Figure 3. Sum()’s arguments aren’t explicitly typed
  1var z = sum( “Neil”, “Young” );

The call in Figure 3 returns the concatenated result “NeilYoung.” JavaScript would even let you call sum() as shown below in Figure 4:

Figure 4. Dynamic typing in action again
  1var z = sum( “Neil”, 8 ); 

where the result would be “Neil8.” Interesting, huh? JavaScript has the innate ability to dynamically coerce types when necessary. In the case of Figure 4 above, the numeric value 8 is coerced to string to produce the concatenated string result. But wait, it gets more interesting. Guess the result of Figure 5 below:

Figure 5. Dynamic typing in action
  1var z = sum( “6”, 8 );

That’s right, it’s “68.” Now, guess the result of Figure 6 below; it’s a little trickier:

Figure 6. Attempting explicit casting
  1var z = sum( 0 + “6”, 8 );

In this case, the result is “068.” As I was learning this, I would have bet you a paycheck that the 0 + “6” would have resulted in a coerced numeric value of 6, but that isn’t the case. Like VB and C#, the + sign means either arithmetic addition or string concatenation. If there is a string somewhere in the expression, JavaScript always assumes the + sign means string concentration. Getting sneakier, consider the output of Figure 5 below:

Figure 7. A way to explicitly cast a string to numeric value
  1var z = sum( 1 * “6”, 8 );

In this case, because the * sign has only one meaning, arithmetic multiplication, the 1 * “6” does indeed get coerced to the numeric value 6 and the result of calling sum() as shown in Figure 7 is the numeric value 14. If you try an arithmetic operation against the wrong type (eg, 1 * “A”) then JavaScript returns a special value named “NaN” indicating that the operation couldn’t be performed on non-numeric values. I’ll discuss NaN later in a post about JavaScript error handling.

We’ll see later that JavaScript has a few other explicit type conversion options available to it. We’ll also see that JavaScript has the ability to test the types of variables so that you can build in a little type-safe protection when it’s needed. Note though, the impact that JavaScript’s dynamic typing has on function naming. The name sum() for the function above (at least as it is currently written) is a poor name for that function because it can do more than just the numeric operation implied by the name “sum().”

Unusual variable scoping

Variable scoping in JavaScript has two levels to it: an easy, pretty obvious level and another richer but more complex level. This second level has to do with JavaScript closures. Closures are beyond the scope of this post, but will be covered in another later. For now let’s consider the basic implementation of JavaScript variable scoping.

When you declare a variable with JavaScript, the var keyword is optional (although is should be required!). For example, Figure 8 below declares variable x

Figure 8. Declaring a variable with the var keyword
  1var x = 89;

as does the line below in Figure 9:

Figure 9. Declaring a variable without the var keyword
  1x = 89;

Both lines declare a variable x, but there is a difference. When you use var to declare a variable, that variable is scoped either globally to all functions (if it’s declared outside of any functions) or scoped to the function in which it’s declared. Let’s look at a few more examples.

Figure 10 below shows a global variable x being declared. Because x isn’t owned by a function, its value is available anywhere. Remember, too, that global Javascript variables are available to all other JavaScript files used by any one page. Global truly means global in this case.

The example below shows x being assigned to the scopeTest()’s variable y which, because the var keyword is used, is available only inside scopeTest().

Figure 10. Declaring a variable outside the bounds of functions
  1var x = 89;
  2
  3function scopeTest()
  4{
  5    var y = x;
  6}

Because x is global by virtual of not being declared inside a function, the use of var in line 1 in Figure 10 above is option. Had line 1 omitted the var keyword, the behavior in Figure 10 would not have changed. Having said that, the var keyword doesn’t change the global behavior (because x is declared outside the bounds of any functions); you should always use the var keyword.

If the code in Figure 10 were written as shown below in Figure 11, the variable y declared in scopeTest() is global (because it isn’t declared with the var keyword). The interesting thing about the y variable is that it isn’t available to the rest of the program until scopeTest() has been called once. Therefore, the code below will fail at line 3 (where writeLine() is a diagnostic function to display a variable we’ll discuss later) because testScope() hasn’t yet been called.

Figure 11. declaring a global variable in a function
  1var x = 89;
  2
  3writeLine( y ) 
  4
  5function scopeTest()
  6{
  7    y = x;
  8}

However, anytime after a call is made to testScope(), then the global variable y it declared is available to the rest of the JavaScript program. Figure 12 below will now correctly display the value of the global variable y.

Figure 12.Referencing y
  1var x = 89;
  2
  3scopeTest();
  4
  5writeLine( y );
  6
  7function scopeTest()
  8{
  9    y = x;
 10}

JavaScript variables are not block-scoped

Remember that variables are not blocked scoped in JavaScript like they are in C# or Java; rather in JavaScript variables declared in a function are scoped to all of the code in that function. Therefore, what appears as though it should be a variable private to the if block below is really available from where it’s declared on down in the function. Figure 12 below shows this.

Figure 12. JavaScript local variables are block-scoped
  1function scopeTest()
  2{
  3    // Variable x is undefined here.
  4    if ( condition )
  5    {
  6        // Variable x is available beyond the 
  7        // if block’s scope. 
  8        var x = 89;
  9    }
 10    // Variable x is available here!
 11}

As you can imagine, bad things can happen when you omit the var keyword. The general rule of this is don’t ever omit it! If a variable needs to be global, don’t declare it inside a function, declare as an inline variable. Note also that the dynamic nature of JavaScript can get you in big trouble quickly if you aren’t vigilant. Consider the code below in Figure 13:

Figure 13. JavaScript doesn’t have Option Explicit!
  1Function scopeTest()
  2{
  3    var myRate = 89;
  4    Myrate = myRate + 100;
  5}

In this case, I meant to increment the value of myRate by 100. However, I got the case wrong on line 2 spelling Myrate instead of myRate. So, without any fanfare, JavaScript sees that not as an error, but rather as my desire to declare a second global variable named Myrate. Not only was myRate not incremented as needed but I also got a free global variable out of the mistake. And, this is important, myRate has an incorrect value with JavaScript providing no clues as to anything being amiss.

For my money, the ease with which a coder can make such a simple, profound mistake is why JavaScript got a bad name in the first place. You must always be aware of case. If JavaScript had an option explicit-like setting like VB does (disallowing variable declarations without the var keyword), we’d be protected against such boneheaded, but certainly possible, errors.

While there isn’t anything built into JavaScript to help you avoid these errors, there is a superb online JavaScript utility called JSLint you can use to screen your code for such errors. JSLint investigates your JavaScript and reports lots of information about it. One of the things it reports is the sloppy use of variables as shown in Figure 13. For JavaScript work of any real merit, the use of JSLint is highly recommended.

The lesson learned: take great care with your JavaScript variable naming and watch your case.

Batch printing Word documents

I recently worked on a project where one of the tasks needing to be done was printing previously-created Word documents in batch, from a Windows fat-client program. The specification required that the user not see the Word doc. The class below provides a PrintDocument() method that automates Word to open the document and print it, without making Word document visible.

Windows only!

Do note that this code is only for use in a fat client environment. Word automation won’t work in multi-threaded, service-side environments such as ASP.NET. Don’t attempt to use this code in a Web app. Although the code presented here doesn’t show the Word document, Word does indeed get loaded (albeit invisibly) to print the document.

My general language of choice is C#, but I’ve learned that its much easier to code Office automation tasks with VB.NET than it is any other .NET language. My friends from England would call this “Horses for Courses.” The upcoming C# 4.0 enhancements may (hopefully!) change this, but until then, I’m going to stick with using VB.NET for Office automation.

Figure 1. A helper class to print a Word document
  1Imports System.IO 
  2Imports System.Windows.Forms 
  3Imports System.Drawing
  4
  5Namespace rp.OfficeHelpers
  6
  7    Public Enum PrintStatus
  8        Success
  9        FileNotFound
 10        FailedToOpenDocument
 11        FailedToPrintDocument
 12    End Enum
 13
 14    Public Class Word
 15
 16        Public Shared Function PrintDocument( DocumentName As String, _  
 17                                              PrinterName As String ) As PrintStatus 
 18
 19            PrintDocument( DocumentName, PrinterName, 1 ) 
 20        End Function
 21
 22        Public Shared Function PrintDocument( DocumentName As String, _  
 23                                              PrinterName As String, _ 
 24                                              NumberOfCopies As Integer ) As PrintStatus 
 25
 26            Dim wordApp As Microsoft.Office.Interop.Word.Application = _ 
 27                           new Microsoft.Office.Interop.Word.Application()
 28            Dim wordDoc As Microsoft.Office.Interop.Word.Document
 29            Dim CurrentPrinter As String = wordApp.ActivePrinter
 30
 31            If ( Not File.Exists( DocumentName ) )
 32                Return PrintStatus.FileNotFound    
 33            End If
 34
 35            wordApp.Visible = false
 36         
 37            wordApp.ActivePrinter = PrinterName
 38
 39            ' Document name must be provided as an object, not a string.
 40            Try 
 41                wordDoc = wordApp.Documents.Open( CType( DocumentName, Object ) )
 42            Catch WordError as System.Exception 
 43                Return PrintStatus.FailedToOpenDocument
 44            End Try  
 45         
 46            Try 
 47                wordDoc.PrintOut( Copies := CType( NumberOfCopies, Object ), Background:= false )
 48            Catch WordError as System.Exception 
 49                Return PrintStatus.FailedToPrintDocument
 50            End Try  
 51                                                                  
 52            wordApp.ActivePrinter = CurrentPrinter
 53
 54            wordApp.Quit( SaveChanges := false )
 55
 56            Return PrintStatus.Success        
 57        End Function
 58
 59    End Class
 60
 61End Namespace

Getting a list of installed Windows printers

For printing tasks, it’s common to need to fetch the list of currently installed printers on a given PC. The Windows’ PrintDialog does display available printers—but it’s generally intended to be used in the general workflow of printing a document. The PrintDialog is also no help whatsoever for browser-hosted intranet apps where a user needs to select, and then print, to a given network printer. What I wanted was an easy way to show users available printers; and I wanted this technique to work in either Windows or browser clients.

For example, the other day I worked on a task where the requirement was to be able to batch print documents (Word and Excel mostly, but also images). In this case, the PrintDialog wasn’t much help. I wanted to provide an easy way for users to select the target printer without all of the ceremony of the PrintDialog.

To perform this task, I wrote the code shown in Figure 1. It provides two classes:

  • PrinterCommon. This class provides a GetInstalledPrintersList() method that returns an instance of a class that provides a string array of printer names and an integer value indicating which of the printers in the list is the default printer. (I named this class PrinterCommon because I intend later to add other common print tasks to it.)
  • InstalledPrinters. This class is the result type returned from from GetInstalledPrinterList(). While I typically don’t like to put more than one class in a source member, given the tight coupling between PrinterCommon and InstalledPrinters, that seemed like an OK shortcut for this simple task.
Figure 1. Code to get a list of installed printers.
  1using System;
  2using System.Drawing.Printing;
  3
  4namespace rp
  5{
  6    /// <summary>
  7    /// Common print and printer tasks.
  8    /// </summary>
  9    internal class PrinterCommon
 10    {
 11        /// <summary>
 12        /// Get the list of installed printers.
 13        /// </summary>
 14        /// <returns>An instance of InstalledPrinters.</returns>
 15        public static InstalledPrinters GetInstalledPrinterList()
 16        {
 17            // Get default printer name.
 18            string currentPrinter = new PrinterSettings().PrinterName;
 19
 20            // Declare a string array to store the list of installed printers.
 21            var installedPrinters =
 22                new string[ PrinterSettings.InstalledPrinters.Count ];
 23
 24            // Copy the list of installed printers into the installedPrinters
 25            // array (starting at element zero).
 26            PrinterSettings.InstalledPrinters.CopyTo( installedPrinters, 0 );
 27
 28            // Get index of default printer.
 29            int i = Array.IndexOf( installedPrinters, currentPrinter );
 30
 31            // Return with a new instance of InstalledPrinters.
 32            return new InstalledPrinters() { PrinterNames = installedPrinters, 
 33                                             SelectedPrinterIndex = i };
 34        }
 35    }
 36
 37    /// <summary>
 38    /// A simple class used to list the installed printers
 39    /// and the index in that list of the default printer.
 40    /// </summary>
 41    class InstalledPrinters
 42    {
 43        public string[] PrinterNames { get; set; }
 44        public int SelectedPrinterIndex { get; set; }
 45    }
 46}

The code to use the GetInstalledPrinterList() is very easy; it is shown below in Figure 2. Note that the Item’s AddRange() method is used to assign the array of printer names to the ComboBox (which also works with ListBox). While the code in Figure 2 is specific to Windows, a simple variation of it works just fine with browser-based applications.

Figure 2. Using the GetInstalledPrinterList() method
  1rp.InstalledPrinters pl = rp.PrinterCommon.GetInstalledPrinterList();
  2
  3comboBox1.Items.AddRange( pl.PrinterNames );
  4comboBox1.SelectedIndex = pl.SelectedPrinterIndex;

Great resources to help you learn JavaScript

Here are some of my favorite and most frequently-used resources for learning JavaScript. I’ll update this list on a recurring basis.

Resource Description
JavaScript Tutorial
JavaScript Tutorial
JavaScript Reference Series
JavaScript Reference
JavaScript Closures
There are more online references and tutorials for JavaScript on the Web than there are naked pictures of Paris Hilton. To find them (the JavaScript stuff, you perv), you only need a firm grasp of Google! Listed to the left are some of my favorites. Most of them speak for themselves. The first one, though, deserves special mention. Most readers will be familiar with it already, but for those of you who aren’t, be sure to bookmark W3Schools. While it has great JavaScript info, it also has loads of other great Web development info.
JSLint JSLint is an online JavaScript code quality tool. It investigates the JavaScript you paste into it and reports tons of information about it.  Perhaps the most important thing it reports is sloppy use of undefined variables. JSLint is the work of JavaScript Jedi Douglas Crockford. He promises that JSLint will hurt your feelings!
ECMAScript Language Specification While no one but the official language spec committee calls JavaScript “ECMAScript,” this 188 page manual (it’s a PDF) is quite handy. It’s dry, and probably tells you a little more than you really want to know, but it its value, especially for free, as a JavaScript reference is superb.
FireBug JavaScript debugger for FireFox
IE8 debugger
Opera Dragonfly debugger
The combination of FireFox and Firebug has probably done more for learning and exploiting JavaScript than all of the JavaScript books ever written. The synergy of the two actually make writing JavaScript fun—and that’s an elusive word association. Both IE8 and Opera also now both offer intrinsic JavaScript debuggers that, while not as good as FireBug, are quite a step forward for these two browsers.
jQuery This isn’t just a superb JavaScript library–it’s a JavaScript game changer. Using it will improve, vastly for the better, the way you write JavaScript. The decision tree for determining if you should use jQuery is very simple: do you write JavaScript? If yes, you need jQuery.
JavaScript style guide JavaScript coding conventions per Crockford.
Douglas Crockford JavaScript videos Douglas Crockford has made several videos about JavaScript and they are very enlightening. There is a series on JavaScript and then one on advanced JavaScript. Also, do an advanced Google search for Crockford’s JavaScript PowerPoints—they are terrific.

On a slightly related note, to hear ten or so of the most awkward DotNetRocks minutes ever, give a listen to Carl and Richard welcoming Douglas to their show #422. Listen for a couple of minutes about 9 minutes into the Podcast. Richard’s uncomfortable laughter will make you cringe and Carl trying to explain away his Wierd Al reference draws dead air. I’m generally a big fan of DNR, but this interview had me wishing for a flat tire on my way to work just for an excuse to stop listening. An opportunity to interview a JavaScript god was completely pissed away. To Carl and Richard’s credit, Crockford does come across as a bit of a mooncat. He remains pretty much disengaged throughout the entire interview.
headfirstjavascript This is a good JavaScript book for beginners. The Head First books flirt with being just a little too pretentious (they are a little like a Dummies book gone nearly right) but overall the info in the book overcomes some of its “mom made me a JavaScript scrapbook” impact.
javascript_the_good_parts One more Crockford reference and I swear I’m done with him (for now). JavaScript: The Good Parts is a very good book on intermediate/advanced JavaScript. If you’re new to JavaScript, don’t make this your first book. But once you think you’ve got a a handle on JavaScript, this book will definitely ramp up your JavaScript knowledge more than one level.

Expand virtual PC disk space—painlessly

I am rapidly becoming quite addicted to the virtues of using virtual PCs. It’s great having lots of virtual images with which to test and develop. Need to test IE 7 but you’re running IE 8? Make an IE 7 testing image!

However I just bumped into a problem with virtual image: out of the box, it’s a hassle to add to an image’s available disk space. However, vmToolkit has a free utility called VHD Resizer that makes this a painless process.

I was going to write a post about how to use VHD Resizer, but Pieter Mol has beaten me to it. His instructions are superb. With VHD Resizer and Pieter’s great help, resizing a virtual partition is now really very simple.

Note that I used VHD Resizer with Windows XP. Check with vmToolkit as to the latest news about Vista compatibility.