Uncategorized
Snack size C#: null coalescing operator
Feb 13th
You need to assign the value of an expression to a variable, unless that expression evaluates to null, in which case default to something else. And if that something else is also null, then fall back to another value, and so on.
For example, a web page that uses a theme setting to control look-and-feel. If the user has selected their own theme then use that; otherwise use the site’s default theme; or, if that’s not defined, use the global theme; or finally if no global theme is defined then fall back to a system default.
The long, readable version
Using good, old fashioned, conditional logic.
string theme;
if (userTheme != null)
{
theme = userTheme;
}
else if (siteTheme != null)
{
theme = siteTheme;
}
else if (globalTheme != null)
{
theme = globalTheme;
}
else
{
theme = defaultTheme;
}
The shorter, slightly befuddling version
By nesting the ternary conditional operator in a most disagreeable way.
string theme =
userTheme != null ? userTheme
: siteTheme != null ? siteTheme
: globalTheme != null ? globalTheme
: defaultTheme;
The deluxe C# 3.0 version
With the overkill of an implicitly-typed array, an IEnumerable extension method, and a lambda predicate.
string theme = new [] {
userTheme, siteTheme, globalTheme, defaultTheme
}.First(t => t != null);
The elegant coalescence version
With C# 2.0’s null-coalescing operator, doing what it does best.
string theme = userTheme ?? siteTheme ?? globalTheme ?? defaultTheme;
Free Microsoft certification beta exams coming soon
Feb 11th
New beta Microsoft certification exams available free between March 31, 2010 and April 20, 2010.
- 70-515 TS: Web Applications Development with Microsoft® .NET Framework 4
- 70-516 TS: Accessing Data with Microsoft® .NET Framework 4
- 70-513 TS: Windows Communication Foundation Development with Microsoft® .NET Framework 4
- 70-519 Pro: Designing and Developing Web Applications using Microsoft® .NET Framework 4
More info on Gerry O’Brien’s blog here: Free Certification Exams
70-513 TS: Windows Communication Foundation Development with Microsoft® .NET Framework 4
70-515 TS: Web Applications Development with Microsoft® .NET Framework 4
70-516 TS: Accessing Data with Microsoft® .NET Framework 4
70-519 Pro: Designing and Developing Web Applications using Microsoft® .NET Framework 4
TableHeaderScope.Column and HTML standards compliance
Feb 5th
Neil spotted this quirky behaviour in the TableHeaderCell control. Suppose you’ve got a Table web control that renders a <table> tag with a <th scope=”col”>, using code something like this:
Table table = new Table()
{
Rows =
{
new TableRow()
{
Cells =
{
new TableHeaderCell()
{ Scope = TableHeaderScope.Column, Text = "MyColumn" }
}
}
}
};
Then the rendered HTML won’t be W3C compliant because a scope value of “column” isn’t valid:
<table border="0">
<tr>
<th scope="column"></th>
</tr>
</table>
According to the W3C HTML and XHTML specs, the acceptable values for scope are [row|col|rowgroup|colgroup]. This is confirmed by the W3C Markup Validation Service, which reports the error:

Stepping into the source code for the TableHeaderCell control with Reflector or the .NET Reference Source, you can see the root of the problem:
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
TableHeaderScope scope = Scope;
if (scope != TableHeaderScope.NotSet)
{
writer.AddAttribute(HtmlTextWriterAttribute.Scope,
scope.ToString().ToLowerInvariant());
}
}
When the control sets the scope attribute’s value, it uses a lowercase string representation of the TableHeaderScope.Column enumeration, i.e. “column”. An enum value of TableHeaderScope.Col would’ve been ok, but TableHeaderScope.Column is invalid.
Workarounds
Neil has a good workaround by adding the scope attribute manually instead of using the TableHeaderCell.Scope property:
TableHeaderCell th = new TableHeaderCell(); th.Attributes["scope"] = "col";
I thought I’d have a go at extending this fix into a simple control adatper that makes sure TableHeaderCell always renders itself correctly. It works by checking whether the Scope property is set to TableHeaderScope.Column, and if so manually adds the attribute scope=”col” instead. Here’s the code:
public class TableHeaderCellAdapter : WebControlAdapter
{
protected override void RenderBeginTag(HtmlTextWriter writer)
{
TableHeaderCell th = (TableHeaderCell) this.Control;
if (th.Scope == TableHeaderScope.Column)
{
th.Scope = TableHeaderScope.NotSet;
th.Attributes["scope"] = "col";
}
base.RenderBeginTag(writer);
}
}
To associate the control adapter class with the TableHeaderCell control, add a browser definition file to the App_Browsers folder:
<!-- file: ~/App_Browsers/ControlAdapters.browser -->
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter
controlType="System.Web.UI.WebControls.TableHeaderCell"
adapterType="TableHeaderCellAdapter" />
</controlAdapters>
</browser>
</browsers>
Configuring IIS7 for ASP.NET on Windows Vista
Feb 5th
As part of Microsoft’s ongoing Trustworthy Computing initiative, Vista takes the secure by default principle more seriously than previous versions of Windows. Consequently, many features aren’t installed by default, one of which is IIS 7. So, to install IIS go to:
Control Panel – Programs – Turn Windows features on or off
Then find the Intenet Information Services section and add everything you need, including ASP.NET.
Installing ASP.NET Membership, Roles and Profiles support in SQL Server
Feb 4th
Here are few quick tips if you’re using the ASP.NET Application Services with SQL Server, like Membership, Roles, Profiles, Personalization or Web Events. These built-in “building-block” services have SQL provider implementations in .NET that let you use a SQL Server 2000 or 2005 database as their data store. These are the framework classes that implement the SQL Server providers:
- SqlMembershipProvider – managing user credentials and authentication
- SqlRoleProvider – handling role-based authorisation
- SqlProfileProvider – storing and retrieving information about individual users
- SqlPersonalizationProvider – saving state of web parts
- SqlWebEventProvider – capturing and logging web event data
ASP.NET SQL Server Registration Tool
Adding support for these providers to your database is easy, just run the ASP.NET SQL Server Registration tool from the command-line (aspnet_regsql.exe) to launch the ASP.NET SQL Server Setup Wizard. This will guide you through the process with a simple GUI:
cd C:\Windows\Microsoft.NET\Framework\v2.0.50727 aspnet_regsql.exe
By default, the wizard installs all five services : Membership, Roles, Profiles, Personalization and Web Events. However, if you need support for only some, say just Membership and Roles, then aspnet_regsql can be run from the command-line with specific options, for example:
aspnet_regsql -S MySqlServer -E -A mr -d MyAspDatabase
This installs the Membership and Roles services (-A mr) on server MySqlServer in database MyAspDatabase using current Windows credentials for authentication. To see a full list of command-line options and switches, run the registration tool with the help flag:
aspnet_regsql.exe /?
There’s also an option to generate just SQL scripts without executing them, and another to remove services from the database that aren’t used or needed anymore. (You can also manage SQL cache dependencies and session state using this tool.)
For more info about ASP.NET SQL providers:
Horse sense: Agile versus Waterfall
Feb 2nd
Check out Stuart Cam’s excellent comparison of agile versus waterfall development models, illustrated as drawing a horse:
That freakish Frankenstein waterfall horse is going to give me nightmares.
New VS 2010 and .NET 4.0 training on msdev
Feb 2nd
Microsoft’s just added eight hours of .NET 4.0 and Visual Studio 2010 sessions to its training site msdev.com with New Features in .NET Framework 4 and Visual Studio 2010, Beta 2.
Subjects covered are:
- Parallelism
- ADO.NET Data Services
- F#
- Office Programmability
- ASP.NET AJAX
- ASP.NET MVC
- ASP.NET WebForms
- Managed Languages
And there’s even more ASP.NET 4.0 training in the ASP.NET 4.0 Quick Hit Videos series. A great introduction to loads of new features in bite-size pieces:
- Chart Control
- Dynamic Metadata
- Permanent Redirect
- Imperative WebForms Routing
- Declarative WebForms Routing
- Outbound WebForms Routing
- Auto Start
- Clean Web.Config Files
- Predictable Client IDs
- Selective View State
- The HtmlEncoder Utility Method
- New Rendering Option for Check Box Lists and Radio Button Lists
- Persistent GridView Row Selection
- Table Free Templated Controls
- Easy State Compression
- Tableless Menu Control
- Imperative JavaScript Syntax for Microsoft Client Side Controls
- The ScriptLoader
- jQuery Syntax for Microsoft Ajax
- AJAX Data Templates
- Hidden Field Divs
- Disabled Control Styling
Easy Localization using Factory Methods in .NET
Oct 4th
ASP.NET 2.0 has some great localization features that make it easy to build multilingual web applications. The problem comes when you need different business logic for different countries, maybe to validate a local address or calculate shipping costs. You somehow need to get the application to behave differently based on a country code or the thread’s current culture setting.
For simple variations you can use separate configuration settings for each country. For example, a regular expression in web.config to validate a local telephone number. But if the logic is more complex then you might need a different plan.
An obvious approach is to use conditional switch/select-case statements, like this:
switch (countryCode)
{
case "FR":
/* Logic for France */
case "US":
/* Logic for USA */
}
But for large applications this can quickly get unwieldy and difficult to manage. Adding a new country means finding every switch statement and adding a new case.
Instead, a good solution is the Factory Method design pattern. It makes your application much easier to maintain, and adding new countries is easy. Here’s a quick example that extends the idea of validating local postcode formats.
Class Diagram
These are the classes used, described below in more detail.

