Use Enumerated Values with Bit Flags to Handle Multiple Options

If your code uses a set of options and you don't use enumerated values, you can end up writing opaque code like this which passes an unexplained "magic number" to a method:


With enumerated values, your code becomes easier to read because you can pass a named value:


Some applications need a set of options that can be combined in a variety of ways. In that scenario, a favorite developers' trick is to have each bit in a Byte represent one of the options. By using values that are powers of 2 and logical Ors, a developer can set individual bits in the Byte; using those same values against the Byte, along with logical Ands, a developer can check which bits in a Byte are set. Bringing in enumerated values makes working with bit flags easier to both read and write.

First, you need to override the default integer values for enumerated values to set the enumerated values to powers of 2, as in this enumeration:

Public Enum UpdateOptions
   Deferred = 1
   Audited = 2
   Transacted = 4
End Enum

To use these enumerated values with the Update method to specify both the Deferred and Audited options, you would Or together the enumerated values. The Visual Basic code looks like this (in C#, you would use the | operator instead of the Or):

cust.Update(UpdateOptions.Deferred Or  UpdateOptions.Audited)

Inside the Update method, to accept the Byte created by Oring together the options and to see if a particular option has been set, you use this code in Visual Basic (in C#, use the & operator instead of And):

Private Sub Update(Options As Byte)
If Options  And UpdateOptions.Deferred Then

You don't need the Flags attribute I put on my enumeration, but it does simplify debugging. The Flags attribute causes the ToString method to generate a useful result when used on a Byte that's been cast to the type of the enumeration. This example casts the Options variable to my UpdateOptions type, and then calls the result's ToString method:

Private Sub Update(Options As Byte)
Debug.WriteLine(CType(Options, UpdateOptions).ToString())

Because I used the Flags attribute on the UpdateOptions enumeration, the output is the informative "Deferred, Audited"; without the Flags attribute, the output would have been the less helpful "3".

Posted by Peter Vogel on 05/07/2013 at 1:16 PM0 comments

Free Yourself with a Dependency Injection Container

I'm now doing a column for MSDN magazine about how design patterns help developers solve typical business problems. The column is called "Patterns in Practice", but it could just as easily have been called "Thinking with Objects." As I was writing this month's Patterns in Practice column, I was thinking about how much easier my life has become since I've started using Inversion of Control (IoC)/Dependency Injection Containers. But when, as a consultant, I work with other developers, I find that these tools aren't all that common.

The issue is that, once you start thinking in terms of "What objects would make it easy to solve this problem?", you can end up with a few, very complicated objects. A better solution is to have lots of very simple objects that you can instantiate as you need them. With this approach, you end up with many variations on a single class, with each of those variations designed to do a great job of handling a specific problem.

The problem is that dealing with those objects can be a nightmare. If, for instance, you have three different Customer classes (each designed to handle one kind of customer), you can end up with three different variable declarations:

Dim  custp As PremiumCustomer
Dim  custOrd As OrdinaryCustomer
Dim  custDb As Deadbeat

Using inheritance or interfaces lets you make all the variations on a class look alike. The practical result is that you can declare one variable to work with all the varieties of the class. If all the Customer classes inherit from one class or implement the same interface, you can declare a single variable to work with any Customer object. Here's the only variable declaration you need if all Customer classes implement the same interface, ICustomer:

Dim  cust As ICustomer

The problem is the New statements; those statements have to reference a specific class:

cust  = New PremiumCustomer
cust  = New OrdinaryCustomer
cust  = New PremiumCustomer

What a Dependency Injection Container does is eliminate those New statements. Instead, you load the container with the objects your application needs. When you want a class, you just turn to the container and ask for it. You can even specify criteria to choose which object you want. Code like this works with Microsoft's Unity container, for instance, to find an object that implements the ICustomer interface and is associated with the string "Premium":

cust  = DependencyContainer.Resolve<ICustomer>("Premium")

Really, these tools solve a ton of problems and can completely change the way you think about objects when solving problems.

Posted by Peter Vogel on 04/30/2013 at 1:16 PM0 comments

Don't Create Pages in SharePoint; Use User Controls

Because the Master Page for your SharePoint site is kept in the hive (and because Visual Studio isn't smart enough to follow the MasterPageFile attribute that points to the Master Page in the hive) when creating a page in Visual Studio, you can't switch to Design View. For those of you with a great grasp of HTML that may not be a problem. Because of my shaky grasp of HTML and CSS, when I work in Source View I'm frequently surprised at what shows up in the browser when I view my page.

There are workarounds for this problem (copying your site's Master Page into your project and setting/resetting your page's MasterPageFile to point to the local copy, for instance). Lately, however, I've been using a hint from my friend Patrick Haggerty (who wrote Learning Tree's SharePoint Development course). When I create a page, I don't add controls directly to the page. Instead, I create a User Control and add my controls to it. I then add my User Control to the appropriate Content control on the page I'm creating. When I'm creating a User Control, I always have both Design View (which I like) and Source View (when I need it). Until Visual Studio gets smarter (and Visual Studio 2012 hasn't), this is the best solution I've got.

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

Free Tool: Try Out SQL Queries and Explore Databases with QueryExpress

As an independent consultant, I move from one client's computer to another. Because of that, I frequently find myself on computers where I need to browse a database but don't have a copy of SQL Server Management Studio installed. If you want a quick replacement for Management Studio, try QueryExpress. It's so small and downloads so quickly that you'll think it hasn't download at all. QueryExpress also requires no installation: just drop it on your desktop and double-click its icon to run it.

QueryExpress isn't a complete replacement for Management Studio by any means, but it gives me everything I need: a text window for entering SQL statements, a TreeView of all of the databases on the server (with their tables, stored procedures, and functions) and a GridView of any query results.

There's some stuff missing that I wish was there: QueryExpress won't scan for databases for you to connect to, so I have to know what my server and database engine names are; and the undo in the text window only goes back one step. But, to compensate for that, QueryExpress works with SQL Server, Oracle or any OLE DB compatible database.

If you want something more powerful that's still free, you can take a little longer and install Query ExPlus, which builds on Query Express.

Posted by Peter Vogel on 04/15/2013 at 1:16 PM0 comments

Customize Visual Studio Menus

There are probably lots of items on the Visual Studio menus and toolbars that you never use: Why not get rid of them? The odds are also good that there are items on the Visual Studio menus that you use frequently but are buried on some submenu. For instance, I want to know why the Views menu is cluttered up with windows I never use like Team Explorer (most of my clients don't use Team Foundation Server) and Properties (I always use F4). And why is the Immediate Window (which I use all the time) buried on the Other Windows menu off the Debug menu?

Why not set up Visual Studio to work the way you do? Removing the items you don't want is ridiculously easy: From the Tools menu, select Customize and, in the Customize dialog, click on the Commands tab. In the dropdown list at the top of the dialog, select the Menu bar you want to customize (e.g. View or View | Other Windows). Then find the menu items you never use and delete them. Finding the menu you want to delete isn't always obvious, though; the Team Explorer menu choice appears on the list as TfsTeamExplorer.

Adding the items you do want is only slightly more complicated. Still in the Customize dialog, after selecting the menu you want to add to, click on the Add Command button. This will display a list of available commands (on the right) organized by the menu (on the left) that the commands normally appear on. So, to add the Immediate View menu item to the View menu (where it belongs), first select the Debug menu in the left column. Then, when the list of commands on the right refreshes, select the Immediate menu item and click OK.

And: Don't Worry! If you delete something that you wish you'd kept, you can always add it back. Or, if things go horribly wrong, just click the Reset button on the Customize dialog to get back to the original menus.

There's an added benefit here: Job Security. If no one can figure out how your copy of Visual Studio works, it makes you that little bit harder to replace.

Posted by Peter Vogel on 04/05/2013 at 1:16 PM0 comments

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

Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.