Tips

Tip: Reveal DevExpress Menu

image

 

In this blog post, Alex Skorkin explains why the DevExpress Menu doesn’t show up in Visual Studio when using CodeRush Xpress, and how to show it:

How to show the DevExpress menu if it is not visible

Advertisements
Coding

CodeProvider: Create Contract Class

I’ve used the free offering (CodeRush Xpress) from Developer Express for years, and my feelings about it can be summed up by paraphrasing Larry Wall: “A machine without CodeRush is a sad machine indeed.”  Over the last few weeks I’ve been interested in implementing my own CodeRush plugin.  Prompted in no small part by Mark Miller’s decision to implement my CodeRush plugin suggestion during the weekly CodeRush Feature Workshop, I’ve taken the plunge and written my first plugin.  Here it is.

What’s it for?

A code provider in CodeRush automatically creates typical code blocks appropriate to the current coding context.  For example, the suggestion Mark Miller implemented was to add the IDisposable interface to an existing class.  When called on a class that does not implement IDisposable, this code provider adds “IDisposable” to the type declaration, implements the appropriate methods, and ensures that any disposable fields owned by the class are disposed.  Writing this code by hand typically took a bout 20 minutes.  Using Visual Studio code snippets got that down to about 5 minutes.  Using CodeRush, the code is generated instantly and consistently.  Pretty cool.

For those of you out there using Code Contracts, I’ve created a code provider that will implement a buddy class to hold contracts for an interface.  The provider will add a namespace reference to System.Diagnostics.Contracts to your interface file, decorate your interface with the ContractClassAttribute, then generate the buddy class in a separate class.  The buddy class file will import all the namespace references from the interface file, and the code provider will decorate it with the ContractClassForAttribute.  Each method and property on the interface will be explicitly implemented in the buddy class.  Property getters and non-void methods will return the default values for their types.  A TODO comment is placed into each member body, indicating where the contracts should go.

A little sugar

Since I’m scratching my own itch with this plugin, I decided to take it as far as I could.  I use FxCop and StyleCop on all my production code, so I wanted to make sure that the buddy class would leave me as little work to do as possible.  So, if the interface file has a file header comment, this is copied, updated with the buddy class file name, then placed at the head of buddy class file.  The namespace references are sorted in the order that StyleCop expects, and placed inside the the file namespace.  The provider generates an Xml documentation summary comment for the buddy class.  When Xml documentation comments are found on the interface, these are copied onto the appropriate methods in the buddy class.

Example

A few days ago I didn’t even know how to implement an interface contract, but I figured it was possible and quickly found this article Code Contracts Primer – Part 6 Interface Contracts by Derik Whittaker.  If Part 6 is any indication of the quality of this series, then Derik’s articles are a great place to start learning about Code Contracts if you are new to the subject.  (Another nice resource is Towards Code Correctness: Integrating Software Contracts and Unit Testing).  I’m going to use an example I’ve adapted from Derik’s article to show how the “Create Contract Class” code provider works.

You start with an interface that you would like to create specifications for:

//-----------------------------------------------------------------------
// <copyright file="IPayrollCalculator.cs" company="Jim Counts">
//     Copyright (c) Jim Counts 2011. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace PayrollCalculatorExample
{
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  /// <summary>
  /// Describes a payroll calculator.
  /// </summary>
  public interface IPayrollCalculator
  {
    /// <summary>
    /// Gets the state or province.
    /// </summary>
    string StateOrProvince { get; }

    /// <summary>
    /// Gets or sets a value indicating whether to withhold tax.
    /// </summary>
    /// <value>
    ///   <c>true</c> if withholding tax; otherwise, <c>false</c>.
    /// </value>
    bool WithholdTax { get; set; }

    /// <summary>
    /// Calculates the paycheck.
    /// </summary>
    /// <param name="baseRate">The base rate.</param>
    /// <param name="hoursWorked">The hours worked.</param>
    /// <returns>The paycheck amount.</returns>
    double CalculatePaycheck(double baseRate, int hoursWorked);

    /// <summary>
    /// Determines the base rate.
    /// </summary>
    /// <param name="employeeType">Type of the employee.</param>
    /// <returns>The employee base rate.</returns>
    double DetermineBaseRate(EmployeeType employeeType);
  }
}

