February 2009 - Posts

March's Toolbox Column Now Online
26 February 09 10:00 AM | Scott Mitchell

My Toolbox column in the March 2009 issue of MSDN Magazine is available online. The March issue of MSDN Magazine has a focus on the Web and my reviews in Toolbox follow suit and include:

  • The Ajax Data Controls Project - The Ajax Data Controls (ADC) project is an ASP.NET AJAX extension that marries the ease of the server-centric development model with the performance of the client-centric development model. ADC is a collection of controls that displays data in an Ajax-enabled web page. You can add the ADC to your page like you would any other web control, and set their properties through the Properties window. However, you work with the ADC controls programmatically via JavaScript. The net result is that the ADC result in significantly less markup between partial page postbacks than the built-in Web controls in an UpdatePanel, but provide a similar page developer experience.
  • Fiddler - an HTTP traffic analyzer is a must-have tool for web developers. Such tools provide a clear picture of the low-level HTTP traffic coursing between the client and server. Moreover, such tools can be quite helpful in debugging or generating a pre-canned HTTP request (for testing server-side functionality) or response (when testing client-side functionality). My favorite HTTP traffic analyzer is Fiddler, a free tool created by Eric Lawrence. Check it out.
  • Blogs of Note:
    • Rick Strahl - Rick is an old-school FoxPro developer and ASP.NET developer who regularly shares his experiences, insights, tips, and tricks on his blog. Rick's blog posts primarily focus on Web topics, including ASP.NET, jQuery, AJAX, and Silverlight.
    • Sam Larbi - Sam pens one of my favorite blogs, My Secret Life as a Spaghetti Coder. Sam works as a jack of all trades developer, dabbling in both Web and desktop applications and languages ranging from C++ to ColdFusion to C# and ASP.NET. Along with posts about specific technologies, Sam also routinely writes about the non-technology-related aspects of being a developer, including topics like meetings, working with others, personal development, and so on.

The Bookshelf section reviewed jQuery in Action by Bear Bibeault and Yehuda Katz. An excerpt follows:

Due to JavaScript's increasing importance in Web development, several frameworks have been created. One of the most popular ones is jQuery, a free, open-source, cross-browser JavaScript framework created by John Resig. (In fact, Visual Studio 2010 will ship with the jQuery library, making it even easier for ASP.NET developers to get started with jQuery.) ... jQuery in Action (Manning, 2008) ... is a great resource for leaning the ins and outs of jQuery and for mastering its terse and flexible syntax. jQuery in Action assumes the reader is already familiar with JavaScript and wastes no time covering the basics of the language. Instead, it starts with a quick introduction to the motivation behind jQuery and jQuery fundamentals and then moves on to using jQuery to accomplish common tasks. (Some of the more advanced JavaScript concepts that are used by jQuery are covered in an appendix.)

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

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

Filed under:
Creating and Consuming Syndication Feeds in ASP.NET 3.5
23 February 09 07:21 AM | Scott Mitchell

Do you run a website that routinely publishes new content? If so, does your site offer a syndication feed? A syndication feed is an XML file that summarizes the most recently published content and is commonly used in blogs, news sites, sports sites, social networking sites, and other content producing websites to provide a machine-readable format of the latest content. For the longest time the .NET Framework did not include built-in support for syndication feeds, meaning that if you needed to generate a syndication feed or parse the syndication feed from another site you either needed to:

The good news is that syndication functionality was added to the .NET Framework version 3.5, namely with the addition of the classes in the System.ServiceModel.Syndication namespace. This namespace includes a classes that model a syndication feed and the items that compose the feed, along with classes for formatting a syndication feed into either RSS 2.0- or Atom 1.0-compliant XML. (RSS 2.0 and Atom 1.0 are the two leading syndication feed format standards.)

For more information, check out my latest article on DotNetSlackers.com, which looks at creating and consuming syndication feeds using these new classes in the .NET Framework 3.5 from an ASP.NET application: How to Create a Syndication Feed For Your Website.

