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 
  {CustomerFactory.GetCustomerById("A123"), 
  CustomerFactory.GetCustomerById("A456")}

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
  <Runtime.CompilerServices.Extension()> 
  Sub Add (ByVal q As Queue, ByVal itm As Object)
    q.Enqueue(itm)
  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();
ProcessCustomer(cst);
PremiumCustomer pcst = new PremiumCustomer();
ProcessCustomer(pcst);

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();
ProcessCustomer(cst);

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


Connecting One WebPart to Many in SharePoint

Given the number of default interfaces that SharePoint provides, it's conceivable that you might want to create a provider WebPart that several consumers could connect to simultaneously. To make that happen, you must specify in the connection method that multiple consumers are allowed.

After decorating your connection method with the ConnectionProvider attribute, set the attribute's AllowsMultipleConnections property to True. Here's an example of a connection method for a provider that supports the IWebPartTable interface:

<ConnectionProvider("First Name", _
       AllowsMultipleConnections:=True)> _
Public Function MyProviderMethod() As IMyWebPartTable
  Return Me
End Function

A provider with a ConnectionProvider method like this could drive several consumer WebParts on the same page. You can also mark a ConnectionConsumer as allowing multiple connections which would allow a single consumer to interact with several providers at once (that would, I think, be something of a nightmare).

If you want a consumer WebPart to be able to connect to WebParts that support different interfaces (a consumer WebPart that works with both the IWebPartRow and IWebPartTable interfaces, for instance) then you need two separate connection methods: one for each interface. The same is true if you want to create provider that provides data through two or more interfaces (both the IWebPartRow and IWebPartParameters interfaces, for instance).

When you have multiple connection methods in the same WebPart, you must assign each method a unique id as the second parameter to the method's Connection* attribute. That's what this example does, creating a consumer that can work with both the IWebPartTable and IWebPartRow interfaces:

<ConnectionConsumer("Employee Data", "AllData")> _
Public Sub MyConsumerMethodForAllData(parm As IWebPartTable)
  '…code
End Sub
<ConnectionConsumer("Employee Data", "SelectedRow")> _
Public Sub MyConsumerMethodForSelectedRow(parm As IWebPartRow)
  '…code
End Sub

However, there are two scenarios related to these examples that aren't supported: A WebPart cannot connect multiple times to the same WebPart; if you have two WebParts that both support both the IWebPartTable and the IWebPartField interfaces (one as a consumer and one as a provider), they can only be connected once. The user will decide at runtime which interface to use.

Also, users can't connect a provider to a consumer that it's already connected to even if they swap roles. You can't, for instance, connect a WebPart A as a consumer to WebPart B as a provider, then turn around and have WebPart B connect as a consumer to WebPart A as a provider.

Posted by Peter Vogel on 12/10/2012 at 1:16 PM0 comments


Extend Your Classes Without Changing Code

So I'm at a client's site and we're discussing adding a new method to an existing class. One of the client's programmers said, "We should put the method in the base class and let all the derived classes inherit it from it" Another programmer said, "I think it would be better to create a new class that inherits from our base class and add the new method to it."

And I said, "Let's not change anything. Let's just create the new method."

I had a couple of reasons for disliking the first two suggestions. First, of course they weren't my suggestions. But beyond that, I didn't want to change the base class because the base class had this neat feature: it worked. I hate making changes to working code—it's just asking for something new to fail. Adding a new derived class would avoid that problem, but creates a new one: developers would have to be told to use the new class in order to get access to the new method. Developers were already using the existing classes and I didn't see any value in making them change.

So I suggested we create an extension method and avoid all those problems. An extension method sits in a separate file from the base class, so the base class is unchanged (though the method would be in the same Class Library project and be distributed as part of the same DLL). An extension method also appears automatically in the IntelliSense dropdown lists for the existing classes, so developers would have it presented to them as part of the classes they were already using.

Creating an extension method is easy. In C#, you add a static class with a static method, with both the class and method declared as public. The method's first parameter specifies the class the method will attach itself to (the parameter has to be flagged with the this keyword).

When the extension method is used from an object, that object is automatically passed to the extension method in that parameter. This ToggleCustomerStatus method, for instance, will appear in the IntelliSense list of any Customer object (or any object that inherits from Customer), toggle the value of the Status property on the Customer object the method is used on, and return the new value:

public static class CustomerCSExtensions
{
  public static bool ToggleCustomerStatus(this Customer cust)
  {
    cust.Status = !cust.Status;
    return cust.Status;
  }
}

To create an extension method in Visual Basic, add a Module, declare it Public, write your function or subroutine, and decorate the method with the extension method. The first method parameter specifies the class to which the method will be added. When the extension method is used from an object, that object is automatically passed to the extension method in that parameter.

This ToggleCustomerStatus method, for instance, will appear in the IntelliSense list of any Customer object (or any object that inherits from Customer) and, unlike my previous example, doesn't return a value:

Public Module CustomerExtensions
  <System.Runtime.CompilerServices.Extension()>
  Public Sub ToggleCustomerStatus(ByVal cust As Customer)
    cust.Status = Not cust.Status
  End Sub
End Module

To use the extension method, you need to add an Imports or using statement for the namespace that the extension was declared in. If the extension method is in the same namespace as the object it's attaching itself to, developers using that object will probably already have that namespace in place. After that, using an extension method looks just like using any other method (and it doesn't matter if the class the extension method is being attached to is written in one language and the extension method itself is written in another language). Here's the C# ToggleCustomerStatus method in action in some VB code:

Dim cust As Customer
If cust.ToggleCustomerStatus Then …

And the VB version used from C# code:

Customer cust;
cust.ToggleCustomerStatus();

While my sample extension method accepts only the single parameter that specifies which class it should attach itself to, an extension method can accept multiple parameters, just like any other method. You can also specify an interface as the first parameter's datatype so that your extension method will attach itself to a variety of objects (provided they all implement that interface). And, most importantly, you don't change any working code.

Posted by Peter Vogel on 12/03/2012 at 1:16 PM2 comments


Free Tool: Find Memory Leaks in SharePoint

It's hard to create memory leaks in .NET, but I can do it when developing in SharePoint without even trying very hard. The SharePoint Dispose Check (SPDisposeCheck to its friends) analyzes your code to see if you're following Microsoft's best practices in disposing of SharePoint resources.

SPDisposeCheck is a Visual Studio Add-In that adds a new menu item to your Tools menu. When you select it, SPDisposeCheck pops up a dialog that lets you check which parts of your Solution will be checked. In addition to running an analysis when you want, you can also choose to have your code analyzed as part of building your projects. By default, the results are displayed in the Output Window (you have to set the dropdown list at the top of the Window to SPDispose check). However, you can also choose to have any problems listed as Errors.

PDisposeCheck won't stop you from having memory leaks in SharePoint; but at least when you track a leak down, it won't be something so obvious that you'll feel foolish about it.

Posted by Peter Vogel on 11/29/2012 at 1:16 PM0 comments


Using Properties in WCF Services

Scattered across all the services I've created, I must have 257 methods whose names begin with the word "Get" (e.g., GetCustomerData, GetOrdersForDate). And I typically have a corresponding method for accepting the data (e.g., UpdateCustomerData, SetOrders). I wouldn't write a class like that with two separate methods; I'd create a Property just called, for instance, CustomerData.

It turns out that you can use properties in a WCF Service: just put the OperationContract attributes on the property's getter and setter:

Public Property CustomerData As String
  <OperationContract()> _
  Get
    Return _CustData
  End Get
  <OperationContract()> _
  Set(value As String)
    _CustData = value
  End Set
End Property

Now, when I add a service reference to a consumer to generate the client-side proxy, I discover that I've only solved half of my problem. For the example above, the client-side proxy has two methods: get_CustomerData and set_CustomerData:

Dim cr As New CustomerService.CustomerServiceClient
sr.set_Data(custData)
Dim custData As CustomerData = sr.get_Data()

But on the service side, I no longer have two separate methods. Instead, the getter and setter for my data are now brought together in one Property. I'm OK with that.

If you're feeling very radical, you can write your property so that it accepts a parameter:

Public Property CustomerData(CustomerID As String) As String
  <OperationContract()> _
  Get
    Return _CustData
  End Get
  <OperationContract()> _
  Set(value As String)
    _CustData = value
  End Set
End Property

On the client-side, the proxy's get_ and set_ methods will now require a parameter:

Dim cr As New CustomerService.CustomerServiceClient
sr.set_Data("ALFKI", custData)
Dim custData As CustomerData = sr.get_Data("ALFKI")

Posted by Peter Vogel on 11/26/2012 at 1:16 PM0 comments


Redefining Operators

I'm not sure whether to classify this as a tip or bad advice: It's possible to redefine the operators (e.g. !, =, ++) used with a class. That doesn't mean it's a good idea. As I discussed in an earlier tip, the differences in using equality tests between C# and VB (and, within a language, the differences between the equals operator and the Equals method) probably create enough confusion without you assigning an arbitrary meaning to =/== for a particular class. But having said that…

Let's say you have some class that switches between two states: A Customer class that can be creditworthy or not creditworthy; a Service that switches between being "in" or "out" of service; a Product that is in-stock or out-of-stock. You can have a property that allows you to control this:

Dim cust As New Customer("A123")
cust.Creditworthy  = False

To toggle between the two states, you could use this code:

cust.CreditWorthy = Not cust.Creditworthy

But it might be nice to just do this to toggle the Creditworthy property:

cust = Not cust

Before showing how to implement this, let me point out my chief objection: How would anyone reading your code or using your Customer object know what the Not operator is doing?

But if you want to do it, you add a shared/static Operator method to your class with the name Not. This Operator method should accept and return the object that it's part of (if you wanted to redefine the + operator, you'd add an Operator method called +). That method will be passed the object that the operator is being used on so that you can modify the object if you wish. Implementing my state-switching code would look like this:

Public Shared Operator Not(Cust As Customer) As Customer
  Cust.Creditworthy = Not Cust.Creditworthy
  Return Cust
End Function

In C#, the code looks like this:

public static Customer operator !(Customer cust)
{
  cust.Creditworthy = !cust.Creditworthy
  return cust; 
}

I can now toggle the creditworthiness of a Customer object in C# like this:

cust2 = !cust;

Postfix and prefix conventions are also honored with operators that support it. The primary difference in overriding binary operators (e.g. +, -) is that your operator method is passed two parameters: the object on either side of the operator.

Like I said: I'm not sure if this is a tip or bad advice, but I had a client ask me how to do it so people do seem to care.

Posted by Peter Vogel on 10/16/2012 at 1:16 PM1 comments


Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.