Then, put your cursor on the interface declaration and use CTRL+~ to bring up the CodeRush menu.  Select the “Create Contract Class” menu item and the code provider goes to work.

CRMenu

The provider creates a new class in a new file.  The name is chosen by convention.  The provider removes the leading ‘I’ from the interface name and concatenates “Contract” to the end.  So in this example, it generates a class called PayrollCalculatorContract, and puts it in PayrollCalculatorContract.cs:

//-----------------------------------------------------------------------
// <copyright file="PayrollCalculatorContract.cs" company="Jim Counts">
//     Copyright (c) Jim Counts 2011. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace PayrollCalculatorExample
{
  using System;
  using System.Collections.Generic;
  using System.Diagnostics.Contracts;
  using System.Linq;
  using System.Text;

  /// <summary>PayrollCalculatorContract class contains CodeContract declarations for IPayrollCalculator.</summary>
  [ContractClassFor(typeof(IPayrollCalculator))]
  public sealed class PayrollCalculatorContract : IPayrollCalculator
  {
    /// <summary>
    /// Gets the state or province.
    /// </summary>
    string IPayrollCalculator.StateOrProvince
    {
      get
      {
        // TODO: Add Contracts Here
        // CodeContracts runtime will ignore this return value.
        return default(string);
      }
    }

    /// <summary>
    /// Gets or sets a value indicating whether to withhold tax.
    /// </summary>
    /// <value>
    ///<c>true</c> if withholding tax; otherwise, <c>false</c>.
    /// </value>
    bool IPayrollCalculator.WithholdTax
    {
      get
      {
        // TODO: Add Contracts Here
        // CodeContracts runtime will ignore this return value.
        return default(bool);
      }
      set
      {
        // TODO: Add Contracts Here
      }
    }

    double IPayrollCalculator.CalculatePaycheck(double baseRate, int hoursWorked)
    {
      // TODO: Add Contracts Here
      // CodeContracts runtime will ignore this return value.
      return default(double);
    }

    double IPayrollCalculator.DetermineBaseRate(EmployeeType employeeType)
    {
      // TODO: Add Contracts Here
      // CodeContracts runtime will ignore this return value.
      return default(double);
    }
  }
}

The type declaration for IPayrollCalculator is decorated with the appropriate attribute, and the Contracts namespace reference is tucked right between System.Collections.Generic and System.Linq:

namespace PayrollCalculatorExample
{
  using System;
  using System.Collections.Generic;
  using System.Diagnostics.Contracts;
  using System.Linq;
  using System.Text;