Happy Programming!

What's the Best Way to Format a Title for a Blog Post, Article, or Tutorial?
22 February 09 07:59 AM | Scott Mitchell

If you are writing an article, blog post, or tutorial about a feature of ASP.NET or the .NET Framework, how do you format the title? For example, say that you are writing a blog entry about grouping data using ASP.NET's ListView control. Which of these titles is most appropriate?

  1. Grouping Data Couldn't Be Easier!
  2. Group Data Using the ListView Control
  3. ASP.NET's ListView Control Makes Groupnig Data Easy
  4. Learn How to Group Data Using the ListView Control in ASP.NET 3.5

I think title (1) is the worst of the four because it provides no context. It could be a blog entry about grouping data in Excel, a look at using SQL's GROUP BY clause, or an article not even related to computers. Granted, the body of the blog post would make it crystal clear, but from an SEO perspective and when considering that the title it what appears in the search engine results, a more descriptive title would seem to be preferred.

Title (2) does a good job mentioning the feature to be discussed (grouping data) and the control to be used (the ListView). However, it still lacks context, especially if there is some other technology stack that has a control with the same name. (See the postscript below for more discussion on why noting the technology can be important.)

Title (3) mentions the goal / feature (grouping data), the control being demonstrated (the ListView), and the framework (ASP.NET), but it makes no mention of the ASP.NET version. The ListView control was added to ASP.NET version 3.5, so a developer using ASP.NET version 2.0 might not realize that this technique doesn't apply to her until she gets half way through the blog post.

That leads us to title (4), which gives a complete and thorough description. And this is the title format I've migrated to over the years. For example, my current article series on 4Guys about the ListView is titled: Using ASP.NET 3.5's ListView and DataPager Controls, with subtitles explaining what each installment of the article series covers, as in: Using ASP.NET 3.5's ListView and DataPager Controls: Grouping By a Data Field. However, over time I've found one problem with this most descriptive title: including the version number makes sense and seems like a good idea when covering some new feature in the latest version of ASP.NET, but it unnecessarily dates the article. Because ASP.NET versions are additive, the technologies present in ASP.NET 2.0 are still around in ASP.NET 3.5, which is great from a developer's perspective. But if you include the verison number in the article it makes it sound like the feature in question is now antequated or that it no longer applies to the latest version.

Take the following article title, for example: Health Monitoring in ASP.NET 2.0. Health Monitoring was introduced in ASP.NET 2.0 and does not exist in ASP.NET 1.x, hence the rationale for adding the version number in the title. But today we are using ASP.NET 3.5. Health Monitoring still exists and is still used in ASP.NET 3.5 applications, but that article title makes it sound like Health Monitoring is something specific to 2.0. I worry that someone who sees that title in Google's search results will say, “I'm using ASP.NET 3.5, so that article is not relevant to me“ and instead choose to read an article that's titled, “Learn How to Use ASP.NET's Health Monitoring“ because it makes no mention of ASP.NET 2.0.

Given all of this, I am torn between title formats (3) and (4), and I'm now leaning more to (3) than (4). Including the version number is useful when writing about a technology that will be in the next version of ASP.NET or is in the just-released version of ASP.NET, but it becomes a liability as time marches on and new versions of ASP.NET are released. Perhaps the ideal approach would be to change the title over time. That is, name the article Health Monitoring in ASP.NET 2.0 when ASP.NET 2.0 first comes out, but knock off the version number and change the title to Health Monitoring in ASP.NET when ASP.NET 3.5 is nearing release.

Thoughts?

P.S.: Regarind title (2) and omitting the framwork context... During the ASP.NET 1.x days I wrote an 18-part article series on 4Guys titled An Extensive Examination of the DataGrid Web Control. There is also a DataGrid control that can be used in WinForms applications. Despite having the same name, the DataGrid controls in the ASP.NET and WinForms differ substantially when it comes to binding data to the control, adding paging and sorting features, and so on. Long story short, during the ASP.NET 1.x days I'd get an e-mail or two a week from WinForms developers who had questions about the WinForms DataGrid control. It was clear that some had read the article, realized that the focus was on the ASP.NET DataGrid, but asked their question anyway, hoping I could help, while others clearly did not read a word of the article. Perhaps a more descriptive title: An Extensive Examination of the ASP.NET DataGrid Web Control would have reduced the number of these e-mails.

