Archive for the ‘.NET Programming’ Category.

Inserting and Retrieving An Image In SQL Server 2005

If you’re looking for a solution to store and retrieve a picture from a table in a SQL Server 2005 database, I hope that these two functions (StoreImageInDatabase at line 4 and RetrieveImageFromDatabase at line 72) will satisfy your requirement. I had to implement such functionality in a project and decided to keep it here for further reference. It’s heavily commented for those developers that are taking their first steps with ADO.NET. Feel free to share your own implementation too. There are so many ways to do this.

/// 
/// Stores an image to the database
/// 
private static void StoreImageInDatabase( string imageFilename, ImageFormat imageFormat )
{
    // Make sure the image file exists prior to proceeding with the storage.
    // Note: The File.Exists method will return false whether the imageFilename parameter is null or empty.
    if ( !File.Exists( imageFilename ) ) throw new FileNotFoundException( “The image file was not found”, imageFilename );

    // Load the image from the filename received as a parameter.
    Image image = Image.FromFile( imageFilename );

    // Holds the byte representation of the image.
    Byte[] content;

    // Use a MemoryStream to store the image representation as stream of bytes.
    using ( var stream = new MemoryStream() )
    {
        image.Save( stream, imageFormat );

        // Convert the stream into an array of bytes because that’s the value we’ll pass to our SQL parameter.
        content = stream.ToArray();
    }

    // Our connection string (put it in your configuration file if needed)
    const string connectionString = “INSERT YOUR DATABASE’S CONNECTION STRING HERE”;

    // Create an SQL connection based on a connection string pre-defined (the using statement will close/dispose the connection on our behalf even if an exception should occur).
    using ( var connection = new SqlConnection( connectionString ) )
    {
        // The SQL statement/stored procedure used to store our image.
        // Just make sure that you have a parameter named ‘@PICTURE’ of type Image as well as a column named ‘PICTURE’ of type Image too in the table.
        const string sqlStatement = “UPDATE SOME_TABLE SET PICTURE = @PICTURE WHERE SOME_CONDITION”;

        // Create an SQL command based on our stored procedure and SQL connection.
        using ( var command = new SqlCommand( sqlStatement, connection ) )
        {
            // Explicitly state that we’ll be using a SQL statement or a stored procedure (CommandType.StoredProcedure).
            command.CommandType = CommandType.Text;

            // Define the SQL parameter which will hold our image to store.
            var parameter = new SqlParameter( “@PICTURE”, SqlDbType.Image )
                            {
                                    Value = content
                            };
            command.Parameters.Add( parameter );

            try
            {
                // Open the connection.
                connection.Open();

                // Execute the stored procedure to store our image in the database.
                command.ExecuteNonQuery();

                MessageBox.Show( “Image stored successfully”, “Image storage”, MessageBoxButtons.OK,
                                 MessageBoxIcon.Information );
            }

            catch ( SqlException ex )
            {
                MessageBox.Show( ex.Message, “SQLException”, MessageBoxButtons.OK, MessageBoxIcon.Error );
                // Other error handling, logging, etc.
            }
        }
    }
}

/// 
/// Retrieves an image from the database
/// 
private static Image RetrieveImageFromDatabase()
{
    // The image that will be retrieved
    Image image = null;

    // Our connection string (put it in your configuration file if needed)
    const string connectionString = “INSERT YOUR DATABASE’S CONNECTION STRING HERE”;

    // Create an SQL connection based on a connection string pre-defined (the using statement will close/dispose the connection on our behalf even if an exception should occur).
    using ( var connection = new SqlConnection( connectionString ) )
    {
        // The SQL statement/stored procedure used to retrieve our image.
        // Just make sure that you have a column named ‘PICTURE’ of type Image.
        const string sqlStatement = “SELECT PICTURE FROM SOME_TABLE WHERE SOME_CONDITION”;

        // Create an SQL command based on our stored procedure and SQL connection.
        using ( var command = new SqlCommand( sqlStatement, connection ) )
        {
            try
            {
                // Explicitly state that we’ll be using a SQL statement or a stored procedure (CommandType.StoredProcedure).
                command.CommandType = CommandType.Text;

                // Open the connection.
                connection.Open();

                // Execute the query and build a DataReader with the results.
                var reader = command.ExecuteReader();

                Debug.Assert( reader != null );

                // Since we only have one image stored in the table (this is an example after all…), we’ll only have one image to retrieve from our table.
                // If you have to retrieve one specific image (or more) from a collection of images in the table, then you can precise which one to retrieve via a parameter.
                reader.Read();

                // Since the only column of our table is used to store/retrieve an image, its column index is zero.
                // We simply cast that column into an array of bytes.
                var content = (byte[])reader[0];

                // Create a stream based on the entire content of our buffer.
                using ( Stream stream = new MemoryStream( content, 0, content.Length ) )
                {
                    // Write the content (array of bytes) to our stream.
                    stream.Write( content, 0, content.Length );

                    // Create an image object based on the stream.
                    image = Image.FromStream( stream );
                }
            }

            catch ( SqlException ex )
            {
                MessageBox.Show( ex.Message, “SQLException”, MessageBoxButtons.OK, MessageBoxIcon.Error );
                // Other error handling, logging, etc.
            }
        }
    }

    return image;
}