  /// <summary>
  /// Describes a payroll calculator.
  /// </summary>
  [ContractClass(typeof(PayrollCalculatorContract))]
  public interface IPayrollCalculator
  {

When the provider finishes, you will be looking at the buddy class implementation, and the project should compile as is.  In this example, StyleCop has three complaints, two of them related to fact that there is not a blank line between the getter and setter for “WithholdTax” and one complaint that there is not a leading space preceding the <value> tag in the XML documentation for “WithholdTax”.  Pretty nice.  If you care about those warnings, you have two things to fix, and if you don’t you can get straight to writing your contracts!

Warts

This code provider is definitely alpha.  I know it may have some issues with VB.NET interfaces that are not nested inside an explicit namespace.  I haven’t done any testing with anything except C#, or any coding style except my own.  Also, the provider is ripe for refactoring.   Just because it makes a pretty buddy class, don’t assume the provider is pretty… it ain’t.  Anyway, I hope to clean it up in future revisions.

Thanks

Thanks go out to Developer Express for providing such a powerful tool for free, Mark Miller and Rory Becker for hosting the weekly CodeRush Feature Workshop, and once again to Rory for maintaining the CodeRush and DXCore Community Plugins site.  I would not have been able to figure out half the tricks implemented in this code provider without access to the source code for CR_GenerateTest.

Code

Here is the initial code drop, with before and after examples.

Coding

Implementing a TypeConverter

The .Net Extensions library on CodePlex has a great extension method: ConvertTo<T>

There are several overloads available.  Here is its core implementation:

public static T ConvertTo<T>(this object value, T defaultValue)
{
  if (value != null)
  {
    var targetType = typeof(T);

    if (value.GetType() == targetType) return (T)value;

    var converter = TypeDescriptor.GetConverter(value);
    if (converter != null)
    {
      if (converter.CanConvertTo(targetType))
        return (T)converter.ConvertTo(value, targetType);
    }

    converter = TypeDescriptor.GetConverter(targetType);
    if (converter != null)
    {
       if (converter.CanConvertFrom(value.GetType()))
         return (T)converter.ConvertFrom(value);
    }
  }

  return defaultValue;
}

I only just discovered this project last weekend, but I have a similar method in my utility library called ConvertSimpleType<T> which I adapted from the ASP.NET MVC source.  What’s great about these methods is that the let you move the logic for implementing casts and conversions out of the consuming classes and into a TypeConverter.  If appropriate, the TypeConverter can delegate this logic back to the class itself, keeping all the logic about the class in one place, the class itself.

Example

Say you are using a stream and wanted to decouple from System.IO.Stream for testing purposes.  You’ve created a an interface and a wrapper class like so:

public interface IStreamWrapper
{
    void Close();

    // Other methods omitted...
}

public class StreamWrapper : IStreamWrapper
{
    private readonly Stream stream;

    public StreamWrapper(Stream stream)
    {
        this.stream = stream;
    }

    public void Close()
    {
        stream.Close();
    }
}

You are happy now because you can easily create mocks against IStreamWrapper for all your tests that consume streams.  However you may find that you run into a problem when interacting with other classes.  Say you want to save your XML data to your wrapped stream.

public void Respond(
    IStreamWrapper responseStream,
    XDocument responseDataXml)
{
    responseDataXml.Save(responseStream); // Does not compile
}

You can make the compiler happy with a cast, but that just moves the problem to runtime:

public void Respond(
    IStreamWrapper responseStream,
    XDocument responseDataXml)
{
    // Now throws NullReferenceException at runtime...
    responseDataXml.Save(responseStream as Stream);
}

You can add a conversion operator to the wrapper, but the runtime will not use it because that implementation is part of the class, but Respond only knows about the interface, so you would have to cast back to StreamWrapper first before you can take advantage of the “implicit” conversion operator.

public class StreamWrapper : IStreamWrapper
{
    // New method
    public static implicit operator Stream(StreamWrapper source)
    {
       return source.stream;
    }
}
public void Respond(
     IStreamWrapper responseStream,
     XDocument responseDataXml)
{
  // Works if responseStream is a StreamWrapper, but not with other
  // IStreamWrapper implementations
  responseDataXml.Save(responseStream as StreamWrapper);
}

But the real problem is that you have taken an explicit dependency on StreamWrapper. The method interface advertises that it expects any IStreamWrapper, but it is lying.  Say you have a FakeStreamWrapper implementation for testing.  This fake class should be convertible to stream, and indeed the conversion operator is exactly the same as StreamWrapper’s, except for the input:

public class FakeStreamWrapper : IStreamWrapper
{
  private readonly Stream stream;

  public FakeStreamWrapper(Stream stream)
  {
         this.stream = stream;
  }

  public static implicit operator Stream(FakeStreamWrapper source)
  {
         return source.stream;
  }

