.NET Framework 3.5 Reference Poster

This slick .NET 3.5 reference poster is available as a free download from MSDN. It lists the most commonly used types and namespaces in the framework, and makes a great addition to any .NET developer’s workspace:

.NET 3.5 Poster

It’s getting harder and harder to keep up with .NET’s continutally expanding scope, but this poster makes a handy reminder of what’s available, with information on which classes were added in .NET 3.0, and which were introduced in 3.5.

A broad cross-section is covered across all areas of the .NET Framework:

  • ASP.NET
  • WinForms and WPF
  • Communications and Workflow
  • Data, XML and LINQ
  • Fundamentals

Printing

The hi-res version is Microsoft XPS format, so if you’re not using Vista or Office 2007 then you might want the Microsoft XPS Viewer. Also, for ‘easy printing’, there’s a 16 page 4×4 version, but remember: ’some assembly is required if you choose this print method’, so remember to ask an adult for help with the scissors.

My local print shop printed and laminated the PDF version onto A1, which is easily hi-res enough and looks great.

Other .NET Reference Posters

There are other reference posters on MSDN, in particular I like the Silverlight Developer Reference, and keyboard shortcuts for Visual Studio 2008, available for both C# and Visual Basic.

(Thanks to Chris Bowen for the tip off.)

SQL Server 2008 will have IntelliSense

With so many exciting new features in Visual Studio 2008 to play with, I haven’t had much time to look at the preview releases of SQL Server 2008, alias Katmai. The last I heard was there wouldn’t be much new stuff for developers, just features for DBAs and BI analysts with a few performance optimisations thrown in.

The previous upgrade, SQL Server 2000 to 2005, was a huge step forward for developers and added significant advances like CLR integration, SQL Server Management Objects (SMO), Integration Services (SSIS) and a native XML data type; as well as T-SQL enhancements like Common Table Expressions (CTEs), structured error handling with try/catch, pivot, apply, top(n) and row_number.

So I was surprised to see how much new stuff is packed into the latest SQL Server 2008 CTP release, even, finally, IntelliSense for Management Studio, which was much anticipated but conspicuously absent from 2005:

SQL Server 2008 IntelliSense

Also notice the new collapsible code regions, just like you get in Visual Studio. Editing T-SQL has never been such fun! Although, you have to feel a bit sorry for RedGate, whose SQL Prompt plug-in has been filling the auto-completion gap for the last few years.

The groovy new features don’t end with IntelliSense, there are plenty more being sneaked into SQL 2008. I’ll be looking at more soon.

kick it on DotNetKicks.com

MCPD Web Developer exam 70-547 hints and tips

Following my post about studying toward MCPD certification, I’ve now taken the exam and am pleased to say I passed with a good score. The exam 70-547 is about designing and developing web applications using ASP.NET 2.0. It focuses on the full software development lifecycle and covers planning, architecture, design, testing and deployment, where as the prerequisite MCTS exams cover more of the actual coding and implementation details.

My main study guide was the official Microsoft Press book, MCPD Self-Paced Training Kit (Exam 70-547). It covered the syllabus thoroughly enough to get me through the exam, but like most similar books wasn’t much fun to read. It’s over 700 pages, and after the first few hundred the content starts to get fairly monotonous. It’s also difficult to skim because you might miss something essential for the exam. If you’re an experienced developer then you might not learn much, but if you’re new to coding then you should find plenty of useful information about broader areas of software development, such as architecture, data modelling and unit testing.

A lot of the testing chapters read like an advert for Visual Studio Team System (VSTS) and aggressively promote its unit testing and web load testing capabilities. There’s nothing wrong with that, it’s a Microsoft exam after all, but you will need Visual Studio Team Test if you want to work through the practical exercises (an evaluation version is available). The unit testing in VSTS is impressive, but doesn’t seem to offer much over the freely available NUnit. The web load testing on the other hand is invaluable.

My best advice for the book is to read it in short frequent bursts. Try to read a little bit every day and you’ll easily work through it, so don’t be intimidated. If you find yourself slacking, just register for the exam and you’ll soon become motivated. And remember to use the 15% exam discount voucher that comes with the book.

My other study resource, which I also used for the MCTS exams, was the practice test from MeasureUp. The questions are very relevant to the actual exam, and helped highlight areas to focus my study. The most useful feature is that every answer has an explanation, so if you get one wrong you can see why and hopefully fill a gap in your knowledge.

The exam isn’t easy, but many questions appeal to common sense as well as technical expertise, and there aren’t any trick questions. There’s more than enough time to work through the 40 multiple-choice questions, so be careful to read each one closely and don’t panic. Some questions ask you to pick more than one answer so follow the instructions carefully. The passing score is 700 out of 1000.