How do you construct your objects?

I love it when an object is designed in a way that allows me to use it without forcing me to ask or wonder how it should be initialized.  Good enough?  Ok, let’s go further…

Let’s start with a simple example of a Person class.  One way I could write the class is like this:

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    // No constructors defined means the compiler will create a default (parameterless) constructor for us.
}

All right, so if I want to use this class, I need to know or figure out which properties of my newly instantiated Person object to set before actually using it.  This is an important step, because if the object participates in some method that requests a valid value from one of its properties, and that property isn’t in a valid, coherent state, then we might not get the expected result and debugging the problem might be cumbersome.  In our case, since a Person object is fairly straightforward and common, we pretty much know that its FirstName and LastName properties should be set prior to use it.  But what about its Age?  Let’s suppose that the Age is as important as the FirstName and the LastName.  Let’s also suppose that there are a bunch of other properties that defines a Person, such as Weight, Height, EyesColor, HairColor, Cavities, Faith, etc.  How can we possibly know that we must set the Age property when IntelliSense gives us a myriad of other properties belonging to this object?  Frankly, we can’t, unless the author of the class tells us or it’s documented somewhere (but then again who documents code, right?).

I believe that if the author of the Person class had use an intention-revealing technique to design the class, such as Test-Driven Development, she probably would’ve thought about how to properly initialize the class.  But then again, even that depends on the developer’s experience, philosophy and imagination on designing object-oriented software.

When designing objects, it’s important to ask ourselves a few questions prior to coding.  For example, should we provide a parameterless constructor (which will force the clients of the object to properly initialize its members)?  Should we provide constructors which accept parameters to properly initialize the object so that it’s ready to be used?  Even that question forces us to ask whether or not we should fully or partially initialize the object. 

Whenever I instantiate an object, I like to know the information it needs to be properly initialized (ReSharper is pretty helpful in such a scenario).  In other words, I want to know the “what” NOW…not later.  Furthermore, I don’t want the clients using my object to think too much about these concerns either.  I just want them to instantiate the object and be ready to start using it.  Am I asking for too much here?  I don’t consider myself a good programmer if I remove the developer out of the “zone” whenever she uses my objects.  It’s like constantly turning on and off a lighting switch…it gets annoying…very annoying.  That being said, if I take our previous little example, I would design the Person class as the following:

class Person
{
    public Person (string firstName, string lastName, int age)
    {
        // Implementation…
    }

    // No more constructors…not even a default (parameterless) constructor.
}

This constructor implementation would be valid if I want this object to be initialized with a FirstName, LastName and Age upon instantiation.  How can I know whether or not this is a “good” practice?  In most cases, you can probably find the answer directly in the requirements document, but again I strongly believe that it depends on one’s own experience, philosophy and imagination with object-oriented design and programming.  Nevertheless, with the now refactored Person class, I can easily communicate to the client of that class what she needs to provide to the object for it to be properly instantiated and ready to use.  I don’t make her think…I don’t push her out of the “zone”.

Another way to think about it is that when you go to the bank to open a new account, the bank teller doesn’t just hand you over a new “empty” account.  First, she asks you a few questions and gets some information from you, such as your name, your address, your credit history, etc.  Does it make sense for her to ask those things?  Absolutely, because it makes sense in the process of creating a bank account.  Going back to our Person class, does it make sense for that object to ask you to provide a FirstName, LastName and Age information prior to creating one?  Well, it also depends on the process of creating a Person object in your business domain.  (Software development is a field where there’s a lot of those “well, it depends!” moments).

