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

CTP3 of the Windows Live™ Tools for Microsoft® Visual Studio® 2008 shipped last week.  This includes ASP.NET controls for both Virtual Earth and Silverlight Streaming.  The following two video-casts illustrate how you can get started with these two controls:

Dr Neil on the ASP.NET Silverlight Streaming control

Myself, covering the ASP.NET Virtual Earth control

Last week I talked about how useful the Immediate Window is during debug-mode. A less-known, but totally awesome, feature of the Immediate Window is that it can be used at design-time to test/debug your code. This is particularly useful if you are working on a particular class or method that you want to test without running the entire application.

The best way to understand this is to see it in action. The screenshot below shows a new Customer object being created in a C# project within the Immediate window.

Design Time Expression Evaluation in the Immediate Window

When you declare a new object in the Immediate window at design-time, Visual Studio will create an instance of that object. However even though it has created this object, Visual Studio will remain in design-mode (For those that are interested, it actually uses the Object Test Bench in the background). If you invoke a method or property that contains an active breakpoint, Visual Studio will change to debug mode and break at the breakpoint. Once you resume execution from the break Visual Studio will return to design-mode.

There are a few gotcha’s and caveats that you need to be aware of when performing design-time expression evaluation.

Firstly, within a Visual Basic project you can’t use an explicit variable declaration (for example, Dim myCust as Customer). Instead variables are declared implicitly using the assignment operator (for example, myCust = new Customer()).

Secondly, if you are using C#, IntelliSense is not available in the Immediate window during design-time expression evaluation. Visual Basic programmers are a little more spoilt, as they are given a limited form of IntelliSense here.

Thirdly, any statements you enter into the Immediate Window will be evaluated against whatever project is selected in the Solution Explorer. If no project is selected,Visual Studio will evaluate it against the startup project. If the code doesn’t exist is that project, you will get an error.

Finally, you can’t use design-time expression evaluation in any project that requires an execution environment. This includes Web projects, VSTO projects, Smart Device projects, and SQL projects. However as I mentioned earlier, the scope of this is per-project. Therefore, if you have a solution that contains a web project and a separate class library project for your business logic, you can use this method to test any of the business logic code.

Professional Visual Studio 2008 was officially published today and should now be in stock at your favourite online book store. If you’re an instructor at an accredited educational institution, you can request an evaluation copy from the publisher. Wrox also has a User Group Program, which allows your local user group to request a review copy of the book.

Once you get your hands on a copy of the book, don’t forget to download the associated source code from Wrox.

We’re also excited to announce that Wiley Publishing have advised us that it will be translated into Simplified Chinese. We will update you as soon as we hear any further information on the availability of that version.

We’ve requested some promotional copies from the publisher to give away to the readers of this website. The details of this are still being worked out, as we are hoping to ensure that it’s not limited to U.S. residents only. Stay tuned for more information on this in the near future.

We sincerely hope you find Professional Visual Studio 2008 to be a useful resource. We very keen to hear feedback on the book (both positive and negative), so if you have any comments or questions, please comment on a post in this blog or send us an email.

This post has been a long time coming, as I previously announced I would start this series following my user group presentation back in June. There’s a myriad of reasons why I let it go so long, however the impending release of Professional Visual Studio 2008 has kicked me into action.

For the first of what will become an ongoing weekly series of debugging tips I’d like to start off with one of my favourite windows in the whole of Visual Studio – the Immediate Window. This useful window can be used during both debugging and at design-time. The window is displayed using the keyboard shortcut Ctrl+Alt+I, or by selecting it from the Debug->Windows menu. You can also type immed in the Command window and it will display and switch focus to the immediate window.

Quite often when you’re debugging an application, you’ll want to evaluate a simple expression either to test a bit of functionality or to remind yourself of how something works. This is one situation where the Immediate window comes in very handy. This window enables you to run expressions as you type them, as shown below.

The Immediate Window

To make life easier, the Immediate window supports IntelliSense, and you can use the arrow keys to track back through the history of previous commands executed.

The Immediate window also allows you to execute any Visual Studio command. To submit a command you must enter a greater than symbol > at the start of the line. There is an extremely large set of commands available; in fact almost any action that can be performed within Visual Studio is accessible as a command. Fortunately IntelliSense makes navigating this list of available commands a little more manageable.

Nick blogged last year about aliases, which are available under both the Command and Immediate windows. One of the more well-known aliases is “?”, which is a shortcut for the Debug.Print command that prints out the value of a variable. As long as you have the Immediate window open, this is generally quicker and more convenient than bringing up a watch window, or hovering over a variable and waiting for the data tip to display.

If you start to become really dependant on the Immediate window for your debugging, you should consider enabling the option to Redirect all Output window text to the Immediate window. This option can be enabled under  Tools->Options->Debugging. Although the option says it redirects all Output window text, it will actually only redirect the debug messages (e.g. Debug.Print).

Debugging Tips and Tricks

Thursday evening I am presenting at my local .NET User Group on the topic of debugging. The title is “How to be a Debugging superhero”, and for the session I will be covering as many Visual Studio 2008 debugging tips, tricks, and best practices as I can fit into an hour. It should be a fun session (100% hands on) and I’ve also got a bunch of swag to give away, courtesy of the Microsoft Heroes {Community} Launch program.

For those who can’t make it to sunny Perth for the session, as of next week I will be starting an ongoing, weekly series of blog posts covering all of the debugging tips and tricks that I can lay my hands on. I wrote 5 chapters on debugging in our upcoming Professional Visual Studio 2008 book, so there is plenty of material for me to draw from.

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
« 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-2012 David Gardner, Keyvan Nayyeri, and Nick Randolph. All rights reserved.
Blog | Archives | Books | About | Contact