  public void Close()
  {
         Console.WriteLine("Close was called.");
  }
}

If you submit this fake to the Respond method, you will get a NullReferenceException in the StreamWrapper conversion operator and FakeStreamWrapper’s conversion operator is never called.   Respond asks the runtime to cast responseStream to StreamWrapper, but the runtime does not know how to do that for FakeStreamWrapper, so it supplies (StreamWrapper)null as the value instead.  Then the runtime tries to implicitly convert the null value into a Stream to satisfy the requirements of the XDocument.Save(Stream) method.  This is when StreamWrapper’s conversion operator is called with a null input value, resulting in the exception.

So what we need is a dynamic way to convert from any implementation of IStreamWrapper into stream.  Then our consuming class will not need to know about every wrapper implementation we might create.  This is where the TypeConverters come in, but using them involves some ceremony (see the implementation at the beginning of this post).  So using a method like ConvertTo<T> makes using TypeConverters very handy because all that ceremony is hidden inside the extension method.

Here is what we want our new Respond method to look like:

public void Respond(
     IStreamWrapper responseStream,
     XDocument responseDataXml)
{
     responseDataXml.Save(responseStream.ConvertTo<Stream>());
}

Inside ConvertTo<T>, the TypeDescriptor class takes care of finding out which implementation of IStreamWrapper was passed in, then looking for an appropriate conversion mechanism to Stream. The logic is simple:

  • Can we find a converter that knows how to convert a StreamWrapper to a Stream?
  • Can we find a converter that knows how to build a Stream from a StreamWrapper?
  • Return default if we can’t figure it out.

In our case, we should be able to take the first path, because StreamWrapper and FakeStreamWrapper each have an implicit operator to Stream.  But our classes are not quite ready to work with this new way of converting types.  TypeDescriptor does not look for implicit operators, it looks for a TypeConverter implementation associated with one of the types involved in the conversion, so we will need to create a TypeConverter for the TypeDescriptor to find.  Also, we will need some way of telling the TypeDescriptor to use the TypeConverter we create.  This last piece sounds like metadata, and it is, so if you are familiar with metadata in .NET you probably expect that this metadata will be passed with an attribute, and you would be correct.

Implementing TypeConverter

Without a custom TypeConverter and some way of telling the TypeDescriptor class to use it, we still get a NullReferenceException when using ConvertTo<Stream>() in our example.  When ConvertTo<T> cant find a way to convert to the target type, it returns the default, which is null for reference classes like Stream, causing XDocument.Save(Stream) to throw the exception.  So lets get our classes working with ConvertTo<T>!

Add Metadata

This part certainly involves less typing.  The attribute we want to use is in System.ComponentModel, so import that namespace:

using System.ComponentModel;

Now add the attribute to your class declaration:

[TypeConverter(typeof(StreamWrapperConverter))]
public class StreamWrapper : IStreamWrapper
{

That’s it for metadata!  Of course, StreamWrapperConverter doesn’t exist, so we need to implement it before trying to compile.

Implement TypeConverter

In this minimal TypeConverter implementation, we will just make sure that we can convert from StreamWrapper to Stream.  We wont worry about converting from Stream to StreamWrapper, although that code is simple, I’ll leave it out for brevity:

using System;
using System.ComponentModel;
using System.Globalization;

namespace ImplementingTypeConverter
{   

  public class StreamWrapperConverter : TypeConverter
  {    

    public override bool CanConvertTo(    

      ITypeDescriptorContext context,
      Type destinationType)
    {    

      return destinationType == typeof(global::System.IO.Stream) ||

     base.CanConvertTo(context, destinationType);
    }