Let me wrap up this idea by giving you two more examples from the .NET Framework.  If you search for the “MailMessage” class with Reflector, you will see that there are two MailMessage classes in the search results (see the picture below).  One of these belongs to the System.Net.Mail namespace and another one belongs to the System.Web.Mail namespace.  They both provide the same functionality, but the one from System.Web.Mail is actually obsolete.  In fact, it’ll ask you to use the one from the System.Net.Mail namespace instead. 


Figure 1. Search results for “Mail Message” in Reflector
image

If we look at MailMessage from System.Net.Mail, we’ll see the following four constructors:

  • A public parameterless constructor which initializes an empty instance of it.
  • Another public constructor which accepts two MailAddress objects as parameters (one is the source MailAddress and another the destination MailAddress)
  • Another public constructor which accepts two string parameters (the source email address and the destination email address)
  • Another public constructor which accepts four string parameters (the source email address, the destination email address, the subject and the message body)

I can understand that providing multiple ways to instantiate such an object is required in this context, because this MailMessage object belongs to a framework and not a custom application.  As Kent Beck righteously points out in his latest book, “Implementation Patterns”, there is a big difference in the way objects are designed and built in a framework versus a custom application.  As you can see, these constructors are telling me what specific information I should provide them in order to instantiate a fully working object.

Now take a look at the obsolete MailMessage class from System.Web.Mail.  You might expect the same number of constructors as the one from System.Net.Mail.  Instead, this one only provides one constructor: the default parameterless one.  Oh boy!  Now, the client of this class must know which properties (Attachments, Bcc, Body, BodyEncoding, From, CC, etc.) to set before actually using the object.  She is getting out of her “zone”…the light bulb is flashing…it’s annoying.  Good thing this one is now obsolete.

I still see much code in custom application that doesn’t offer the developer the guidance to properly instantiate an object prior to using it.  This forces us to ask ourselves “Ok, now that I have instantiated this object, what exactly do I need to provide it with for it to work properly?”.  I hate asking myself these questions.  I just want to use the object.  I want to think about more important things that knowing which properties to set.  If you’re at this crossroad and need to know what kind of information should an object request in its constructor, writing a unit test for it prior to coding might reveal a powerful weapon to counter the never-ending battle in our minds when designing good objects.

What other tricks or ways do you know about writing good object constructors?

How to recursively traverse a DOM element in JavaScript

Suppose you want to traverse all the child nodes of a DOM element in order to do something with them, such as disabling them for example.  Here’s one way to do it.


In this example, the function that is responsible to traverse the DOM element’s child nodes and disable them is the recursive function EnableDisableDOMElement.  You have no choice but to use a while loop because you don’t know exactly the depth of each child nodes of every DOM element. 

You can use this code by calling the DisableDOMElementTree function (feel free to name it according to your intention) and pass it a DOM element as a parameter. For instance, in the onload event of the body element, you can call DisableDOMElementTree and pass it a valid DOM element which is the root of the elements tree. You can use document.getElementById with the name of a DOM element as a parameter to the function.

Hope it helps!

Null Coalescing Operator

I learned something new about C# 2.0 today while using ReSharper: the null coalescing operator which is represented by the ?? keyword.  According to the C# ECMA standard (p.63-64),

The result of a ?? b is a if a is non-null; otherwise the result is b.  Intuitively, b supplies the value to use when a is null.  When a is of a nullable type and b is of a non-nullable type, a ?? b returns a non-nullable value, provided the appropriate implicit conversions exist between the operand types.

In practice, the null coalescing operator can be achieved through the following refactoring (a simple ALT+ENTER which ReSharper will do this automatically for you.  It’ll ask you whether you want to “Replace ‘?:’-operator with ‘??’”).

object Foo()
{
  object someObject = getObject();
  return someObject == null ? “Object is null” : someObject; // <--- This statement will be refactored to use the null coalescing operator

  // Prefer the ternary operator over using conditionals for easy readability.
  // In other words, avoid writing the following statements:

  // if (someObject == null)
  //   return “Object is null”;
  // else return someObject;
}

This is how we can refactor the above method to use the null coalescing operator:

object Foo()
{
  object someObject = getObject();
  return someObject ?? “Object is null”; // <--- This is it.
}

In other words, if the left-side operand is null, the value of the right-side operand will be returned; otherwise the value of the left-side operand will be returned.