P.S.S.: I'm sure that if you e-mail a blogger or author of an article with a question, you do so in a very courteous and kind manner and realize that you are, in essence, asking for free help from a stranger who likely has other tasks and duties that demand his attention. Moreover, I'm sure you understand if said author or blogger cannot respond to your query, or responds with a, “Sorry, I'm too busy to help,“-type message. But there are people who somehow expect that you are there to be their free, private consultant and programmer, and get surly if you don't answer their question post haste. I bring this up because writing the above aside reminded me of one of the most vitriolic e-mails I ever got from a reader was from a guy who had a question about the WinForms DataGrid control. I had explained to him that there were differences between the ASP.NET and WinForms DataGrid, and that I was not familiar with the WinForms DataGrid and therefore couldn't be of help, and got back one of the nastiest e-mails I've ever received about how they were indeed alike and that I just didn't want to help him and was being all sorts of words I don't want to write here for fear that your workplace's Internet filter will flag my site. The point is (and there is a point in here somewhere, I'm sure), is that the next time you run into one of these types of people, feel free to smack them on the back of their head for me.

Filed under:
Blogs are the Most Important Innovation of the 21st Century
13 February 09 08:35 AM | Scott Mitchell

A case could be made that blogs and blog hosting websites like WordPress and Blogger are, so far, the most important innovation of this century, technological or otherwise. Prior to the advent of blogs, publishing online was a task reserved for the computer savvy. Sure, sites like Geocities and Tripod lowered the barrier, but still required a good deal of work and at least a passing familiarity with HTML. It wasn't until blogs that the average person - my mom, my grandfather, etc. - could, with a few points and clicks of the mouse, get their thoughts, feelings, and information out to an audience of, potentially, billions. In mathematics there is the concept of different cardinalities of infinity. While both the set of integers and the set of real numbers are inifinite sets, there are 'more' items in the set of real numbers. It's a 'bigger' infinity, if you will. In a similar vein, both e-mail and blogs shrink the world and allow people who may be vast distances apart to communicate with one another instantly, but blogs go a step beyond e-mail (or the telephone or fax machines) in that it allows for one-to-many communications. With an e-mail message you can send urban legends and corny jokes to your aunt in Baltimore, but with your blog you can share them with the world at large.

Blogs have had a very profound affect on society as a whole. They have democratized the publishing process and made the idea of citizen journalism a reality and, in doing so, they have quickly neutered industries that were flourishing a mere 10 years ago. Why buy a newspaper when you can get your information online? Why pick up a copy of Sports Illustrated when you can read more interesting and in-depth articles written by ex-GMs, current athelets, and impassioned fans? And what's the motivation to purchase a programming book when there are countless developers sharing their tips and tricks, what works and what doesn't, on their blogs each day? Of course, there are benefits to be had by big box newspaper and magazines and having content presented on pieces of paper. Print media is not dead, but it has been relegated to a niche market, and blogs are a big reason why.

Blogs have also had a profound impact on the Web 2.0 landscape, namely in the areana of syndication. Ten years ago content syndication was in its infancy. Blogs were the first application that used syndication - Dave Winer invented RSS in 1997 to syndicate content from his blog, Scripting News. As the popularity of blogging grew, the RSS standard matured, the Atom standard was created, and non-blog sites started embracing syndication. Today, virtually every website that produces content on a regular or semi-regular schedule provides a syndication feed. We have blogs to thank for that development.