Step 1
Create an abstract class for performing local validation called LocalValidatorBase. This is a base class which can’t be instantiated. Add a method signature IsValidPostcode that takes a string and returns a boolean. Classes for various countries can now derive from LocalValidatorBase and override IsValidPoscode with custom validation logic.
(The LocalValidatorBase class can contain logic to share between all the subclasses, but if this isn’t necessary then you can create an interface instead of an abstract class called something like ILocalValidator.)
Step 2
Derive two local validation classes from LocalValidationBase called LocalValidatorAU and LocalValidatorDE, one for Australia and one for Germany. In each, override IsValidPoscode to perform country-specific logic for validating a postcode, maybe by checking the string length or matching against a regular expression. The details aren’t important here.
Step 3
Create a factory class to return the correct validator object for the current country setting. Add a static/shared factory method called GetLocalValidator that returns a LocalValidatorBase class. The magic of polymorphism means this method can return any class derived from LocalValidatorBase. Use a switch statement, or some other conditional logic, to return a new instance of LocalValidatorDE or LocalValidatorAU depending on a country code parameter or the thread’s current culture name.
Step 4
That’s all there is to it. You can now call the factory method to get the correct validator object for the current country.
' call the factory method to get a concrete validator
Dim validator As LocalValidatorBase = _
LocalValidatorFactory.GetLocalValidator()
Dim isValid As Boolean = validator.IsValidPostcode("12345")
The validation success depends on the rules in the object returned by GetLocalValidator, which will be different depending on the current country.
Firebug
Dec 15th
Firebug, a developer plug-in for Firefox, just made front-end development a lot easier:
- Inspect and edit live HTML and CSS
- Visualise CSS box-model
- Monitor network metrics
- Debug and profile JavaScript
- DOM explorer
MCTS study resources
Nov 16th
Here are a few online resources for studying towards MCTS: .NET Framework 2.0 Web Applications:
Exam 70–528: .NET 2.0 Web-Based Client Development
- Microsoft Preparation Guide
- Web-based Client Development – Free Skills Assessment
- MeasureUp practice test (150 questions)
- Wikibook MCTS textbook
Exam 70–536: .NET 2.0 Application Development Foundation