Microsoft releases .NET 3.5 SP1, SQL Server 2008 RTM and Entity Framework/Data Services

Microsoft released tons of good stuff (the kind your parents will let you have) today.

First of all, you can now download Microsoft .NET Framework 3.5 Service Pack 1.  According to Microsoft,

Microsoft .NET Framework 3.5 Service Pack 1 is a full cumulative update that contains many new features building incrementally upon .NET Framework 2.0, 3.0, 3.5, and includes cumulative servicing updates to the .NET Framework 2.0 and .NET Framework 3.0 subcomponents.

Also as stated by Microsoft,

.NET Framework version 3.5 Service Pack 1 provides the following new features and improvements:

  • ASP.NET Dynamic Data, which provides a rich scaffolding framework that enables rapid data driven development without writing code, and a new addition to ASP.NET AJAX that provides support for managing browser history (back button support). For more information, see What’s New in ASP.NET and Web Development.
  • Core improvements to the CLR (common language runtime) that include better layout of .NET Framework native images, opting out of strong-name verification for fully trusted assemblies, improved application startup performance, better generated code that improves end-to-end application execution time, and opting managed code to run in ASLR (Address Space Layout Randomization) mode if supported by the operating system. Additionally, managed applications that are opened from network shares have the same behavior as native applications by running with full trust.
  • Performance improvements to WPF (Windows Presentation Foundation), including a faster startup time and improved performance for Bitmap effects. Additional functionality for WPF includes better support for line of business applications, native splash screen support, DirectX pixel shader support, and the new WebBrowser control.
  • ClickOnce application publishers can decide to opt out of signing and hashing as appropriate for their scenarios, developers can programmatically install ClickOnce applications that display a customized branding, and ClickOnce error dialog boxes support links to application-specific support sites on the Web.
  • The Entity Framework is an evolution of the existing suite of ADO.NET data access technologies. The Entity Framework enables developers to program against relational databases in according to application-specific domain models instead of the underlying database models. For more information, see Getting Started with the Entity Framework. The Entity Framework introduces some additional features, including support for new SQL Server 2008 types, default graph serialization of Entities, and the Entity Data Source. This release of the Entity Framework supports the new date and file stream capabilities in SQL Server 2008. The graph serialization work helps developers who want to build Windows Communication Foundation (WCF) services that model full graphs as data contracts. The Entity Data Source provides a traditional data source experience for ASP.NET Web application builders who want to work with the Entity Framework.
  • LINQ to SQL includes new support for the new date and file stream capabilities in SQL Server 2008.
  • The ADO.NET Data Services Framework consists of a combination of patterns and libraries, which enable data to be exposed as a flexible REST (Representational State Transfer)-based data service that can be consumed by Web clients in a corporate network or across the Internet. The ADO.NET Data Services Framework makes data service creation over any data source. A conceptual view model of the underlying storage schema can easily be exposed through rich integration with the ADO.NET Entity Framework. Services created by using the ADO.NET Data Services Framework, and also compatible Windows Live (dev.live.com) services, can be easily accessed from any platform. For client applications that are running on Microsoft platforms, a set of client libraries are provided to make interaction with data services simple. For example, .NET Framework-based clients can use LINQ to query data services and a simple .NET Framework object layer to update data in the service.
  • Windows Communication Foundation now makes the DataContract Serializer easier to use by providing improved interoperability support, enhancing the debugging experience in partial trust scenarios, and extending syndication protocol support for wider usage in Web 2.0 applications.
  • The .NET Framework Data Provider for SQL Server (SqlClient) adds new support for file stream and sparse column capabilities in SQL Server 2008.

Second of all, if you have an MSDN Subscription account, you can also download SQL Server 2008 which is fully supported by Visual Studio 2008 and .NET 3.5 upon installing .NET 3.5 SP1.

Here are some links that might be of interest for you if you want to get up and running with SQL Server 2008:

Finally, the ADO.NET Team at Microsoft has also released Entity Framework and Data Services.  According to today’s blog post on their site,

The Entity Framework and Data Services raise the level of abstraction for database programming and supply both a new model-based paradigm and a rich, standards-based framework for creating data-oriented Web services. Powered by rich and integrated tooling, the new ADO.NET Entity Designer lets users instantly leverage the new model-based paradigm in their applications. With the ADO.NET Entity Designer, users can generate models & mappings from an existing database and also create models with complex inheritance hierarchies & mappings in an intuitive, easy to use graphical user interface well integrated with Visual Studio 2008 SP1. The new Entity Data Source Control lets users consume models in their web applications with ease.

