Customising Visual Studio debugger DataTips with DebuggerDisplay
Feb 18th
The DebuggerDisplay attribute lets you change how an object is displayed in the Visual Studio debugger. Take these two simple classes representing a Company and an Employee.
public class Company
{
public string Name { get; set; }
public string StockSymbol { get; set; }
public IEnumerable<Employee> Employees { get; set; }
public Company(string name) { Name = name; }
}
public class Employee
{
public string Name { get; set; }
public Employee(string name) { Name = name; }
}
Create and initialise a new Company object with some data.
var company = new Company("Microsoft")
{
StockSymbol = "MSFT",
Employees = new List<Employee>
{
new Employee("Anders Hejlsberg"),
new Employee("Steve Ballmer"),
new Employee("Scott Guthrie")
}
};
Now, if you break into the code and start a debug session, you can hover over the company object to reveal its debugger DataTip. By expanding the nodes you can drill down into the object’s data.

The default information shown in the DataTip, although useful, can be improved by decorating classes with the DebuggerDisplay attribute. For companies, it might be useful to to display their Name and StockSymbol instead of the object type {Company}.
[DebuggerDisplay("{Name} - {StockSymbol}")]
public class Company
The same goes for the Employee object. We can show the employee name instead of the type {Employee}.
[DebuggerDisplay("{Name}")]
public class Employee
The result is a more useful and descriptive view of your Company objects.