It may seem like an over-exaggeration to say that blogs have had such a profound impact, but consider this - how do you think my daughter will react when I tell her, 15 years hence, that there was a time in my life when only people who were 'computer experts' could publish content online. I think she'll be flabbergasted, and I think that surprise and disbelief she'll have is a testament to how important an innovation blogging has been.

Filed under:
Keyboard Thoughts
09 February 09 07:05 PM | Scott Mitchell

Jeff Atwood recently replaced his keyboard, a Microsoft Natural Keyboard 4000, with... a new Microsoft Natural Keyboard 4000.

I mentioned my beloved Microsoft Natural Keyboard 4000, which is pretty much the holy grail of keyboards to me. Some people don't care for the non-split spacebar, and the way the keys have a fair bit of resistance -- but that's never bothered me. If you're into the whole ergonomic split layout thing, as I obviously am, it's difficult to go wrong with the Natural 4000. That's why I'm replacing my old keyboard with the very same model.

I am also a (mostly) satisfied user of the Microsoft Natural Keyboard 4000. My only complaint has to do with the function keys and function key remapping. For starters, the function keys are not as big as they were in old school keyboards. I cut my teeth on keyboards where the function keys were square shaped. However, the function keys on the Microsoft Natural Keyboard 4000 are almost half as tall as they are wide. But what's more frustrating is that, like many Microsoft keyboards, the function keys (F1-F12) perform some alternate action if the Function Lock option is disabled. (You can toggle the Function Lock by pressing the F Lock key, which is immeidately to the right of F12.) About once a month the Function Lock status will toggle magically. I know for a fact I'm not pressing it. I don't know if some program can toggle it, or if they keyboard has a short circuit, or if my forceful typing somehow jiggles the F Lock key. Regardless, about once a month I find that my function keys aren't working and the reason is because the Function Lock has been disabled.

This function mapping also annoys Jeff, who lists three bad keyboard design decisions:

  • Mangling the Home Key Cluster
  • Using a Non-Standard Arrow Key Cluster
  • Remapping the Function Keys

I have another item to add to the list - keyboards that break from the norm of having the lower left key be the Ctrl key. Too many laptops do this, placing the Fn key in the lower left corner and the Ctrl key to its immediate right.

The Ctrl key is one of the most oft-used keys for people who prefer to keep their hands on the keyboard and off the mouse, as it's the key that typically denotes a keyboard shortcut, including the most essential ones: Copy, Paste, Cut, Open, Save, Print, Undo, and Redo. It is almost tantamount to moving the space bar, or the Enter or Tab keys. Almost. Which is why it is baffling that this keyboard layout is still in use and is not some footnote in the history of flawed design, like Microsoft Bob and VRML.

Filed under:
Accessing the DropDownList Control's SelectedIndex or SelectedValue Properties Selects the First ListItem
06 February 09 10:04 AM | Scott Mitchell

I was recently helping a colleague squash a bug that had popped up on a page that involved a DropDownList. Specifically, an HttpException was being thrown with the error message Cannot have multiple items selected in a DropDownList. This exception is raised, as the message notes, if a DropDownList contains multiple ListItems whose Selected properties are set to true.

The page in question had a DropDownList whose values were populated from a web service on the first page load. Shortly after this population code was a foreach loop that looped through the items in the DropDownList looking for a ListItem whose value matched a user-specific setting. The first such ListItem found had its Selected property set to true before exiting the loop. The code (in the Page_Load event handler) looked something like this:

if (!Page.IsPostBack)
{
    ... Populate MyDropDownList ...
 
    ... More Code ...
 
    foreach(ListItem li in MyDropDownList.Items)
        if (li.Value.StartsWith("some value specific to the user visiting the page"))
        {
            li.Selected = true;
            break;
        }
}

This error was perplexing because while there was some code that occurred between the population of the DropDownList, when the appropriate ListItem was selected, and when the page was rendered, none of that code set the Selected property to true or assigned a value to the DropDownList's SelectedIndex or SelectedValue properties. To unearth the cause of this error I fired up the debugger and set a breakpoint at the point where the DropDownList was populated. I then put the following statements in the Watch window:

  • MyDropDownList.Items[0].Selected
  • MyDropDownList.Items[1].Selected
  • MyDropDownList.Items[2].Selected
  • ...

