July 2008 - Posts

Final Two Master Page Tutorials Published
31 July 08 04:50 PM | Scott Mitchell

The final two tutorials (#9 and #10) of my Master Pages Tutorial series are now available on www.asp.net. These tutorials explore two advanced master page scenarios:

  • Specifying the Master Page Programmatically [VB | C#] - in most cases a content page's master page is specified statically through the MasterPageFile attribute in the @Page directive. However, it is possible to dynamically set a content page's master page, as this tutorial shows.
  • Nested Master Pages [VB | C#] - much like how a content pages can bind to a master page, it is possible for master pages to bind to other master pages. Such nested master pages are quite useful in scenarios where there is an overarching look and feel to a site, but various portions of the site require a more customized and unique template. With nested master pages you can define the global common layout in a top-level master page and then use child master pages to create more specialized layouts for particular sections of the site.

Like my past tutorials, these tutorials are all available in C# and VB versions, include a complete working source code download, and are available to download as PDF, as well.

Enjoy! - http://asp.net/learn/master-pages/

Filed under:
August's Toolbox Column Online
29 July 08 12:16 PM | Scott Mitchell

My Toolbox column in the August 2008 issue of MSDN Magazine is avaiable online. The July issue examines:

  • FileHelpers - .NET includes XML serialization capabilities, which makes it easy to load an XML file into a collection of objects and to save object state back out to an XML file. If you need similar functionality for delimited or fixed-length text files (like CSV files), check out FileHelpers, an open-source .NET library created by Marcos Meli that provides such serialization capabilities.
  • Blogs of Note - K. Scott Allen - a great blogger with in-depth and timely posts on ASP.NET, LINQ, ASP.NET MVC, and project management.
  • YSlow for Firebug - Firebug is a free Firefox extension that is a must-have for all web developers. It captures many important metrics and allows developers to dynamically adjust the page's markup, CSS rules, and to debug JavaScript, all from the browser! YSlow for Firebug is an add-on to Firebug that provides a bevy of performance metrics and targeted guidelines on how to improve a page's response time.

For The Bookshelf section I reviewed Accelerated VB 2008, by Guy Fouche and Trey Nash. An excerpt from the review follows:

As a freelance developer and consultant, I work with clients who have existing apps but need help in adding new features. Some applications are written in C#, others in Visual Basic, so I need to have a mastery of both languages. Visual Basic is easy to pick up; its prose-like syntax and straightforward semantics have helped make it one of the most popular programming languages in the world. But there's a wide gulf between knowing Visual Basic and mastering it. To help bolster my Visual Basic skills, I picked up Accelerated VB 2008 (Apress, 2008) by Guy Fouché and Trey Nash. This book dispenses with the typical page-filling content found in most computer trade books and replaces it with distilled information and code examples that get right to the point. Because of this terse style, however, Accelerated VB 2008 is not for beginners who are interested in learning Visual Basic, but it's ideal for intermediate developers who are either looking to bolster their understanding of Visual Basic or who are in need of a good desk reference.

Enjoy! - http://msdn.microsoft.com/en-us/magazine/cc721607.aspx

As always, if you have any suggestions for products or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.

Filed under:
Losing Tab and Esc Key Functionality in Microsoft Virtual PC 2007
26 July 08 10:04 PM | Scott Mitchell

I've been using Microsoft Virtual PC product for many years, posting separate VPCs for each client's work and for test beds for installing beta software or trying out products for my Toolbox column. A couple of months ago I started noticing that when in a VPC the Tab and Esc keys were being ignored. For example, when I would use Alt+Tab from within a VPC I would be toggling through the applications in the host environment. Likewise, if I hit Ctrl+Esc from within a VPC it would display the Start menu options in the host environment. Because I try to use the mouse as infrequently as possible and stick to keyboard shortcuts, having a nonfunctional Tab key seriously hindered by productivity. From Alt+Tab to moving from one form field to the next to inventing code, it's amazing how frequently I use the Tab key.

My initial assumption was that there was some problem with Virtual PC. I found information noting such problems when using UK keyboards, but nothing specific to my problem. My research revealed that a general rule of thumb was to check for programs in the host environment that might be capturing keystrokes and thereby "stealing" the keystrokes from the VPC. My approach was rather ham-fisted, but what I did was the following: I launched task manager and started killing off processes one at a time. After each process was killed, I would go over to the VPC and see if it now recognized the Tab and Esc keys.

The culprit ended up being FogCreekCopilotHelper.exe. Copilot is a desktop sharing tool from Fog Creek Software that I use now and then when providing telephone-based consulting services. This process is supposed to shut down automatically when the Copilot software closes. However, sometimes it does not cleanly die off; instead, it lingers around and seems to swallow up the Tab and Esc keys in Virtual PC.

I first detected that FogCreekCopilotHelper.exe was the source of my problems several weeks ago, but I held off posting a blog entry because I wanted to observe how exactly this problem arose. I've had several sessions with Copilot where the FogCreekCopilotHelper.exe process shutdown cleanly and did not interfere with my Virtual PC experience. In the times when it has caused trouble I noticed that mid-way during the Copilot session the Tab and Esc keys stopped working in Copilot! The same behavior I noted in Virtual PC after the fact. And, sure enough, when Copilot loses the Tab and Esc keys the FogCreekCopilotHelper.exe process does not cleanly die, but rather sticks around and steals the Tab and Esc keys from Virtual PC.

Long story short, if you lose functionality for certain keys in Virtual PC first look for the FogCreekCopilotHelper.exe process and kill it if it's floating around. If you do not use Copilot (or if this process is not present) then start to systematically kill off processes until you find the troublemaker. This approach of methodically killing processes is not very elegant, but can help detect the problem assuming you do not inadvertently kill essential processes during the genocide.

Filed under:
Email Verification for New Accounts via ASP.NET's Membership Framework
25 July 08 08:54 PM | Scott Mitchell

In my last blog entry, The CreateUserWizard and Validation ErrorMessages, reader Andrei Rinea commented:

I wish the whole Membership set of controls would be replaced with better ones. Very often I need to have an authentication/authorization mechanism that doesn't need a username but an e-mail. I need email verification and in case the user loses the password he/she should be able to recover it without knowing (a) username.

This scenario is possible, but requires some customizations of the Membership controls. For instance, you can configure Membership so that an Email is not required, and then customize the CreateUserWizard control so that it uses the text “E-mail:” in place of “Username:” (thereby storing the user's e-mail address as their username.

The CreateUserWizard control can also be customized to require that user's verify their email address before being able to log in. See these two articles for more information and to download a complete, working example:

Personally, I quite like the existing Membership controls. They provide a suitable out-of-the-box implementation that allows one to get started without having to write a lick of code, yet are highly customizable through properties, templates, and events, allowing for virtually unlimited scearios and workflows. And if a particular control doesn't cut the mustard you can always create your own UI that uses the Membership framework behind the scenes (via the Membership class).

Filed under:
The CreateUserWizard and Validation ErrorMessages
24 July 08 10:41 AM | Scott Mitchell

The CreateUserWizard control introduced in ASP.NET 2.0 makes it easy to create a new user account on a website that uses the Membership framework. (See my Creating User Accounts tutorial for more information on using this control.) Out of the box, the CreateUserWizard control offers a fully functional interface for creating new user accounts. You don't have to write a lick of code or declarative markup. Instead, just set a few properties and you're off and running.

Teach Yourself ASP.NET 3.5 in 24 Hours reader Jason L. e-mailed me recently with an interesting observation about the behavior of the CreateUserWizard's validation functionality. The CreateUserWizard control's default user interface includes validation controls for the various input fields. For example, there are RequiredFieldValidator controls to ensure that the visitor enters values for the username, password, e-mail, and so on. The ErrorMessage property values of these validation controls can be customized via the CreateUserWizard control's properties, such as UserNameRequiredErrorMessage and EmailRequiredErrorMessage.
Regardless of the values you use for the ErrorMessage properties, the RequiredFieldValidator controls have their Text properties values all set to the same thing, an asterisk (*). When a validation control is both its Text and ErrorMessage properties assigned, the value of the Text property is displayed in the location of the validation control in the event of invalid data; the value of the ErrorMessage property is displayed in a ValidationSummary control (if one exists on the page).

For whatever reason, the default CreateUserWizard control user interface does not include a ValidationSummary control. Consequently, the values specified in the UserNameRequiredErrorMessage and EmailRequiredErrorMessage properties (among the other ErrorMessage-related properties) are never displayed. (Granted, these property values are assigned to the tool tip of the validation controls, meaning that a user can hover her mouse over the asterisk and see a more detailed ErrorMessage description.) Interestingly, the CreateUserWizard's default interface does show a message if the password and confirmation password do not match. This behavior is due to the fact that the default interface includes a CompareValidator control that does not have its Text property set. Rather, only its ErrorMessage property is assigned (and this can be customized via the CreateUserWizard control's ConfirmPasswordCompareErrorMessage property).

So how do you get the ErrorMessage properties for the RequiredFieldValidator controls to display when using the default interface? One way is to add your own ValidationSummary control to the page. If you do this piece sure to set a ValidationSummary control's ValidationGroup property to the ID of the CreateUserWizard control. In other words, if the CreateUserWizard is named MyCreateUserWizard then set the ValidationSummary control's ValidationGroup property to "MyCreateUserWizard". However, if the user enters a password that does not match with the confirm password the corresponding error message will be displayed twice: once by the CompareValidator and again in the ValidationSummary control.

The only sure fire way to get the validation messages to display as expected is to customize the user interface created by the CreateUserWizard. The good news is that it is very easy to convert the CreateUserWizard into a template, at which point you have virtually unlimited customization capabilities regarding the validation logic and display. For more information on customizing the CreateUserWizard control's user interface, check out Customizing the CreateUserWizard Control and Storing Additional User Information.

Filed under:
Installing Dragon Naturally Speaking (DNS) on Vista / Windows Server 2008 64-Bit
19 July 08 08:11 PM | Scott Mitchell

Earlier this week I bought Dragon NaturallySpeaking version 9.5. It took me close to an hour to get the software install and configured properly on my system, primarily because I am using a 64-bit operating system. Dragon NaturallySpeaking does not support the 64-bit versions of Windows Vista or Windows Server 2008, but there is a workaround that allows you to install on a 64-bit operating system. Another challenge is that Dragon NaturallySpeaking has trouble with certain onboard sound cards. This blog entry highlights the challenges I faced when installing Dragon NaturallySpeaking provides workarounds.

If you try to install Dragon NaturallySpeaking a 64-bit operating system you will be stopped by the installer. After a bit of searching, I found this helpful post by VelvetPoodle:

The problem is the installer bundled with the software. This has code preventing it from being run on 64 bit vista. This can be edited using the free application orca.exe which is part of the much larger Microsoft core platform SDK. If you only want the application orca.exe do a google search for it. Make sure you get the 64 bit version though… Alternatively get it from here:
http://blogs.msdn.com/astebner/archive/2004/07/12/180792.aspx.

1. Copy the entire contents of the DVD to a folder on your computer
2. Make a backup of the file Dragon Naturally Speaking 9.msi
3. Install Orca and open Dragon Naturally Speaking 9.msi from the installer directory
4. To the left under tables, scroll down and click on the “launch Conditions”. The error conditions will appear to the right.
5. Select the Condition “Not VersionNT64”
6. Right-Click and select “Cut Row(s)”
7. Save the edited "Dragon Naturally Speaking 9.msi"
8. Install as normal


While this method will certainly get Dragon NaturallySpeaking to install and work on 64-bit operating system, one thing to keep in mind is that NaturallySpeaking will not respond or respond very slowly when dictating in 64-bit applications. For example, if I try to dictate in Internet Explorer, Dragon NaturallySpeaking virtually hangs. Supposedly, the next version of Dragon NaturallySpeaking will support 64 bit operating systems.

After successfully installing Dragon NaturallySpeaking on my computer, the application started and I was greeted with a warning: "Audio Setup Wizard cannot find the sound system." This error threw me for a loop because my computer certainly does have a sound system - I can hear music coming from my speakers and am able to record voice from a microphone. Some online sleuthing turned up message board posts from other Dragon NaturallySpeaking users who encountered similar problems with onboard sound card systems not supported by Dragon NaturallySpeaking. My computer has an onboard RealTek sound card; other users with the same configuration had reported similar errors.

In the same post where VelvetPoodle shared how to install Dragon NaturallySpeaking 64-bit operating system, another poster named webbediva shared a workaround for the audio wizard problem that worked for me:

To get past the audio wizard error:
With Naturally Speaking bar running, right-click on the audio.exe file using Windows Explorer in Program Files\Nuance\NaturallySpeaking9\Program. Under "Properties" click "Compatibility" tab and select "XP". Double-click to run.

To summarize, with Dragon NaturallySpeaking running need to set the compatibility level of the audio wizard program to be compatible with Windows XP and run this program from Windows Explorer. With this step out of the way, Dragon NaturallySpeaking (finally) worked! It took a bit of research and effort to get Dragon NaturallySpeaking properly installed and configured on my machine, but I haven't had any issues since (except for slow or nonexistent response times for 64 bit applications).

Read the post with the two workarounds: http://forums.cnet.com/5208-6035_102-0.html?forumID=44&threadID=280578&messageID=2744514

Filed under:
Using Dragon NaturallySpeaking
19 July 08 07:49 PM | Scott Mitchell

Earlier this week I broke my right hand playing basketball. I currently have a splint on, which renders my right hand useless. I can wiggle the tips of my fingers but I lack the control to use a mouse or type with this lame hand. I'm getting proficient typing with my left hand, but it is still significantly slower than typing with both. For instance, with both hands I can type in the neighborhood of 100-120 words per minute. With just my left, I type a shade under 40 words per minute, and even slower when keying in typical code syntax with its mix of punctuation and case changes. (Thank God for IntelliSense!)

On Thursday I bought Dragon NaturallySpeaking from my local Fry's. NaturallySpeaking a popular voice recognition software package. I opted for the Standard Edition, which set me back $100. Not having had experience with voice recognition software in the past, I was a bit skeptical at how accurate such software could be. I knew it would not suffice for coding, but my hope was that it would make a good substitute for writing e-mails and authoring articles. So far, I have been pleasantly surprised with the accuracy and ease of use. The marketing literature claims over 99% accuracy. I have no clue how accurate it truly is, but keep in mind that even with 99% accuracy that still means that there will be one error every 100 words you utter. And if you are as verbose as I am, 100 words comes very quickly. Every couple of sentences there are one or two corrections I have to go back and make with my keyboard or voice commands.

Speaking of using voice recognition software for coding, I did try writing a little bit of code with my voice. My only foray into this was with a simple "Hello, world" example. What I intended to write was:

Response.Write("Hello, world!");

I said: "response", "period", "write", "open parenthesis", "open quote", "cap hello", "comma", "world", "exclamation point", "close parenthesis", "semi-colon". What I got was:

Response. Right ("Hello, world!");

Close, but no cigar. One of the main problems is that the software injects spaces where it thinks they are needed when speaking English, not when being parsed by a programming language. Moreover, it has trouble with homonyms at times. Note how it chose to use "Right" instead of "write".

In addition to writing text with your voice you can also use Dragon naturally speaking to issue a computer command such as copy, paste, formatting, and other common commands. The copy and paste features are quite useful, but what can be frustrating is when you say a word to type that to also maps to a command, such as "print" or "close".

All in all, I'd recommend using Dragon NaturallySpeaking or some other voice recognition software for people with some sort of typing impairment who spend much of their day sitting in front of a computer responding to e-mails or writing articles or other documents. It takes some getting used to, and there certainly are errors that you have to put up with, but it is a lot more efficient than typing with one hand and allows you to keep that one good hand on the mouse most of the time.

One warning regarding Dragon NaturallySpeaking: the software does not natively support 64-bit operating systems (although there is a workaround), and certain onboard sound cards are not recognized by the software without a bit of a workaround. I'll discuss some of the challenges I had installing Dragon NaturallySpeaking, and the steps I took to surmount those challenges in: Installing Dragon Naturally Speaking (DNS) on Vista / Windows Server 2008 64-Bit.

Filed under:
Suggestions for a broken hand?
15 July 08 10:27 PM | Scott Mitchell

i broke my right hand playing basketball tonight. splint on, prognosis is 4-6 weeks in a cast that will likely be high enough on my hand to greatly reduce finger mobility. as it stands now, i can only type w/my left hand and have moved the mouse to my left and switched the right and left buttons, but typing w/ one hand is excruciatingly slow and error-prone. i'm sure practice makes perfect but right now it is frustratingly slooooooooooow.

maybe best to ditch natural keyboard for a 'normal' one as the keys on the natural are so farther apart.

i wonder if there's a key mapping that's ideal for left handed only typing. like dvorak for lefties

any tips on how to get by on a computer with a busted hand?

thanks in advance

Filed under:
Three New Master Page Tutorials Published
13 July 08 11:21 AM | Scott Mitchell

Tutorials #6, #7, and #8 in my Master Pages Tutorial series on www.asp.net have been published. These tutorials examine the interaction between the master page and its content pages:

  • Interacting with the Master Page from the Content Page [VB | C#] - there may be times when the content page needs to programmatically interact with its master page. This tutorial looks at common scenarios where this type of interaction is needed and shows various techniques for accomplishing this type of interaction.
  • Interacting with the Content Page from the Master Page [VB | C#] - the most typical type of master page and content page interaction originates from the content page. However, there may be times when the master page needs to signal the content page to take some action. This tutorial looks at such scenarios and shows a technique for this style of interaction.
  • Master Pages and ASP.NET AJAX [VB | C#] - web pages that use Microsoft's ASP.NET AJAX framework must include the ScriptManager control on the page. This control can be placed in the master page. This tutorial looks at the effects of adding the ScriptManager to the master page. It also walks through a complete AJAX example and shows how to use the ScriptManagerProxy control to add custom script references in a content page.

Like my past tutorials, these tutorials are all available in C# and VB versions, include a complete working source code download, and are available to download as PDF, as well.

There are two remaining tutorials in this series that should be published by the end of this month. The two remaining tutorials look at specifying a content page's master page at runtime and using nested master pages.

Enjoy! - http://asp.net/learn/master-pages/

Filed under:
Two Monitors Are Better Than One, But Are Three Better Than Two?
10 July 08 08:52 PM | Scott Mitchell | 1 comment(s)

In my ten year software developer career I've only worked for two companies, and both job experienced pre-dated the 21st century and my graduation from college. At both jobs, I only had one monitor, albeit a rather large one for the time (21” at both companies, if I remember correctly). After graduating, I decided to strike out on my own as a freelance writer, consultant, and trainer, and haven't looked back since. Not knowing any better, I used a solitary monitor until April 2006, when I finally updated to a dual monitor setup. I bought a second video card, picked up the same brand/model of monitor, and graduated into the 21st century. (What prompted me to upgrade to two monitors was, primarily, stories of enhanced productivity from my wife, who was, at the time, working for a company that supplied dual monitors to all its devs. Bill Gates is also a big fan of multiple monitors.)

Two monitors are superior to one for many development- and writing-related tasks. Having Visual Studio in one window and the browser in another and being able to see both simultaneously nets huge performance gains. Likewise, when writing, having Microsoft Word up on one screen and code or a browser is a great time-saver. Today I have a hard time functioning when at a client's site and am reduced to using a single monitor setup. But just how much better are two monitors than one?

Anyone who tells you that they are twice as productive with two monitors than with one is probably over exaggerating. For development- and writing-related activities I find that two monitors allows me to accomplish somewhere on the order of 25%-50% more work in a given unit time. That's a wet finger in the air estimate, but there have been more formal studies. Microsoft Research reports that multiple monitors “can increase your productivity by 9 to 50 percent.” A small study performed by Darrell Norton shows productivity as lines of code per day increased by 10% and defect levels decreased by 26% (hat tip Jeff Atwood). What doesn't get measured in these studies is the increased quality of worklife. Even if the actual productivity gain is nominal, having a second monitor feels better. It lets you see more screen real estate at a given point in time. It lets you compare two documents side by side rather than incessantly Alt-Tabbing.

A couple of months ago I upgraded to a new computer. The only components I salvaged from my old computer was a 350 GB S/ATA hard drive and my two monitors; everything else was bought new. While investigating parts and formulating my shopping list I debated whether to upgrade to three monitors. Jeff Atwood is a big fan of three monitors:

As good as two monitors is, three monitors is even better. With three monitors, there's a "center" to focus on. And 50% more display area. While there's certainly a point of diminishing returns for additional monitors, I think three is the sweet spot. Even Edward Tufte, in the class I recently attended, explicitly mentioned multiple monitors. I don't care how large a single display can be; you can never have enough desktop space.

I didn't think a third monitor would make me any less efficient, but I questioned as to whether the improvements in efficiency (or quality of worklife) were as grandiose as Jeff made them out to be. In the end I decided to give it a whirl. I bought two GeForce 8600 GT video cards for the new system. These have dual DVI outputs meaning that I could upgrade to a fourth monitor if I were so inclined. I kept the two monitors from my previous setup - 17 inch monitors from Sharp - and bought a new Samsung SyncMaster 2053 BW monitor, which is a wide screen that has about the same visible height at the Sharps, but is about 33% wider. The two Sharps run at 1280x1024, the Samsung at 1680x1050.

I've been using the three monitor setup for a couple of months now and regret to say that I have not seen the same productivity benefits or improvement of worklife that Jeff espouses or that I enjoyed when going from one monitor to two. For certain tasks I am more productive with three monitors than two, a prime example being if I need to review a client's email while bug bashing. I can have the email open that explains the error in one window, Visual Studio in another, and the web application running in the third. However, for most other activities the third monitor does not add too much value. Consequently, it's not uncommon for one of the three to sit unused for long stretches of time.

Three monitors also have some detriments that weren't present with two. Because of the width of the three monitors, I frequenty tilt my neck to see the side monitors; with two monitors I could see both with when looking straight ahead by just turning my eyes, but not with three. The net result is that if I spend an inordinate amount of time focusing on one of the side monitors my neck becomes a bit stiff. To combat this I try to make myself swivel my chair when I start looking at a side monitor, but it's second nature for me to turn my head and I don't realize that I'm not swiveling until my neck starts to bother me.

In the end, three monitors are better than two, just like I imagine four would be better than three, but the returns on multiple monitors quickly diminish as the number of monitors grow (at least for my line of work and from my personal work habits). Knowing what I know now, if I had to choose between a third monitor and some other upgrade (perhaps a super high-end hard drive or a high-end office chair), I'd stick with two monitors and take my luck with what's behind Door Number 1.

Filed under:
Speeding Up FireFox When Using the ASP.NET Development Server from Localhost
09 July 08 01:54 PM | Scott Mitchell | 1 comment(s)

I have long used FireFox as my default browser for surfing the web, but I typically test my ASP.NET pages on Internet Explorer for a couple of reasons:

  • Some of the larger software projects I work on are developing intranet applications, where all users' browsers are fixed (IE 6 for one client, IE 7 for another).
  • For book and article and tutorial screen shots I typically use IE as my browser of choice because IE is still, after all, the most used browser.
  • Until Visual Studio 2008, Visual Studio used IE as the browser when debugging an ASP.NET application (even if FF was setup as the default). Because all of my clients are still on ASP.NET 1.x or 2.0, I don't use VS 2008 too often.

However, I have recently been working on some AJAX material and have been using VS 2008 more frequently. Visual Studio 2008 kindly launches my default browser (Firefox) when I debug my web application. The problem was I noticed that Firefox was loading pages very slowly. I'd visit a site through localhost (via the ASP.NET Development Web Server) and pages would take several seconds to load.

To help analyze the problem I used the excellent Firefox extension Firebug (which I reviewed in the March 2008 issue of my Toolbox column). Firebug will show you the total number of network resources downloaded when visiting a page, along with the time it took to download each.

Firebug

Each resource - from the 4KB HTML fiel to the 7KB JPG file, was taking close to a FULL second to retrieve! When requesting this same page from a remote, production web server, download times were 5 to 10 times faster per resource. What was going on here?

I next opened Internet Explorer - the same pages loaded instantaneously. I fired up Fiddler, an excellent HTTP Debugger for IE, and noted that the resources were being downloaded in 0.02 seconds, nearly 500 times faster than from Firefox. By now I was seriously stumped. I then did what I should have done from the getgo - I searched the web. Duh!

Turns out that there is a known issue with Firefox's IPv6 support and the ASP.NET Web Development Server that introduces these lengthy delays. To quote from the Mozilla Wiki:

IPv6 was designed in part to solve the problem IPv4 will soon be facing: the exhaustion of all possible IP addresses. Mozilla implemented IPv6 support in early 2000, but that support did not receive widespread testing until recently as IPv6-capable OSs and network software/equipment became more common. One particular bug that has appeared exists not in Mozilla, but in IPv6-capable DNS servers: an IPv4 address may be returned when an IPv6 address is requested. It is possible for Mozilla to recover from this misinformation, but a significant delay is introduced.

...

Two approaches were taken to work around these bugs: first, a preference to globally disable IPv6-based DNS lookups browser-wide (this preference [network.dns.disableIPv6]), and a blacklist of domains which should never have IPv6-based DNS lookups performed (network.dns.ipv4OnlyDomains).

Consequently, to fix this problem of slow response times when visiting localhost using Firefox, either set the network.dns.diableIPv6 configuration property to true or set the network.dns.ipv4OnlyDomains configuration property to “localhost”. My search led me to many pages around the Web suggested that you set the nework.dns.disableIPv6 property to true, but this would disable IPv6 support for all sites visited by the browser (at least according to the Wiki documentation). Therefore I set the network.dns.ipv4OnlyDomains property to “localhost”.

To set these properties, fire up Firefox and type about:config in the address bar. Next, locate the appropriate setting and change its value to the desired one. With that small change the debug-time experience in Firefox is greatly enhanced. And make no mistake, Firefox's rich library of extensions make it a great browser for web development. (I'll share some of my favorite Firefox web development extensions in a future blog post.)

Lesson for the day: If you bump up to a problem, search for a solution online first. If your search is fruitless then take the time to investigate it further, otherwise you may spend 15 minutes troubleshooting a problem that is already well-known and has a simple solution.

Filed under:
July's Toolbox Column Online
04 July 08 11:43 AM | Scott Mitchell

My Toolbox column in the July 2008 issue of MSDN Magazine is avaiable online. The July issue examines:

  • ScrewTurn Wiki - a wiki is a web application whose content is maintained by its users. Adding a wiki to your site is remarkably easy with ScrewTurn Wiki, a free, open-source ASP.NET wiki application (written in C#). By default, ScrewTurn uses the file system to store its content, which makes adding it to a site as easy as copying a few files up to the web server.
  • Blogs of Note - Scott Hanselman - Scott is one of my favorite technical bloggers. His The Weekly Source Code entries and annually-updated Ultimate Developer and Power Users Tool List are something every .NET developer should check out.
  • SnagIt - SnagIt is one of the best screen capture utilities available. With a simple keyboard shortcut or the click of a mouse it can capture a particular window, a specific region of the screen, or the entire contents of a scrollable window. What's more, you can very easily touch up the image, adding text, highlighting, callouts, and so on, and then save it as an image, Flash file, or PDF, or send it via email, IM, over FTP, or to a Microsoft Office document.

For The Bookshelf section I reviewed LINQ in Action, by Fabrice Marguerie, Steve Eichert, and Jim Wooley. An excerpt from the review follows:

LINQ is made possible thanks to a number of new language enhancements and several new namespaces and classes in the .NET Framework. Because of the breadth and depth of the topic, to really learn LINQ you'll need more than a few online articles. One LINQ book, which explains the various facets through rich examples that build on previous chapters, is LINQ in Action. ... What I liked best about LINQ in Action is how the authors start each new section with straightforward, easy-to-follow examples that highlight the most important features. Next, they pull back the curtains and show how the LINQ queries and features are actually implemented.

Enjoy! - http://msdn.microsoft.com/en-us/magazine/cc700339.aspx

As always, if you have any suggestions for products or books to review for the Toolbox column, please send them to toolsmm@microsoft.com.

Filed under:
For Some Probability Problems, Seeing Can Be Believing
01 July 08 02:54 PM | Scott Mitchell

A few days back I was browsing some of Jeff Atwood's older blog entries and stumbled across one titled, The Danger of Naivete. In it, Jeff discusses an algorithm for randomizing an array that, while simple and seemingly intuitive, is subtlely incorrect in that it over-weights certain permutations and under-weights others. The naive algorithm enumerates each element in the array and swaps it with a randomly selected position in the array. Here's the naive algorithm implemented in C# code.

Random rnd = new Random();

for (int i = 0; i < deck.Length; i++)
{
// Set swapWithPos a random position such that 0 <= swapWithPos < deck.Length
int swapWithPos = rnd.Next(deck.Length);

// Swap the value at the "current" position (i) with value at swapWithPos
int tmp = deck[i];
deck[i] = deck[swapWithPos];
deck[swapWithPos] = tmp;
}

While reading Jeff's blog entry, my stomach sank because I knew that I had authored an article on randomly ordering an array on 4Guys back in the day (circa 2000). I was certain that I had implemented the naive and incorrect algorithm. Upon digging up the old article - Randomly Reordering an Array - I realized that I had used the naive algorithm. Urp. At least in describing my implementation I labeled the algorithm a “quick and dirty way to [randomly reorder an array].”

Of course there are algorithms that randomly reorder an array with an even distribution of permutations. What's interesting is that the simplest such correct algorithm - the Knuth-Fisher-Yates shuffle - is very similar to the naive algorithm. Depending on your programming language of choice, you can likely morph the incorrect naive algorithm into the Knuth-Fisher-Yates algorithm by changing less than 10 characters in the code file.

Rather than blindly change the old article, I wanted to better understand why the naive algorithm doesn't work. Despite Jeff's explanation of why the naive algorithm over-weights certain permutations and why this doesn't happen with the Knuth-Fisher-Yates shuffle, I still had a mental roadblock. It wasn't until I did what Jeff suggested - sit down and draw out the various possible permutations from the naive algorithm vs. the Knuth-Fisher-Yates shuffle - that things came into focus. I also find that having to explain some technology or algorithm or concept helps bolster my understanding of it, in part because any parts that I have trouble explaining force me to do further research. Therefore, this week's 4Guys article - Techniques for Randomly Reordering an Array - looks at ways for shuffling an array and highlights what's wrong with the naive approach and how other solutions account for this. Because Jeff's blog entry was the impetus for Techniques for Randomly Reordering an Array, the two are very common. However, in my article I show the probability breakdown of the naive algorithm (and analyze another approach mentioned by Jeff in his blog entry Shuffling).

In a nutshell, the naive algorithm computes n^n possible outcomes, yet there are only n! permutations available. In the case of a three element array, there are 3^3 = 3 * 3 * 3 = 27 possible outcomes from the naive algorithm yet only 3! = 3 * 2 * 1 = 6 permutations. Because 6 does not divide 27 there must be some potential outcomes that are over-weighted by the naive algorithm and others that are under-weighted. To make this point more clear, check out the following diagram. It shows the possible outcomes when shuffling a three element array whose elements initially have the values [0, 1, 2]. As you can see, the end result is that the permutations [0, 2, 1], [1, 0, 2], and [1, 2, 0] appear five times while the permutations [0, 1, 2], [2, 0, 1], and [2, 1, 0] each appear only four times.

When facing a particularly tough probabilty problem sometimes it helps to sit down and draw out the possible outcomes for the given scenarios. In doing so, things that may otherwise seem very complex boil down to a very apparent solution or explanation.

A great example of simplicity through diagraming is the Monty Hall problem, which goes like this: You are a contestant on the TV game show, Let's Make a Deal and are presented with three doors. Behind one door there is a luxury car. Behind the other two doors there is a poster of a car. The game show host asks you to pick a door. After choosing one, the game show host reveals one of the other doors that has a poster behind it and then asks you if you want to change your door choice to the other unopened door. What is the best strategy?”

The answer is that you should change the door you had selected, because there's a 2/3 probability that the door you did not select houses the luxury car. In other words, there is a 2/3 probability that the door you picked has the remaining poster. The solution seems backwards. It seems paradoxical that the door the host reveals to have a poster of a car could have any influence on your initial selection. But if you sit down and draw out the various probabilities you can see that there's there are more good outcomes if you make the switch than if you hold fast to your initial choice. The following diagram was created by Rick Block; here, instead of a poster of a car you get a goat. Same difference.

While penciling out the various outcomes of a probability problem doesn't feel very sophisticated, it can often be a quick and surefire way to better understand a problem.

More Posts

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.