Check out the Data Platform site to get the latest bits and information on Entity Framework and Data Services.

C# Search: The .NET developer search engine

As a software developer, you’ve probably heard on more than one occasion that "Google is your friend" when it comes down to searching for a solution to a problem, an algorithm, a tool, etc.  As a .NET developer, I cherish very much my friendship with Google’s powerful search engine.  It’s true that I love working with .NET, but sometimes trying to search for a specific thing for it on Google can seem like a daunting task when millions of search results are generated.  Unless you’ve mastered the power of the Google search engine, trying to find exactly what you need is pretty much like trying to look for a needle in a haystack.  And until Google’s search intelligence evolves to a state that it’ll know exactly what we’re thinking, we might as well know how to properly and easily search for things, especially when it comes down to .NET development.  And you know what?  There’s a new site that offers a better and easier way to search for .NET related material.  And you know what else?  It’s powered by Google’s search engine and filters.

C# Search filtersA former co-worker of mine, David Hervieux, was kind enough to use his time and smarts to put together the best .NET-oriented search site powered by Google: C# Search, also known as "The .NET developer search engine".  This search engine is really revolutionary because it helps us to narrow our .NET related search through well-defined sources: sites (like CodeProject, MSDN, DotNetSlackers, etc.), newsgroups, forums, etc. (take a look at the picture on right).  And with the power of Google behind it, you can expect the search results to not only be precise, but super fast!  If you’re accustomed with using SearchDotNet, you can think of C# Search as being version 2.0 of SearchDotNet.

A neat thing about this customized search engine is that when you choose the "Everywhere" item as the source, the search will be done in the same way as if you were performing a regular search on Google.  So what does this means?  Well, first of all, it means that you can set C# Search as your homepage if you’ve already set Google as your homepage since you’ll get the same functionality and more. Second of all, it means that you can use C# Search as the default search page within Visual Studio.  To do this, follow these simple instructions:

  1. Launch Visual Studio
  2. Go to Tools -> Options
  3. Expand the Environment node, then click on Web Browser
  4. Under the Search page replace whatever link is there for "http://csharpsearch.com/default.aspx "
  5. Press on the OK buton

The image below shows you the end result.

Setting C# Search as the default search page in Visual Studio

Firefox and Internet Explorer users can be more productive with C# Search by installing the search toolbars, as shown in the images below.

The Internet Explorer C# Search Toolbar
 

The Firefox C# Search Toolbar

Mmmmm…..I’m lovin’ it!

Reflector vs MSDN documentation

imageAccording to the MSDN documentation concerning the Title property of the HtmlHead class (in ASP.NET), this property “Gets the page title”.  But if you look closely at the syntax declaration, you can clearly see a getter and a setter for this property (look at the figure on the right).  In other words, that property description should have been “Gets or sets the page title” (it hasn’t been corrected in the documentation for .NET 3.5).  That being said, I assume more web developers are using the Title property from the Page class instead because its description clearly states that it “Gets or sets the title for the page”.  But if you disassemble that property with Reflector, you will clearly see that Page.Title actually calls Page.Header.Title in its getter and setter.  Therefore you CAN and SHOULD use Page.Header.Title to dynamically set your page title instead of Page.Title to prevent an extra invocation

What did this little “documentation bug” taught me?

  1. Pay attention when writing API documentation; even more if that API will be used by millions of developers.
  2. Reflector should be part of every developer’s toolbox because you just never know what a type, method or property is really doing (unless you coded it yourself)
  3. You should read the disassembled code of a method/property because the documentation associated with Reflector is still that of MSDN, and as we saw, it’s not perfect.

Using the “Source Control – Team Foundation” toolbar to perform common TFS operations on the current document within Visual Studio

If you happen to be using Visual Studio with Team Foundation Server (TFS) as the source code repository, you might be wasting your precious time in trying to find the specific file in the Solution Explorer that you want to perform some action against it (check out the file, check in the file, view the file’s history, etc.).  This is especially true for a solution which comprises a multitude of projects and a sea of various files.  FYI, I don’t pin the Solution Explorer when I code because I like to have the widest view on my code rather than to share the screen space on the structure of the solution, so it’s a pain to always display the Solution Explorer or use the File –> Source Control menu to perform a TFS operation on a current file.

