Professional Visual Studio
Tips, Tricks, and Best Practices for professional .net developers

Professional Visual Studio 2008I’m very pleased to announce that all 965 pages of Professional Visual Studio 2008 have been written, edited, and handed to the production team. This means that it should still be available on its scheduled release date (28th July 2008).

The last five months have been pretty hectic for both Nick and I, as Visual Studio 2008 has consumed most of our waking hours in one way or another. Visual Studio has even entered my dreams a couple of times, but I’ll save that story for my therapist ;-) Writing a book while maintaining a full-time job was certainly very challenging, but I’ve learnt so much that I never would have found the time to learn otherwise.

We were also lucky to have three excellent guest authors on this book - Miguel Madero, Keyvan Nayyeri, and Joel Pobar. Miguel wrote 5 chapters on the different Team System Editions and TFS. Keyvan authored 3 chapters on Automation and also helped out as a technical editor on a bunch of chapters. Joel contributed a chapter that explained the different types of programming languages (imperative, declarative, dynamic, and functional) that included a great walkthrough of F#.

While I’m going to take it a little easier for a couple of months now, I now finally have time to share some of the things that I’ve discovered over the last few months.

Doug Hodges One of the newest videos on Channel 9 is dedicated again to Visual Studio Extensibility. In this video Ken Levy interviews Doug Hodges about the history of Visual Studio Extensibility.

Doug is a Principal Architect on Visual Studio platform and this interview is a very nice overview of VSX history during the past years. Visual Studio is one of the very old products of Microsoft and has evolved in these years.

This is yet another video about VSX on Channel 9 and it’s interesting to see the growing number of such videos. The text transcript of this interview is also published on CoDe Focus magazine.

Probably you know that Visual Studio, this popular and common development IDE for .NET developers, is over 11 years old and has been an IDE for development from the early days.

When Visual Studio was created originally, the common development technologies were all based on COM programming so Visual Studio was created based on a COM infrastructure.

Those days this wasn’t anything uncommon or special and all developer around the globe were using it. After the birth of .NET technology and its new infrastructure that is completely different from COM, Microsoft didn’t rewrite its IDE to be compatible with new stuff and just applied and updated the existing IDE for .NET development.

Here (the birth of .NET) was a point that changed many things around this IDE. Regular development scenarios and many developers don’t notice the side-effect of keeping the COM nature of Visual Studio but the fact is that this COM nature is now showing its bad effect on this IDE from the extensibility point of view.

Visual Studio is strongly correlated with its COM infrastructure and almost everything is an implementation of an interface. Microsoft has tried to adapt the existing IDE for newer technologies and hide the core API to some extent.

On the other hand, Visual Studio IDE for .NET development (versions 2002, 2003, 2005 and 2008) are great examples of interoperability between .NET and COM in its highest level.

By the way, this wouldn’t be important for anyone but two groups of developers. First groups are those who work at Microsoft to add new features for development to it and the second group are VSX developers. Both groups of developers should deal with extensibility features of VS and lower levels of its API.

If you begin working with Visual Studio Extensibility then you will notice the side-effect of this COM nature after a short while. Here those who don’t have a good background in COM programming, have some difficulties to learn VSX and this is a negative point for VS because new age of developers wouldn’t know much about COM.

One of the good strategies that Microsoft is considering for VS is hiding the lower level APIs from developers who want to extend Visual Studio just by building a .NET infrastructure on top of these APIs. For instance, when you work with code snippets or Visual Studio templates, you don’t deal with anything related to these low level APIs at all.

But unfortunately this is just for some stuff that aren’t strongly correlated with low level API. So all professional VSX developers have to work with COM-related stuff and this is one of the main negative points that a newbie faces with!

I guess I’d better come clean in case people weren’t paying close attention and took me seriously on my Useful .NET coding tip post. Yesterday was April 1st and this was my addition to the general fun and trickery.

There were some subtle clues due to the very silly statements I made in the post:

“Whilst this implementation might have been ok back in the late 90’s”

