Measure Performance with the Stopwatch Class

I like it when my code runs faster, but I don't want to work at it (if my application is running too slow, my time is usually better spent enhancing my data access rather than tweaking code). But if I do rewrite any code to make it run faster, I want to know that I made a difference. This has led me, after all these years, to the System.Diagnostics.Stopwatch class.

To use the Stopwatch class, just call its StartNew method, run your test, then call its Stop method. You can extract the elapsed time from the Stopwatch's ElapsedMilliseconds property then display it or write it to a log file. This example puts the result in a TextBox:

Dim  sw As System.Diagnostics.Stopwatch 
sw  = System.Diagnostics.Stopwatch.StartNew()
…something  to test…
Me.TextBox1.Text  = String.Format("Elapsed time: {0} ms", timer.ElapsedMilliseconds)
There are methods on the StopWatch class to reset the timer (so you can do another test) or restart the timer (so you can continue the current test). You can also get the elapsed time in Ticks or, for long running tests, as a TimeSpan object with hours, minutes, and (horrors!) days.

Posted by Peter Vogel on 03/21/2013 at 1:16 PM0 comments

Free Visual Studio Tool: Brace Completer

When I work in Visual Basic and add an If statement, Visual Studio writes the End If statement; If I add a Class declaration, Visual Studio adds the End Class statement. Why, then, when I work in C# and I type an open brace, doesn't Visual Studio write the closing brace?

In fact, C# will stubbornly mark my line as an error until I do add the closing brace (often hiding some real error). When you do finally type the closing brace in C#, Visual Studio formats the code -- that's got to be harder than adding the brace. That's why, whenever I type an opening brace, I immediately type the closing brace to reduce my chances of having a mismatched brace. Having Visual Studio add the brace would fit right in with my standard practice.

The Brace Completer extension does what I want: when I type an opening brace and hit the Enter key, Brace Completer adds the closing brace, lets Visual Studio format my code according to my settings, and then puts my cursor on the line following the opening brace.