For more info about customising Visual Studio’s debugger DataTips, see this article from MSDN Magazine:
Fibonacci numbers iterator with C# yield statements
Feb 15th
Here’s a C# iterator for generating the sequence of Fibonacci numbers. It uses the yield return statement to pass back each number in turn. By default, the arithmetic addition won’t throw an exception when previous + current is greater than UInt64.MaxValue, so I’m using a checked expression to enable overflow checking.
public static IEnumerable<ulong> FibonacciNumbers()
{
yield return 0;
yield return 1;
ulong previous = 0, current = 1;
while (true)
{
ulong next = checked(previous + current);
yield return next;
previous = current;
current = next;
}
}
We can use the iterator with a foreach loop until it throws an OverflowException.
try
{
foreach (ulong i in FibonacciNumbers())
{
Console.WriteLine("{0:0,0}", i);
}
}
catch (OverflowException)
{
Console.WriteLine("Sorry, the next number is too big.");
}
Building a string of repeated characters in C#
Feb 14th
As many different techniques as I could think of for making a string of repeated characters in C#.
char ch = 'A';
int count = 100;
// clean and concise, using the string contructor overload
var spaces1 = new string(ch, count);
// using Enumerable.Repeat to build a list of spaces,
// then folding them into a string
var spaces2 = Enumerable.Repeat(ch, count).Aggregate("", (s,c) => s+c);
// brute force of looping into a StringBuilder
var sb = new StringBuilder(count);
for (int i = 0; i < count; i++) { sb.Append(ch); }
var spaces3 = sb.ToString();
// building an array of strings, then joining without a delimiter
var spacesArray = Enumerable.Repeat(ch.ToString(), count).ToArray();
var spaces4 = string.Join(string.Empty, spacesArray);
// dirty hack with StringBuilder.Insert
var spaces5 = new StringBuilder().Insert(0, ch.ToString(), count).ToString();
// succinct hack with String.PadRight
var spaces6 = string.Empty.PadRight(count, ch);
// using ArrayList.Repeat to build the array of repeated strings
// then smushing with String.Concat
var arrayList = ArrayList.Repeat(ch, count).ToArray();
var spaces7 = string.Concat(arrayList);
Examples of C# Object Initializers
Feb 13th
A selection of the various C# object initialization syntaxes:
// explicit shorthand array, C# 1.0 style
int[] numbersIntArray1 = { 4, 8, 15, 16, 23, 42 };
// two dimensional 3x2 array
int[,] numbersInt3x2Array = { { 4, 8 }, { 15, 16 }, { 23, 42 } };
// implicitly typed array
var numbersIntArray2 = new[] { 4, 8, 15, 16, 23, 42 };
// typed array with an implicitly type variable
var numbersDoubleArray = new double[] { 4, 8, 15, 16, 23, 42 };
// generic List<>
var numbersList = new List<int> { 4, 8, 15, 16, 23, 42 };
// generic HashSet<>
var numbersHashSet = new HashSet<int> { 4, 8, 15, 16, 23, 42 };
// generic Dictionary
var dictionary = new Dictionary<int, string>
{
{ 4, "four" },
{ 8, "eight" },
{ 15, "fifteen" },
{ 16, "sixteen" },
{ 23, "twenty three" },
{ 42, "fourty two" }
};
// implicitly typed array of System.Uri objects
var searchEngines = new[]
{
new Uri("http://www.google.com/"),
new Uri("http://www.bing.com/"),
new Uri("http://www.yahoo.com/")
};
// implicitly typed array of an anonymous type
var complexNumbers = new[]
{
new { Real = 4, Imaginary = 7 },
new { Real = -10, Imaginary = 3 },
};
// implicitly typed array of System.Func<> delegates
var operations = new Func<int, int>[]
{
(x => x * x),
(x => x + x)
};
// nested object initializers
var smtpClient = new SmtpClient
{
Host = "mail.example.com",
Port = 25,
Credentials = new NetworkCredential
{
UserName = "MailScheduler",
Password = @"%yI2Ei5GL0"
}
};
// implicitly typed jagged array of strings
var jaggedArray = new[]
{
new[] {"Jack", "Sayid", "Hurley", "Miles"},
new[] {"Sawyer", "Kate"}
};
// implicitly typed array of objects implementing IEnumerable<int>
var listOfLists = new IEnumerable<int>[]
{
new List<int> {4, 8, 15, 16, 23, 42},
new Collection<int> { 4, 8, 15, 16, 23, 42 },
new int[] {4, 8, 15, 16, 23, 42 }
};
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# 3.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:
New and upcoming books for ASP.NET developers
Feb 2nd
The are some great books in the pipeline for ASP.NET web developers. Everything from Visual Studio 2010, ASP.NET 4.0, ASP.NET MVC, HTML 5, jQuery 1.4, and even iPhone development. Not to mention second editions of classic titles like jQuery in Action and C# in Depth.
Got any more? Let me know in the comments.
O’Reilly
Web Design for Developers – A Programmer’s Guide to Design Tools and Techniques
Web Design for Developers will show you how to make your web-based application look professionally designed. We’ll help you learn how to pick the right colors and fonts, avoid costly interface and accessibility mistakes–your application will really come alive. We’ll also walk you through some common Photoshop and CSS techniques and work through a web site redesign, taking a new design from concept all the way to implementation.
Effective UI – The Art of Building Great User Experience in Software
Effective UI provides a complete roadmap to building groundbreaking software centered on user experience (UX) quality, how to get management support, employing product management strategies proven to deliver greater success, and how to manage the design, engineering, staffing, and business considerations that must be centered on the user’s needs and working effectively in tandem all throughout the project. Effective UI is a guide for business and product, software professionals, and anyone else struggling to advance the cause of better UX and working to deliver on the promise of higher quality software.
Search Patterns
Search is among the most disruptive innovations of our time. It influences what we buy and where we go. It shapes how we learn and what we believe. This provocative and inspiring book explores design patterns that apply across the categories of web, ecommerce, enterprise, desktop, mobile, social, and realtime search and discovery. Using colorful illustrations and examples, the authors bring modern information retrieval to life, covering such diverse topics as relevance ranking, faceted navigation, multi-touch, and augmented reality. Search Patterns challenges us to invent the future of discovery while serving as a practical guide to help us make search better today.
97 Things Every Programmer Should Know – Collective Wisdom from the Experts
Get 97 short and extremely useful tips from some of the most experienced and respected practitioners in the industry, including Uncle Bob Martin, Scott Meyers, Dan North, Linda Rising, Udi Dahan, Neal Ford, and many more. They encourage you to stretch yourself by learning new languages, looking at problems in new ways, following specific practices, taking responsibility for your work, and becoming as good at the entire craft of programming as you possibly can.
High Performance JavaScript
Do you want to fix performance bottlenecks in your JavaScript code to help your website function better? With this book, you’ll examine the typical code problems that cause JavaScript to run slow. High Performance JavaScript teaches you how to identify inefficient structures and patterns, and replace them with better-performing alternatives.
Programming Microsoft® ASP.NET MVC
Author Dino Esposito leads you through the features, principles, and pillars of the ASP.NET MVC framework, demonstrating how and when to use this model to gain full control of HTML, simplify testing, and design better Web sites and experiences.
APress
Ultra-Fast ASP.NET: Building Ultra-Fast and Ultra-Scalable Websites Using ASP.NET and SQL Server
Ultra-Fast ASP.NET presents a practical approach to building fast and scalable web sites using ASP.NET and SQL Server. In addition to a wealth of tips, tricks and secrets, you’ll find advice and code examples for all tiers of your application, including the client, caching, IIS 7, ASP.NET, threads, session state, SQL Server, Analysis Services, infrastructure and operations. By applying the ultra-fast approach to your projects, you’ll squeeze every last ounce of performance out of your code and infrastructure—giving your site unrivaled speed.
Introducing .NET 4.0: with Visual Studio 2010
Microsoft is introducing a large number of changes to the way that the .NET Framework operates. Familiar technologies are being altered, best practices replaced, and developer methodologies adjusted. Many developers find it hard to keep up with the pace of change across .NET’s ever-widening array of technologies. You may know what’s happening in C#, but how about the Azure cloud? How is that going to affect your work? What are the limitations of the new pLINQ syntax? What you need is a roadmap. A guide to help you see the innovations that matter and to give you a head start on the opportunities available in the new framework.
Pro HTML5 Programming: Powerful APIs for Richer Internet Application Development
HTML5 is here, and with it, rich Internet applications (RIAs) take on a power, ease, scalability, and responsiveness that neither Ajax nor Comet could ever achieve. With this book, developers will learn how to use the latest cutting-edge web technology—available in the most recent versions of modern browsers—to build real-time web applications with unparalleled functionality, speed, and responsiveness.
Pro ASP.NET MVC V2 Framework
Author Steven Sanderson has seen the ASP.NET MVC Framework mature from the start, so his experience, combined with comprehensive coverage of all the new features, including those in the official MVC development toolkit, offers the clearest understanding of how this exciting new framework can improve your coding efficiency. With this book, you’ll gain invaluable up-to-date knowledge of security, deployment, and interoperability challenges.
iPhone and Mac OS X Development for Windows Programmers: C#, C++ and C Edition
When coming to the iPhone and Mac OS X from Windows, you need to learn a new set of coding techniques and tools. Taken blindly, this can come as a shock—a shock that this book will help you avoid. It does this by teaching you to use your existing Windows programming knowledge to ease you into programming for Apple technologies.
Manning
jQuery in Action, Second Edition
A really good web development framework anticipates your needs. jQuery does more—it practically reads your mind. Developers fall in love with this JavaScript library the moment they see 20 lines of code reduced to three. jQuery is concise and readable. Its unique “chaining” model lets you perform multiple operations on a page element in succession. And with version 1.4, there’s even more to love about jQuery, including new effects and events, usability improvements, and more testing options.
Brownfield Application Development in .NET
Brownfield Application Development in .Net shows you how to approach legacy applications with the state-of-the-art concepts, patterns, and tools you’ve learned to apply to new projects. Using an existing application as an example, this book guides you in applying the techniques and best practices you need to make it more maintainable and receptive to change.
Secrets of the JavaScript Ninja
In Secrets of the JavaScript Ninja, JavaScript expert John Resig reveals the inside know-how of the elite JavaScript programmers. Written to be accessible to JavaScript developers with intermediate-level skills, this book will give you the knowledge you need to create a cross-browser JavaScript library from the ground up.
Dependency Injection in .NET
Dependency Injection in .NET is a comprehensive guide than introduces DI and provides an in-depth look at applying DI practices to .NET apps. In it, you will also learn to integrate DI together with such technologies as Windows Communication Foundation, ASP.NET MVC, Windows Presentation Foundation and other core .NET components.
C# in Depth, Second Edition concentrates on the high-value features that make C# such a powerful and flexible development tool. Rather than re-hashing the core of C# that’s essentially unchanged since it hit the scene nearly a decade ago, this book brings you up to speed with the features and practices that have changed with C# from version 2.0 onwards.
MS Press
Microsoft ASP.NET Internals
A comprehensive reference outlining the underpinnings of Microsoft’s Web application environment
Learn how to fully exploit the critical components and rich capabilities of the ASP.NET framework, without scouring blogs for information or enduring hours of trial and error. This comprehensive book offers developers the insights they need—including established architecture patterns—to create better, stronger, faster Web sites and Web-based applications Web services. The book offers readers the guidance they need to take advantage of ASP.NET right away, and outlines the evolution and future of the technology.
Addison Wesley
LINQ to Objects Using C# 4.0: Using and Extending LINQ to Objects and Parallel LINQ (PLINQ)
Using LINQ to Objects, .NET developers can write queries over object collections with the same deep functionality that was once available only with SQL and relational databases. Now, for the first time, developers have a comprehensive and authoritative guide to applying LINQ to Objects in real-world software. Microsoft MVP Troy Magennis introduces state-of-the-art techniques for working with objects more elegantly and efficiently–and writing code that is exceptionally powerful, robust, and flexible.
Updates from comments:
.NET Performance Testing and Optimization (Part 1)
Paul Glavich and Chris Farrell’s upcoming book on .NET performance testing and optimization will be out in a few weeks, and part one is already as a free e-book. They explain why performance testing is a good idea, and walk you through everything you need to know about setting up a test environment. An essential handbook for programmers looking to set up a .NET testing environment.