[Editors note: The first version of .NET wasn't released until 2002]

“…the sender parameter is the one you want, as it will give you the details on who invoked the event (i.e. who was the “sender”)”

“…as you probably know string comparisons can be very slow, so for performance reasons I recommend you compare the User property.”

and this one which is my favourite, because it is so wrong, but sounds like I know what I’m talking about:

“…Windows XP Service Pack 2, which changed the code for the WindowsIdentity class from running in User mode to running in Kernel mode.”

Hopefully my somewhat dry sense of humour didn’t catch anyone too much off guard. As far as April Fools Day jokes go, the clues on this one weren’t particularly obvious, so don’t feel bad if you weren’t paying enough attention to realise. I solemnly promise that everything I post from now on will be totally legitimate with no trickery involved (for the next 364 days at least)!

The other day I found myself explaining a solution to a .NET coding issue that seems to pop up from time to time, particularly with those new to WinForms programming. Since there doesn’t seem to be particularly good search results pointing to a solution elsewhere, I thought I’d share it here.

The Scenario

You have a control on a form, say a Checkbox, that you need to set to a specific value when the form is opened. However you also have a handler attached to the changed event that needs to take action when the user checks/unchecks it. Here’s what a (obviously simplified) typical implementation of this would look like in Visual Basic:

Public Class Form1
  Private Sub Form1_Load(ByVal sender As Object, _
                         ByVal e As System.EventArgs) _
                         Handles Me.Load
    Me.CheckBox1.Checked = True
  End Sub

  Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _
                                       ByVal e As System.EventArgs) _
                                       Handles CheckBox1.CheckedChanged
    If Me.CheckBox1.Checked Then
      MessageBox.Show("I've been checked!")
    End If
  End Sub
End Class

Any guesses as to what’s going to happen here? You’ve probably worked out that when you set the CheckBox1.Checked value to true in the Form1_Load() method, it will cause the CheckBox1.CheckedChanged event to be fired, thereby running your logic.

This is probably not what you wanted to happen. What you want is some way of distinguishing whether the checkbox was changed by an end user, or programmatically by the application itself.

The Solution

There are several ways to code around this, including some really nasty hacks involving the AddHandler/RemoveHandler statements. However if you look at the parameters on the CheckedChanged event hander, you might get a inkling as to what is the most elegant solution for this.

Yes, it’s the sender parameter. This little beauty is often overlooked in favour of the usually quite useful EventArgs parameter. However in this particular case the sender parameter is the one you want, as it will give you the details on who invoked the event (i.e. who was the “sender”).

Now you may have noticed that the sender parameter is of type System.Object. This is where the really elegant part of the solution comes into play. What you need to do is attempt to cast the sender object to a System.Security.Principal.WindowsIdentity, which is the class that represents a Windows user. Make sure you use the TryCast statement (”as” keyword for you C# developers) so that it doesn’t raise an exception if the conversion fails. As long as the TryCast doesn’t return Nothing, you know the checkbox was changed by a user.

Now don’t go and implement it just yet! As regular readers know, I have a fairly strong interest in security. Whilst this implementation might have been ok back in the late 90’s, these days with all the spyware, malware, and viruses that are infecting end users machines it would be wise to include a little bit of defensive programming here.

So how do we know whether the checkbox was changed by a “real” user, as opposed to some nasty malware that is impersonating the user?

It turns out to be quite simple. All you need to do is compare the WindowsIdentity that you retrieved from the sender with the WindowsIdentity that is returned by a call to System.Security.Principal.WindowsIdentity.GetCurrent(). You can use the Name property for the comparison - that will return the username as a string in the format domain\username. However as you probably know string comparisons can be very slow, so for performance reasons I recommend you compare the User property, which returns the SID of the Windows account. If they match then it was changed by the real user.

Now hang on a minute I hear you say. What’s to stop the malware from hijacking the System.Security.Principal.WindowsIdentity.GetCurrent()?

Well in 2002 Microsoft completely reviewed the security of Windows XP as part of their Trustworthy Computing initiative. We reaped the rewards of that review starting with Windows XP Service Pack 2, which changed the code for the WindowsIdentity class from running in User mode to running in Kernel mode. That means unless it’s a rootkit, there is no way that any malware can hijack this call. So as long as your users are running Windows XP SP2 or later, this code is secure.

I know all of the above sounds pretty complicated for such a seemingly simple issue, but if you spend any time trying to get the alternative hacks working, you’ll quickly realise that this is the most elegant solution. You might even want to create a Code Snippet for this, to save yourself some time in the future.

So here’s the final implementation of this solution. Fast, reliable, and secure.

Public Class Form1
  Private Sub Form1_Load(ByVal sender As Object, _
                         ByVal e As System.EventArgs) _
                         Handles Me.Load
    Me.CheckBox1.Checked = True
  End Sub

  Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, _
                                       ByVal e As System.EventArgs) _
                                       Handles CheckBox1.CheckedChanged
    Dim senderUser As System.Security.Principal.WindowsIdentity
    Dim actualUser As System.Security.Principal.WindowsIdentity
    senderUser = TryCast(sender, System.Security.Principal.WindowsIdentity)
    actualUser = System.Security.Principal.WindowsIdentity.GetCurrent()

    If senderUser IsNot Nothing AndAlso _
       senderUser.User = actualUser.User Then
      'This is a real user!!
      If Me.CheckBox1.Checked Then
        MessageBox.Show("I've been checked!")
      End If
    End If
  End Sub