According to Microsoft’s statistics there are only 2,147 MCPD web developers worldwide, so if you want to improve your skills, stand out in the job market, or negotiate a promotion then certification could be a great career move.

My next goal is MCTS certification for SQL Server and exam 70–431. Then it shouldn’t be too long before the next generation of .NET 3.5 MCTS are available.

Let me know your experiences of studying of taking the MCPD exams in the comments below.

Finding orphaned stored procedures and user-defined functions in SQL Server

I’m currently working on a group of ASP.NET 2.0 websites deployed across about thirty countries. The local flagship site runs on an upgraded version of the original code, and I’m now in the process of bringing all the other sites onto the new improved version.

Over time, new features have been introduced to the site, and old ones removed. Consequently the SQL Server database now contains many redundant tables that aren’t used. So, before cascading out the current schema to the other countries, it’s time for a clean up.

I managed to identify about 60 tables that aren’t used by the application and can safely can be dropped or archived. However, I’m now left with hundreds of stored procedures (SPs) and user-defined functions (UDFs) that were associated with these tables, which can also be removed.

The problem was how to find these orphaned objects. My first approach was a small .NET console application which uses SQL Server Management Objects (SMO). It loops through all SPs and UDFs and finds any that have no dependencies.

public List<string> FindOrphans()
{
    Server server = new Server(".");
    Database db = server.Databases["MyDatabase"];
    List<string> orphans = new List<string>();


    // get list of SPs
    UrnCollection urns = new UrnCollection();
    foreach (StoredProcedure sp in db.StoredProcedures)
    {
        // exclude these objects
        if (sp.IsSystemObject) continue;
        if (sp.Name.StartsWith("aspnet_")) continue;

        urns.Add(sp.Urn);
    }


    // get dependencies
    DependencyWalker dw = new DependencyWalker(server);
    DependencyTree tree = dw.DiscoverDependencies(urns, true);


    // find all objects without any dependencies
    DependencyTreeNode node = tree.FirstChild;
    do {
        if (!node.HasChildNodes)
        {
            string name = new Urn(node.Urn).GetAttribute("Name");
            orphans.Add(name);
        }
        node = node.NextSibling;
    } while (node != null);


    return orphans;
}

This works fine, and helped satisfy my current obsession with SMO. But it’s a bit awkward, and not easily portable or modifiable, to have this pure database operation wrapped up in an executable. So I looked into doing the same thing with just a TSQL query.

-- Find all SPs and UDFs have no dependencies
select
    object_name(obj.[object_id]) as [orphaned_object_name],
    obj.type_desc as [object_type],
    'DROP ' +
    case obj.type_desc
        when 'SQL_STORED_PROCEDURE' then 'PROCEDURE'
        else 'FUNCTION'
    end
    + ' [' + object_name(obj.[object_id]) + ']'
from
    sys.objects obj
    left join (select distinct [object_id] from sys.sql_dependencies) dep
        on obj.object_id = dep.object_id
where
    type_desc in ('SQL_STORED_PROCEDURE','SQL_SCALAR_FUNCTION','SQL_TABLE_VALUED_FUNCTION')
    and object_name(obj.[object_id]) not like 'aspnet_%'
    and dep.object_id is null
order by
    obj.type_desc, object_name(obj.[object_id])

The query works by checking for dependencies in the catalog view sys.sql_dependencies. This, I think, is a neater solution. I also included an auto-generated column that writes the SQL drop the SP or UDF, which I copied and executed.

Now, if only I could find a quick way to check for dependencies between my application’s data access layer and the database…

kick it on DotNetKicks.com

Easy Localization using Factory Methods in .NET

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.

Abstract method

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.

Reading other people’s .NET code

One thing that makes HTML easy to learn is the abundance of examples. You can go to any old website and view the source to see how it’s put together, or look through templates on a site like Open Source Web Design or Open Source Templates. It’s easy find examples of good (and bad) practice.

Scott Hanselman’s article Reading to Be a Better Developer got me wondering why we don’t do this more with .NET code, and the problem for me seems to be finding good code examples. Scott recommends looking at the Coding4Fun Developer Kit, but I wanted something more specific to web development.

So here are a few places I found ASP.NET source code that’s worth studying and learning from.

Microsoft Enterprise Library

A great place to start is the application blocks in Microsoft’s Enterprise Library. These are application service components designed to follow Microsoft best practices and include modules for caching, cryptography, data access, exception handling, logging, policy injection, security and validation.

Website Starter Kits