    public override object ConvertTo(
      ITypeDescriptorContext context,
      CultureInfo culture,
      object value,
      Type destinationType)
    {
      var proxy = value as global::ImplementingTypeConverter.StreamWrapper;
      if (destinationType == typeof(global::System.IO.Stream) &&
        proxy != null)
      {
        return (global::System.IO.Stream)proxy;
      }

      return base.ConvertTo(context, culture, value, destinationType);
    }
  }
}

Again, we see a lot of ceremony, but at its heart, the code is very simple.  TypeDescriptor will read the TypeConverterAttribute on StreamWrapper which points to this TypeConverter.  When CovnertTo<T> asks for the converter, TypeDescriptor will provide an instance of this class.  TypeDescriptor doesn’t know what conversions this converter can handle, it just knows that this TypeConverter handles conversions for StreamWrapper.  Since its possible that this TypeConverter can’t handle the requested conversion, ConvertTo<T> will ask this class if it can convert to Stream using the CanConvertTo method.  CanConvertTo will check the destination type, and return true, or revert to the base implementation if the destination type is not Stream.

Once ConvertTo<T> has received confirmation that the StreamWrapperConverter can handle the conversion,  it calls ConvertTo on StreamWrapperConverter.  The ConvertTo method makes sure that it can cast the input object to StreamWrapper, double checks that the destination is Stream, then casts the wrapper object to Stream and returns it.  If the source or destination types are incorrect, it sends the data down to the base class.  In most cases this will result in an exception, just as if StreamWrapperConverter didn’t exist.  We double check the destination type because we don’t know who is calling the StreamWrapperConverterConvertTo<T> is well behaved, and it calls CanConvertTo before trying to convert, but less well behaved callers might not do so.

Unfortunately, TypeConverter returns the result as System.Object, so ConvertTo<T> will cast the result one more time before sending it back to the consuming class.  Working together, TypeConverter, TypeDescriptor and ConvertTo<T> accomplish a lot, and by implementing another TypeConverter for FakeStreamWrapper, we will be able to use either class with our example implementation and the Respond method would never need to know about either wrapper class.  The TypeConverter knows about what types its associated class can be converted to or from, and how to do that.  In most cases, I prefer to push that knowledge into a static method on the class itself.  This keeps the TypeConverter a little more ignorant, and puts the knowledge about the converting the class in the class.  It also makes unwrapping objects really easy, because the static method has access to the wrapped private field.

Improving the Implementation

In a real implementation you will probably want to implement the opposite conversion as well, which would allow ConvertTo<T> to take a Stream and wrap it for us.  This is easy to accomplish, since all the TypeConverter would need to do is call the wrapper’s constructor and supply the Stream instance.

You might also notice some warnings with this implementation if you use FxCop.  FxCop will issue warning CA2225 if you implemented StreamWrapper (or FakeStreamWrapper) as described above.  This warning points out that not all languages support operator overloading.  The recommendation is to create a named method that provides access to the overloaded functionality in those languages.  So we would add a static method to StreamWrapper:

public static Stream ToStream(StreamWrapper source)
{
    return source.stream;
}

Since the body of this method is the same as the implicit operator, you could have the operator call the method, or the method call the operator.  Either way works if you would like to be completely DRY.  The TypeConverter could also call ToStream instead of using a cast, I prefer calling ToStream in the TypeConverter.  For symmetry, I would also implement a FromStream method and an implicit operator from Stream.

The consuming class could still throw a null reference exception if left as is.  The wonderful thing about ConvertTo<T> is that it dynamically finds TypeConverters for IStreamWrapper implementations that comply with the implementation requirements, but nothing guarantees that IStreamWrapper implementations must comply.   For example, a Moq.Mock<IStreamWrapper> will not have the metadata needed by TypeDescriptor to find a converter, and so ConvertTo<T> will end up returning null.  So, the consuming class will need to be refactored to check for null before attempting to use the value returned by ConvertTo<T>.

When dealing with a wrapper class, the operators, conversion methods, and TypeConverter are usually boilerplate.  While you may want to implement more complicated conversions by hand, wrapper conversions are perfect targets for code generation.  I have code snippets that will implement the wrapper class and the TypeConverter.  These are great when I know I need a wrapper, but not as useful when working on legacy code that I want to convert into wrappers.  In that case, I end up doing a lot of cut and paste after generating the code with my snippets.  In the future I hope have a CodeRush plugin that will add the necessaries to the existing class and generate the TypeConverter for me.  I’ll either implement this myself or hope that @MillerMark is reading this, and finds it sufficiently interesting, we might see this idea appear in a #CodeRush feature workshop webinar :).

Whichever is quicker Winking smile

Code

Here is the completed example code, and code snippets.