End Class

A few minutes ago Visual Studio Ecosystem team introduced a new blog named VSX FAQ Blog.

This blog, which is hosted on MSDN blogs, acts as the FAQ of the Visual Studio Extensibility for developers.

As Ken has written in the announcement, this blog (or FAQ) is very useful for scenario-based references where people are looking for answers to common scenarios.

This is another good step forward to the Microsoft’s big plans for VSX in 2008. Such a rich FAQ can help developers a lot.

Brad Abrams has the Silverlight v2 Poster that was so popular at Mix08 available for download.

Silverlight MIX08 (Controls 5_1)

If you are following Silverlight or other technologies that were hot topics at Mix08 then make sure you checkout the recorded sessions.

Wrox Professional Visual Studio Extensibility

As I wrote on my main blog, my book, Professional Visual Studio Extensibility, officially released today and you can order it on Wiley or Wrox sites. There are already sample PDF files and code downloads for the book available on these sites.

It should be also available on Amazon and Barnes and Novel shortly and those who have pre-ordered it should receive it in next couple of weeks.

I’ve written more details about the book on my blog that you can read there. It’s a pleasure to finally see the book getting out to markets and finding its way to bookshelves. Readers of this blog who had left comments to receive free copies of my book and got my confirmation should receive their copies in a few days because they will be sent today or tomorrow.

I’m looking forward for feedbacks from readers. Some reviews will be published on .NET communities and blogs in next couple of months that can help others to decide whether they want to order my book.

I have to thank Nick and Dave for helping me on book promotion on this blog. We will be able to get our hands on Professional Visual Studio 2008 in a few months which is a great complementary for my book.

Last week the beginning of the official Visual Studio 2008 launch wave began.  Combined with the launch of Windows Server 2008 (and Vista SP1) and SQL Server 2008 (although not due for release until late this year), this series of events should really encourage developers to take a look at the new product.

Across in New Zealand Microsoft has partnered with local website Geekzone for a limited time Visual Studio 2008 blog.  For the month of March there will be a number of permanent posts that will discuss various aspects of Visual Studio 2008.  Whilst we will attempt to keep an index of these topics, I suggest that you head over to the Visual Studio 2008 Geekzone blog and add it to your favorite RSS reader.

Today Visual Studio Ecosystem team announced the availability of PowerCommands for Visual Studio 2008 as a free set of extensions that brings lots of helpful features to Visual Studio IDE. These commands are available with source code to let you learn how to develop new commands or modify them. Some of these features are a part of some editions of Visual Studio 2008 and you can bring them to other editions via these commands.

You need to have Visual Studio 2008 SDK 1.0 installed to be able to open the source code for these commands.

A short list of features that are provided by this project are:

  • Collapse Projects
  • Copy Class
  • Paste Class
  • Copy References
  • Paste References
  • Copy As Project Reference
  • Edit Project File
  • Open Containing Folder
  • Open Command Prompt
  • Unload Projects
  • Reload Projects
  • Remove and Sort Usings
  • Extract Constant
  • Clear Recent File List
  • Clear Recent Project List
  • Transform Templates
  • Close All

You can download the package that contains the source code of PowerCommands from the announcement post.

« Previous PageNext Page »


About this site

Professional Visual Studio aims to provide tips and tricks, traps to avoid, and industry best practices from experienced .NET developers on using Visual Studio in the most effective way possible.

Copyright © 2007-2008 David Gardner, Keyvan Nayyeri, and Nick Randolph. All rights reserved.
Blog | Archives | Books | About | Contact