Here’s a little trick that’s available for which allows you to perform common TFS operations against the current open document in Visual Studio.

  1. imageRight-click anywhere on the toolbar container and click on the Source Control – Team Foundation item (the list is in alphabetical order).  Peek on the huge screenshot on the right for guidance.
  2. You should now see the TFS toolbar (take a look at Figure 1 below) which allows you to perform common TFS operations to the current document.

Figure 1. The Source Control – Team Foundation toolbar
image

Starting from the left side, these different items allow you to:

  • Change Source Control
  • Get Latest Version (of the current document)
  • Get Specific Version (of the current document)
  • Check Out For Edit (of the current document)
  • Check In (the current document)
  • Undo Pending Changes
  • View History (of the current document)
  • Refresh Status (of the current document)

You shouldn’t need to use the Solution Explorer or use the File->Source Control menu to perform common TFS operations on the current document anymore.

Juval Löwy on the importance of interface-based programming (TechEd 2008)

At this year’s TechEd conference, Juval Löwy was interviewed on the principle of interface-based programming vs coding to abstract classes.  Not many .NET developers know the difference between an interface and an abstract class, and even less when and why to prefer one to the other (hhmmm…sounds to me like a good post to write soon).  If you didn’t get a chance to hear his full talk on the subject at Tech Ed 2008, I strongly suggest to invest 16 minutes today to watch this interview.

Go to your project’s output directory directly by using Windows Explorer as an External Tool (Visual Studio)

Let’s keep this one short and sweet.

In your Visual Studio 200x, go to the External Tools window (under the Tools menu).  Then click on the Add button and enter the following information in each fields:

  • Title: Go To Build Output Directory (Windows Explorer) (feel free to change the title to suit your needs)
  • Command: c:\windows\explorer.exe
  • Arguments: /select, "$(TargetPath)" (don’t forget the double quotes)
  • Click on OK.

image 

A Cheat Sheet On .NET Framework Design Guidelines

Krzysztof Cwalina has published a condensed version of the Microsoft .NET Framework Design Guidelines which he co-authored with Brad Abrams a couple of years ago. You can find the Framework Design Guidelines Digest here as a PDF file (9 pages long). The document is very useful if you desire to set up a standard, practical and ubiquitous approach of programming with .NET in your own organization in no time and without much effort (the job is already done for you!).

Better Modelling with the Visual Studio Class Designer

As you may have experienced whenever modelling any kind of software design, it gets pretty hard to keep the model in-sync with the software as the code changes over a period of time.  It’s even harder to keep both updated if you’re modelling with a different, independent application than your IDE. 

Today, for the very first time, I was playing around with the Visual Studio 2008 Class Designer.  I’ve been using Sparx’s Enterprise Architect for a number of years, but I wanted a better way to keep my design in-sync with my code inside the IDE.  The major problem with the Visual Studio Class Designer is that it lacks some fundamental features that should appear on a UML class diagram such as associations between classes

Well, you might be delighted to know that there’s a neat project on CodePlex that fulfills this need. That project is PowerToys for the Class Designer and Distributed System Designer.  Here’s its description:

This set of add-ins augments existing functionality in the Visual Studio Class Designer and the Distributed Systems Designers. It now supports Visual Studio 2005, Visual Studio 2008. The Design Tools Enhancements add-in provides a common set of features that can be used by both the Class Designer and the Distributed System Designers, such as pan/zoom window and rich formatting commands. The Class Designer Enhancements add-in provides additional functionality for the Visual Studio Class Designer, such as HTML export and nested type creation commands. This download includes all necessary source code and a Visual Studio project template for creating your own add-ins for the Visual Studio designers. The Class Designer is a developer productivity tool available in Visual Studio Standard Edition and above, which allows developers to easily visualize, design, refactor, and document their code. The Distributed System Designers enable software architects, operations managers, and developers to visually design service-oriented solutions and validate them at design time against their operational environments. The Distributed System Designers are a core component of Visual Studio Team Edition for Software Architects and the Visual Studio Team System.

Even though the description says that it supports Visual Studio 2005, the latest release only supports Visual Studio 2008 (Professional edition or higher).  I haven’t tried it in Visual Studio 2005 (but if you did, feel free to post a comment on your experience with this PowerToys on VS2005).

P.S To show the associations between classes inside the Class Designer, simply right-click on a class attribute or a property, then click on Show as Association or Show as Collection Association, depending on the type.  Sweet!