I wanted to see what items became selected and when. As I was stepping through the code, things started to unfold as I expected. After the DropDownList was populated all of the Items[i].Selected values returned false. But then in the code between where the DropDownList was populated and when a ListItem was selected based on the user's settings, there was a call to a method further down in the code-behind class. That method did not set the DropDownList's SelectedIndex or SelectedValue properties so I stepped over it thinking that it couldn't be the cause of my problems. But as I stepped over the method call the MyDropDownList.Items[0].Selected value in the DropDownList changed to true!

I went to look at the code in that method I had just stepped over. This method was (among other things) showing or hiding a Panel on the page based on whether the first DropDownList item was selected. It had code like:

if (MyDropDownList.SelectedIndex == 0)
    SomePanel.Visible = true;
else
    SomePanel.Visible = false;

But here's the rub - merely reading the value of the DropDownList's SelectedIndex property (or SelectedValue) causes the first ListItem in the DropDownList to be selected! This kind of makes sense, I guess. Unlike a ListBox there's always an item in the DropDownList that is selected. What's confusing is that the MyDropDownList.Items[0].Selected property is not true when the data is first bound to the DropDownList, but only after the SelectedIndex or SelectedValue properties are accessed. If these properties had not been read in the method that was called then my code in the Page_Load event handler would have worked as expected and without error.

You can see how the first DropDownList item gets auto-selected when the SelectedIndex property is accessed by examining the SelectedIndex property code using Reflector:

    1 public override int SelectedIndex
    2 {
    3     get
    4     {
    5         int selectedIndex = base.SelectedIndex;
    6         if ((selectedIndex < 0) && (this.Items.Count > 0))
    7         {
    8             this.Items[0].Selected = true;
    9             selectedIndex = 0;
   10         }
   11         return selectedIndex;
   12     }
   13     set
   14     {
   15         base.SelectedIndex = value;
   16     }
   17 }

Note lines 6-10. If the selected index is not set and if there are one or more items in the DropDownList then the first item is automatically selected (line 8)! In short, the first item of the DropDownList was being silently selected between the time the DropDownList was populated and the foreach loop that set the Selected property of some other ListItem based on the user's settings. Hence the resulting Cannot have multiple items selected in a DropDownList exception during rendering of the DropDownList. (Because the DropDownList's SelectedValue property reads the SelectedIndex property, accessing the SelectedValue property also has the side-effect of selecting the first DropDownList item.)

I fixed this by adding a loop that enumerates the DropDownList Items collection just before the foreach loop, setting each ListItem's Selected property to false.

if (!Page.IsPostBack)
{
    ... Populate MyDropDownList ...
 
    ... More Code ...
 
    foreach(ListItem li in MyDropDownList.Items)
        li.Selected = false;
        
    foreach(ListItem li in MyDropDownList.Items)
        if (li.Value.StartsWith("some value specific to the user visiting the page"))
        {
            li.Selected = true;
            break;
        }
}
Filed under:
The DefaultButton Property - News To Me!
04 February 09 07:28 AM | Scott Mitchell

Back in January I created and shared a custom server control called RedirectButton that was designed to be used in scenarios where the user is taken to a different page when a Button is clicked. It's a common scenario that virtually every ASP.NET developer has implemented at one time or another. The typical pattern for implementing such behavior is to add a Button to the page and create a Click event handler that executes a Response.Redirect(url). If the redirect incorporates some input from the user, then this pattern is expanded to include the addition of a TextBox or some other control to the page and a Response.Redirect(url) statement that includes this control's value in the querystring.