If you're not happy with the default behavior, you can configure the utility from the Tools/Options/Environment/Brace Completer menu choice. Brace Completer does the right thing for C#, C/C++, CSS, and JavaScript; and if you're feeling brave, it's willing to support any other language known to Visual Studio that you might select in the Options dialog. You can also configure Brace Completer to insert the closing brace as soon as you type the opening brace, if you're one of those people who occasionally want to keep everything on one line (and, when you do finally hit the Enter key, you'll get the default formatting expected).

It doesn't seem like a big deal, but I like it very much. I know that it's only saving me one keystroke, but that's one keystroke every time I use a brace. I don't know what that is over a day, month or year, but I bet it's a ton of keystrokes. And, sure, there may come a time when I'll wish that Brace Completer hadn't added the closing brace -- but it hasn't happened yet.

You can find Brace Completer in the online section of Visual Studio's Tools/Extensions and Addins.

Posted by Peter Vogel on 03/18/2013 at 1:16 PM3 comments

Visual Studio Tip: Printing Code to Support Code Review

I don't often print my code out when I'm working at home (too cheap to pay for the ink), but it's something that my clients ask for more often than I expect. The usual reason I'm asked to print my code is to support a code review. By default, the printing process uses the same settings your code editor does, which isn't always appropriate. When you print out your code, you should set up your pages to support the code review process.

There are two obvious options to pick when printing your code, because they appear right in the Print dialog. In the lower left-hand corner of the dialog, you can check off the option to hide collapsed regions, a good way to focus the reader's attention on the code that's being reviewed by collapsing the irrelevant parts of your code before printing (and save some ink!). You can also check off an option to include line numbers, which makes it much easier to refer to specific lines of code.

In the Page Setup dialog, there's another option that's worth checking (it's set by default in some versions of Visual Studio): Page Header. That will print the full path name for the code file at the top of each page, making it easier to refer to code files (and collate your pages if you drop them).

But there's more you can do: Go to Tools/Options/Environment/Fonts and Colors and set the dropdown box at the top of the dialog to Printer. Now you can set up your print options to support your code review. For instance, several studies have shown that serif fonts (like Courier New) are easier to read on paper than san-serif fonts (like Visual Studio's default Consolas): change the font to a monospaced serif font (the monospaced fonts are in boldface). There's not much point in highlighting breakpoints in the printed code, so you might also want to set breakpoints to plain old black on white.

That's just a start on what you might want to change, but you've already focused the reviewer's attention, made it easier to find what you're talking about, made it easier to read, and got rid of an annoying distraction. Not bad for five minutes' work.

Posted by Peter Vogel on 03/14/2013 at 1:16 PM0 comments

Create a SharePoint List in Visual Studio 2012

The problem with creating SharePoint WebParts or pages in Visual Studio is that most of your code will depend on some other resource in your SharePoint site -- typically, a List. If the List has to be deployed as part of installing your application, you have three choices: define your list in CAML (ugly), create your list in your development SharePoint site and export it to your Visual Studio project (awkward, but my preferred method), or create the List in the SharePoint site through the SharePoint UI (not a bad plan, provided you're only installing to one site and you remember to do it).

With Visual Studio 2012 and SharePoint 2013, you have a better choice.  After installing the SharePoint 2013 Development Tools, you can create an empty SharePoint project and add a SharePoint List to it (the SharePoint project and project item templates are now listed in an Office/SharePoint category in the Add Project Item category). When you add a List project item, you get a chance to pick the template you want to base your new List on, either as a customizable or non-customizable List.

If you pick a customizable template, you can select which columns from the template you want to use, change the display names for columns or add existing Content Types to your List. You can also pick which Views you want to make available to the List, set the title and URL, and specify whether the list appears in the Quick Launch menu (or is hidden from the browser). It's not as powerful as the List editor built into SharePoint, but it's pretty good.

Here's my tip: I'm not saying that building Lists in Visual Studio is a "good enough" reason to upgrade to either SharePoint 2013 or Visual Studio 2012. But it's a compelling one.

Posted by Peter Vogel on 03/06/2013 at 9:03 AM0 comments

Free Tool: Hide the Main Menu

Earlier this week, I had the world's simplest tip; here's the world's simplest Add-In: Hide Main Menu (you can find it in Extension Manager). It removes the main menu from Visual Studio (you know: the "File…Edit…View" menu) giving you one more precious line in your code editing window. If you don't use the mouse and do always use the shortcut keys, you may never know the menu's missing.

You can get the menu back by pressing the Alt key; so if you're a mouse-oriented person, you'll need to learn to press the Alt key as you move your mouse to the top of the screen (easier for people holding the mouse in their left hand, I imagine). Or you can make more extensive use of the icons on the toolbars, which do remain on the screen.

Or you may just discover that you don't actually use that main menu much.

Posted by Peter Vogel on 02/28/2013 at 1:16 PM1 comments

Use Find Definition with CSS Class

Simplest tip ever: Use Visual Studio's Go To Definition with CSS classes to get from your HTML to the relevant CSS rule. First click on the name of a class in your HTML:

<div class="error" …

Then press F12 (or right-mouse click and select Go To Definition) and, voila, you're in the right style sheet with your CSS class rule selected. It also works with the CssClass attribute:

<asp:Label  ID="BodyContent"   cssclass="error" …

Posted by Peter Vogel on 02/26/2013 at 1:16 PM0 comments

Initialize Any Collection, Including Your Own, in One VB Statement

Most Visual Basic developers are aware that they can declare and initialize an array in one statement like this:

Dim  csts() As String = {"A123", "B456"}

What you may not know is that, as of Visual Basic 10 (.NET Framework 4/Visual Studio 2010), there's a variation on that syntax you can use to initialize collection: Just insert the keyword From between your collection declaration and the initialization list (the stuff in the curly braces).

For instance, this code initializes a List of Customer objects (each Customer object is defined by passing a CustomerID when creating the Customer object):

Dim  csts As New List(Of Customer) From 
  {New Customer("A123"), New  Customer("B456")}

This example does the same thing, but calls a factory method that returns Customer objects

Dim  csts As New List(Of Customer) From 

To initialize a Dictionary that uses strings for its keys and Customer objects for its values, all you need is a few more curly braces to mark off each item in the list:

Dim  csts As New Dictionary(Of String, Customer) From 
{{"A123", New Customer("A123")}, {"A456", New Customer("A456")}}

The From keyword can be used with any collection that implements the IEnumerable interface (or has a GetEnumerator method), and has an Add method that can use the From keyword. The From keyword uses the IEnumerable interface as evidence that the object is a collection, and then calls the Add method for each item in the initializer list.

If you're creating your own collection class, you can let developers use the From keyword with your class by implementing the IEnumerable interface and having a method called Add that accepts a single parameter (or however many parameters each item in your collection requires).

If you're working with a collection that doesn't have an Add method, you don't have to rewrite the collection class; just create an extension method for the class that puts new items in the collection, and call that method Add. This extension works with the Queue class to give it the ability to use the From initializer syntax by wrapping its Enqueue method inside an Add method:

Module  PHVExtensions
  Sub Add (ByVal q As Queue, ByVal itm As Object)
  End Sub

End Module

Posted by Peter Vogel on 02/21/2013 at 1:16 PM3 comments

Keep Methods Focused to Support Re-use

You may have seen a method that has two or three required parameters and half-a-dozen optional Boolean parameters. On investigation, you discover that the optional parameters each turn off some processing that the method would normally perform (typically, these parameters have names like NoUpdate, SkipAudit). This is evidence of a failure in designing the method.

What's happened here is that a developer originally wrote the method to do 13 things -- but then all the other developers who used that method asked for the ability to turn off some of those 13 things. So one by one, those Boolean parameters got added. And, with each new option, the code in the method became more complicated and harder to debug (or test).

It may seem like a good idea to create one method that takes care of 13 things. For instance, a method for purchasing a product might have all the code to check that the product is in stock, to decrement the quantity of the product on hand, to create a new line on an order (and create the order if it doesn't already exist), to write a log record to the audit trail, and so on. But what if a developer wants to call your method and only wants to do 12 of those 13 things? For instance, when the customer is buying a service (rather than a physical product), there's no stock to check or inventory to decrement. A developer supporting buying services will want to turn that functionality off in the purchase product method.

The "single responsibility principle" is usually discussed in terms of objects, but it's actually more obvious in methods. A method that does exactly one thing (that has a single responsibility) is probably easier to write and understand (and certainly easier to test) than a method that does many things. More importantly, that method is more useful: Developers can mix and match whatever "single responsibility" methods they need to get the result they want. So, instead of building one big method, you're better off building 13 more focused methods: A method to check stock, a method to decrement inventory, a method to create a line on the order, and so on.

But, you may say, the typical activity is to do those 13 things. If that's the case, then there's nothing stopping you from creating a new method that calls the 13 individual methods in the right order to do the "typical" thing. Developers doing the "typical" thing can call your new method (which is, by the way, an example of the Façade pattern). But developers still have the ability to mix and match the other 13 methods when they want to do something "un-typical."

Posted by Peter Vogel on 02/19/2013 at 1:16 PM7 comments

Stop Debugging Code that Works

We all have utility methods that just work. But if you're in Debug mode and stepping through your code (and you forget to shift from using F10 to F11), you end up having to step through your utility method.

Of course, once you're in the method, you can use F7 to step out of the method and onto the statement following the statement that called your utility method. But it would be much better to just not step into the method at all.

That's easily done: just add the System.Diagnostics.DebuggerStepThrough attribute to your method. The next time you're stepping through your code, Visual Studio will just step over your method. Just remember to take the attribute off if you want to put a breakpoint in your utility method: Visual Studio takes this attribute very seriously and ignores breakpoints inside methods decorated with DebuggerStepThrough.

Posted by Peter Vogel on 01/31/2013 at 1:16 PM1 comments

Visual Studio Tip: Get Back Previous Versions

You've just deleted an item in Solution Explorer and realized that you still needed it. Or, after mucking with some code for several days, you've realized that the original version was the right answer. If you've got source control in place, you can use it to get out of the hole you've dug yourself into. Or, you can just get the file back with Visual Studio, if you're running on Windows Vista or Windows 7.

This is actually a Windows Vista/Windows 7 feature (in everything higher than the Home version). but Visual Studio takes advantage of it. If you pick Open Project, for instance, the Open button in the resulting dialog will have a down arrow beside. Clicking that arrow offers a new choice: Show Previous Versions. Selecting that choice changes the file list displayed in the dialog to show the previous versions of the files in the folder, organized by date. You can then grab the previous version of your project and get your file.

Posted by Peter Vogel on 01/29/2013 at 1:16 PM2 comments

Free Tool: Automated Testing with Moles and Pex in Visual Studio 2010

In an earlier set of articles, I showed how to use Microsoft's Fakes Framework and complained about how Fakes is only available in the Ultimate version of Visual Studio 2012. And that's true; but for Visual Studio 2010, Microsoft also has the Moles Isolation Framework for .NET. Moles is similar to shims in the Fakes Framework but, unfortunately, won't see any future development (it's been replaced with Fakes). Still, Moles does work and you can use it for free, even for commercial projects.

But Microsoft has a related tool for addressing a different problem: missing tests. As developers, we tend to test code to make sure it works -- we feed in the results we wrote the code to handle. So Microsoft has a companion to Moles and Fakes called Pex. Unfortunately, to use Pex you must either be an MSDN subscriber or use Pex under the academic license (i.e., not for commercial use).

Pex is a test generator: aim it at your application and Pex generates test cases for you. Pex does that by examining your code and then generating tests that ensures, among other things, every line gets executed. Pex is particularly interested in generating "edge cases": what happens at the outer limits of the ranges you've built into your code. So, for instance, string variables will be tested with null/Nothing values, zero length strings, escape characters, and strings of punctuation marks.

You need to beware of something here: If your code is accessing database or a Web Service, Pex's tests could take a very long time. If your code is performing updates, you could end up with a lot of "interesting" data in your database (e.g. null/Nothing values, zero length strings, strings of punctuation marks). This is, of course, why Pex comes with Moles or Fakes: you really need to isolate your code from your database before running Pex.

You can download Pex through Visual Studio's Extension Manager. After isolating your code, right-mouse click in the method you want Pex to generate tests for and select Run Pex. Then wait. As it's running, Pex will display a table of the inputs it's feeding to your code and the output from each test, including any exceptions. The Pex Explorer window gives you a TreeView of the test results that complements the table view.

Once Pex is finished beating up on your code (Microsoft refers to this as "Pex Explorations"), you can review the results. You can, with a mouse click, save any one or all of Pex's tests as a Visual Studio test; if a test generates an exception, have the generated test accept that exception as an expected result of the test. Alternatively, for any test, you can have Pex write a pre-condition into your code (Pex adds code to your method that tests for that input and throws an exception if it turns up).

If you want to make sure that all the conditions that you wouldn't normally think of are applied to your code (and are an MSDN subscriber or a non-commercial developer), you should take Pex out for a spin.

Posted by Peter Vogel on 01/22/2013 at 1:16 PM0 comments

Picking Overloaded Methods at Runtime (Multiple Dispatch)

I don't spend a lot of time interacting with dynamic languages like Python, but I think that I've finally found a use for the dynamic keyword in C#. It's something that C++ developers call "multiple dispatch" (or so I'm told).

Normally, if you call a method that that has two overloaded versions, the choice between the two overloads is made at compile time, based on how the parameters passed to the method are declared. But, by using the dynamic keyword, you can defer the choice between the two methods until run time and have the choice based on the datatype of the data in the parameters, instead of on the way the parameters are declared.

For instance, assume two classes: one called BaseCustomer and another called PremiumCustomer that inherits from BaseCustomer. Also assume a method with two overloaded versions: one version that accepts a Customer object and one that accepts a PremiumCustomer object. Here are the two methods:

public void ProcessCustomer(Customer cust)

public void ProcessCustomer(PremiumCustomer cust)

Now, here's some code that calls the two versions of the ProcessCustomer method. Guess which version is called each time:

Customer cst = new Customer();
PremiumCustomer pcst = new PremiumCustomer();

You probably guessed that the first two lines of code will call the first version of the ProcessCustomer method -- the one that accepts a Customer object parameter. After all, the cst variable passed to the method is declared as Customer and is referencing a Customer object. And, just as probably, you guessed that the second two lines of code will call the second version of the method that accepts a PremiumCustomer. You'd be right both times.

But how about the following example, which declares the variable passed to the ProcessCustomer method as Customer, but holds a reference to a PremiumCustomer? What's your guess for this code:

Customer cst = new PremiumCustomer();

If you guessed that this example still calls the first version of the ProcessCustomer method, you'd be right. That's because the decision on which overloaded version to call is made at compile time, based on the datatype of the variable being passed (and the cst variable is declared as Customer).

You might prefer, however, to have the decision made at run time based on the datatype of the object actually being passed. In other words, in that last set of code you might prefer to have the second version of the ProcessCustomer method called because the cst variable is referencing a PremiumCustomer object. You can do that by casting the parameter using the dynamic keyword, as in this example:

Customer cst = new PremiumCustomer();
ProcessCustomer((dynamic) cst);

This code will call the second version of the ProcessCustomer method because, even though the cst parameter is still declared as Customer, the variable is pointing at a PremiumCustomer object. I won't always want that behavior, but there will be times when this technique is going to be very useful.

Posted by Peter Vogel on 01/10/2013 at 1:16 PM5 comments

Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.