Another good place to look is the ASP.NET Starter Kit Websites, a collection of working ASP.NET demos that can be examined or built on. They cover DotNetNuke, e-commerce with PayPal, blogging, project time management, media library and plenty more.

Codeplex

Lastly Codeplex, Microsoft’s open source project hosting site. There’s so much goodness here it’s hard know where to start, so try browsing the most popular or active projects to start. Here are the top ten that caught my eye:

  • BlogEngine.NET
    Full featured blog engine targeted at .NET developers. It is light weight and very simple to modify and extend.
  • Umbraco
    Simple, flexible and friendly ASP.NET CMS
  • DinnerNow
    Sample marketplace application designed to demonstrate how you can develop a connected application using IIS7, ASP.NET Ajax Extensions, Linq, WCF, WF, WPF, Powershell, and the .NET Compact Framework.
  • Community Kit for SharePoint
    Set of best practices, templates, Web Parts, tools, and source code for creating a community website based on SharePoint.
  • Facebook Developer Toolkit and Facebook.NET
    .NET wrappers and libraries for the Facebook API.
  • DbEntry.Net
    Lightweight, high performance Object Relational Mapping (ORM) database access compnent for .NET 2.0.
  • PublicDomain
    .NET packages for time zone support, logging, dynamic code evaluation, GAC API, unzipping, RSS, Atom, OPML, screen scraping, and utilities for strings, arrays and cryptography.
  • ASP.NET RSS Toolkit
    Gives ASP.NET applications the ability to consume and publish to RSS feeds.
  • NGenerics
    Class library providing generic data structures and algorithms not implemented in the standard .NET framework
  • Html Agility Pack
    Agile HTML parser that builds a read/write DOM and supports plain XPath or XSLT. The parser is very tolerant with “real world” malformed HTML. The object model is very similar to System.Xml, but for HTML documents.

If you know any other places to find good quality .NET source code then please leave a comment.

Fun Google Searches

It’s amazing how much cool stuff you can do with some of the lesser known Google Search features:

Got any more?

Task List comments in Visual Studio

Here’s a quick Visual Studio tip. You can embed useful notes and reminders in code using Task List comments like this:

// TODO: fix catastrophic memory leak

These notes will automatically appear in the Visual Studio Task List, which you can open with the shortcut Ctrl+W, T or by selecting View – Task List from the main menu bar.

Visual Studio Task List

Visual Studio also supports two other comment tokens, HACK and UNDONE. You can even add your own custom comment tokens in:

Options – Environment – Task List.

If the code and the comments disagree, then both are probably wrong

Let us change our traditional attitude to the construction of programs. Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.
— Donald Knuth

I recently wrote some code commenting guidelines to explain why comments are usually a Good Thing. Some intelligent and good looking people agreed with me, while others insisted sharing incoherent and rambling opinions.

Mads Kristensen rightly pointed out that, “If [comments] are good, then the code is also good”. Some people took this to mean that if a piece of code has good comments, then it’s also guaranteed to be of the very finest quality. There’ll always be exceptions. Code with good comments can easily be mutilated by a placement student or twisted beyond sanity by a crazed Perl developer. But good comments are often correlated with good code when the software is built by a good developer.

How about this one, “code should be written in a way that doesn’t require commenting”. Close, but wrong. Code should be written is such a way that it doesn’t require commenting to explain how it works. My original article wasn’t about refactoring, but if you have a block of code with a comment then sometimes it makes sense to extract it into its own method. If it still isn’t clear then try renaming the method. If you think you need a comment to note assumptions then state them explicitly by introducing an assertion. If there’s still any uncertainty then use comments. Explain obscure optimizations or special algorithms. Explain why you’re code does what it does.

Posted in .net. 3 Comments »

Convert table to CSV string in SQL Server

There doesn’t seem to be a native function in SQL Server to collapse a table of row values into a comma-separated string, for example:

Animal
Llama
Manatee
Pygmy Marmoset
Okapi

Result CSV: “Llama, Manatee, Pygmy Marmoset, Okapi”

In mySQL there’s a built-in aggregate function called group_concat, but no equivalent in SQL Server unless you build your own .NET function, like in this TechNet article Invoking CLR User-Defined Aggregate Functions. That’s quite a chunk of coding and is restricted to SQL Server 2005 or later, so here’s a handy SQL snippet that does a similar job without the fuss.

select Name from Animal

declare @csv varchar(max)
select @csv = coalesce(@csv + ‘, ‘, ”) + Name from Animal
select @csv

If you use the code regularly then consider creating a scalar user-defined function (UDF) that returns the CSV string as varchar.