The RedirectButton control was designed to account for two shortcomings of this pattern:

  • Eliminate the extra round trip to the server (the postback that does nothing more than send back a Response.Redirect).
  • If there is an associated TextBox where the user enters some value and that is transmitted via the querystring, you need to worry about what happens if the user presses the Enter key while focused in this TextBox. There's a postback, most likely, but what Button is considered clicked? This issue becomes more apparent if you have several TextBoxes on a page, each with a Button, that, when clicked, takes the user to some other page passing along the related TextBox's value through the querystring.

Turns out the second shortcoming isn't a shortcoming of the TextBox or the Button or ASP.NET in general, but a shortcoming of my knowledge of the tools at my disposal. Turns out that you can implement such behavior using a standard Button by simply placing it (and the associated TextBox) into a Panel control and setting the Panel's DefaultButton property to the ID of the Button control. (Thanks to alert 4Guys reader Vinod Soni for pointing this feature out to me.) Doing so renders the following markup:

<div ... onkeypress="javascript:return WebForm_FireDefaultButton(event, 'buttonId')">
...
<INPUT id="buttonId" type=submit value=Button name="buttonId" />
</div>

The Panel renders the <div>, which includes an onkeypress client-side event handler. The WebForm_FireDefaultButton function is added to the page automatically through a JavaScript include and is executed everytime there is a key press in the <div>. If the user hits Enter (keycode 13) while not in a multi-line TextBox, then the default button is "clicked." The full script for this function follows:

function WebForm_FireDefaultButton(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
if (!src || (src.tagName.toLowerCase() != "textarea")) {
var defaultButton;
if (__nonMSDOMBrowser) {
defaultButton = document.getElementById(target);
}
else {
defaultButton = document.all[target];
}
if (defaultButton && typeof(defaultButton.click) != "undefined") {
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation) event.stopPropagation();
return false;
}
}
}
return true;
}

What's more, you can also set the default button for an entire form. The HtmlForm class has a DefaultButton property as well. The DefaultButton properties for the form and Panel were added in ASP.NET 2.0; it is not available in 1.x applications. In other words, this functionality has been present in the framework since 2005 - it took four years for me to learn about it, and I work on ASP.NET applications daily and spend time in Reflector and in the documentation several times per week. I find that there are many such ASP.NET features and control properties that fall into this camp (another example - I didn't discover Health Monitoring until nearly two years after ASP.NET 2.0 was released). What explains this? Perhaps it's a commentary on my continuing education into the .NET world and a hint that I need to explore other avenues for learning and dedicate more time and effort to such tasks, and I'm willing to accept that that is part of the reason, but another factor is the sheer size of the .NET Framework and the wealth of features that are added, and the speed and frequency with which new features and frameworks and technologies are unveiled.

Filed under:
New T-SQL 2008 Syntax
03 February 09 07:40 AM | Scott Mitchell

If you are using Microsoft SQL Server 2008 there are some cool new additions to the T-SQL syntax that can help save you a few keystrokes. For example, with T-SQL 2008 you can now (finally) assign a value to a variable when it is declared, like so:

DECLARE @ThisIsLikeSo int = 1984

Rather than having to put the declaration and assignment on two separate lines.

T-SQL 2008 now includes the standard shorthand operators that have been standard in C++/Java/C# and were added to VB several years ago, things like +=, *=, -=, and so on.

But the neatest new T-SQL syntax is row constructors, which provides a terse syntax for declaring a set of records and are not unlike object initializers in higher-level languages. Want to insert four records into a table? In the past you'd have to write four separate INSERT statements, but with row constructors you can write one INSERT statement with four row constructors in the VALUES part:

-- Add four records to the Employees table
INSERT INTO Employees(Name, Email, Salary)
VALUES('Scott',
'scott@example.com', 50000.00),
('Jisun',
'jisun@example.com', 225000.00),
('Alice',
'al@example.com', 75000.00),
('Sam',
'sam@example.com', 45000.00)

My latest monthly tip at DotNetSlackers.com summarizes the new T-SQL 2008 features that will help you write more terse stored procedures, UDFs, and ad-hoc scripts: More Concise T-SQL with SQL Server 2008.

Filed under:
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.