Posts in category .net - page 15

Extension methods illustrated

Extension methods are a great new feature in the .NET Framework 3.5 that let you write new methods that appear to be part of existing classes without the need to subclass or modify them.

We can explain this in simple terms with an example. Here is a useful routine that takes a string and returns what it finds between two other strings that works just fine with .NET 2.0 and .NET 1.1.

public static string Between(string value, string start, string end) {
  int startIndex = value.IndexOf(start, StringComparison.CurrentCultureIgnoreCase);
  if (startIndex == -1)
    return "";
  startIndex += start.Length;

  int endIndex = value.IndexOf(end, startIndex, StringComparison.CurrentCultureIgnoreCase);
  if (endIndex == -1)
    return "";

  return value.Substring(startIndex, endIndex-startIndex);
}

If this method belonged to a static StringUtilities class then you could use it like this:

string newString = StringUtilities.Between(inputString, startingString, endingString);

The problem is knowing that the StringUtilities class within the project you are working on and until you know that IntelliSense can’t even kick in. What would be nice is to add this to the String class but of course we can’t because String is sealed and besides methods everywhere create String classes and not instances of your subclass.

What would be really cool is if Visual Studio and .NET could just realize that this method is static and takes a string parameter as it’s first parameter and let it just appear as another method on the String class and just call StringUtilities behind the scenes.

That is exactly what the extension methods in .NET 3.5 achieve.

All we need to do is put this in front of the first parameter which will let VS and the compiler know that this method should appear as if it is a method against the type of that first parameter. The method must be static and visible to the code and curiously the class itself must also be static. Our signature now appears as:

public static string Between(string <em>this</em> value, string start, string end)

To call the method we simply press . after our string and IntelliSense displays all the usual methods and properties of the String class and any extension methods it can find in your project too which now includes our Between method giving us:

string newString = inputString.Between(startingString, endingString);

Nice but bear in mind the extension method can only access the public parts of the class it will appear with – there is no privileged access to protected properties or methods that would be available with sub-classing!

[)amien

Color schemes for Visual Studio

The default syntax color scheme in Visual Studio seems to be stuck in the 16-color era so once you’ve found your perfect font you are going to need a great theme to go with it.

Here is the theme I’m currently using at home (currently on a 42″ 1900×1200 LCD TV until I can find space for my monitor) that a couple of people have asked for.

To to take full advantage of this theme you will need to download:

  • Envy Code R for the syntax font with the italics hack
  • PalmOS for the output window’s tiny text

Alternatively you could remap it to your coding font of choice (but you won’t get italics because of limitations within the Visual Studio IDE).

Screen shot of Envy Code R PR7 with HumaneStudio theme.

Observations on Microsoft MVC for ASP.NET

Anyone who’s tried to develop large complex web sites with ASP.NET has likely run into many problems covering the page and control life cycle, view state and post backs and subsequent maintainability including the difficulty in creating automated unit tests.

Microsoft, taking a cue from the popularity of Ruby on Rails and subsequent .NET related efforts such as MonoRail, are embracing the model-view-controller (MVC) pattern and developing something more suited to web development than WebForms which aimed to make web development as similar to Windows development as possible (despite the major underlying differences in architecture).

The prototype, currently named System.Web.Mvc or Microsoft.Web.Scalene depending on where you look, is headed by Scott Guthrie with both Phil Haack and Scott Hanselman involved (sounds like a dream project and team to be involved with) and a preview release (“drop”) is due within the coming weeks.

Guthrie and Hanselman presented Microsoft MVC at the ALT.NET conference which revealed some interesting details buried in the video, my rough observations and notes based on the prototype they showed follows:

Philosophy

  • Don’t repeat yourself
  • Highly extensible & pluggable
  • Use generics to achieve strong-typing without code generation
  • Good performance, fast enough for large-scale sites
  • Separation of concern for maintainability
  • Clean URLs in and out
  • Clean HTML

Extensible

  • Interfaces used extensively
  • No sealed classes
  • Plug-in points for view engines (e.g. MonoRail’s NVelocity, Brail)
  • Support for Inversion of Control (IoC) engines (e.g. Windsor, StructureMap, Spring.NET)

Compatibility

  • Runs on the .NET 2.0 CLR
  • Some helper classes require .NET 3.5 (extension methods)
  • Normal Request, Response objects (via interfaces for mocking)
  • Does not support postback form runat="server"
  • Supports MasterPages, DataBinding, CodeBehind
  • Existing .aspx’s are blocked using web.config

Visual Studio

  • Solution templates for web project and unit testing
  • Full designer & IntelliSense integration

Flow

  • Route -> ControllerFactory -> Controller -> Action -> ViewEngine -> View

Routing

  • Routes can be defined dynamically and support RegEx URL matching
  • IControllerFactory pops out the required IController
  • Routing is case insensitive by default
  • Support REST, blog engine, Jango style mappings etc. default is /controller/action/parameters

Controllers

  • FrontController style
  • IController exposes:
    • Execute(IHttpContext context, RouteData routeData)
    • IViewEngine ViewEngine property
  • Some implementations available, all with virtual methods:
    • ControllerBase (adds dispatching)
    • Controller (Populate parameters into ViewData["key"])
    • Controller (Populates parameters by making ViewData type T)
  • Attributes
    • [ControllerAction] attribute to expose methods as actions (secure default behavior by not exposing helper methods)
    • Attribute for output caching
    • [ControllerAction(DefaultAction=true)] to override default method of Index

Parameters (to the controller)

  • Automatically parsed where a TypeConverter exists
  • Future versions will support more complex serialization of types
  • Can be nullable – use null coalesce operator for defaults

View Engine

  • IViewEngine
    • IView LoadView(string viewName)
  • Implementations include:
    • WebFormViewEngine

Views

  • IView
    • virtual void RenderView(object data)
  • Implementations include:
    • ViewPage – pick up parameters from ViewData[""] in conjunction with Controller
    • ViewPage pick up parameters from ViewData as type T in conjunction with Controller

HTML

  • Clean HTML generation (have they sorted out the id mangling by MasterPages/INamingContainer?)
  • Static HTML class supports Link, PagingLinks and Url methods
  • Map to action names using Lambda expressions to ensure follows refactoring, e.g. string url – Html.Link<ProductController>(controller =>controller.Edit(4);
  • Is there a way to follow the default action?

Model/data

  • Pagination extension methods extend IQueryable for getting pages of data (skip, limit)
  • Pattern for view-update-view cycle
  • Object property to form field id mapping available and pluggable, allows
    • product.UpdateFrom(Request.Form)

Testing

  • Easy to write tests by using mock objects (request, response)
  • Unit testing framework project (NUnit, MBUnit, xUnit.NET)

Finally

  • What’s with ScottGu’s nametag, can the show’s organizers not afford anything more than a Post It note?
  • What cool software is Scott Hanselman using to do the screen-cast video/zoom/overlay/highlighting?

[)amien

Refactoring shared libraries and public APIs

Refactoring is an essential process to keep code clean and elegant while it evolves. IDE’s offer common refactorings (although somewhat short of those prescribed in Fowler’s excellent Refactoring book and way short of the overall goals explained in Kerievsky’s Refactoring Patterns).

One limitation of existing tools is that they can only update references within your solution. When you are refactoring a shared library this is a problem, especially if it is your public API to the outside world.

We need to introduce metadata to document how the API has evolved and extend the tools to generate and understand this metadata.

Let’s take a look at a few of the refactoring in Visual Studio and see how they could be documented using the .NET metadata mechanism of choice, attributes.

Rename

Starting simple lets we had a property named Reference:

public string Reference {
  get { return id; }
}

We are going to rename Reference to StockCode for the 1.1.0.0 release. The tool could introduce a stub for backward compatibility whilst also marking it with metadata giving us:

[DeprecatedRefactorRename("StockCode", "1.1.0.0")]
public string Reference {
  get { return StockCode; }
}

public string StockCode {
  get { return id; }
}

The library is both binary and source compatible but with a little IDE work they could get a warning that Reference is now StockCode and given the choice of updating all the references in their project.

Nice. Let’s try a few more:

Remove Parameters

public bool AddStock(int quantity, DateTime arrival, StorageBin location) {
   ...
}

We are switching to a managed warehouse and so we no longer need to know where items are stored so we refactor and remove the StorageBin.

[DeprecatedParameterRemoved("location", "1.1.0.0.")]
public bool AddStock(int quantity, DateTime arrival, StorageBin location) {
  return AddStock(quantity, arrival);
}

public bool AddStock(int quantity, DateTime arrival) {
  ...
}

Reorder Parameters

[DeprecatedParametersReordered("arrival, quantity", "1.1.0.0.")]
public bool AddStock(int quantity, DateTime arrival) {
  return AddStock(arrival, quantity);
}

public bool AddStock(DateTime arrival, int quantity) {
  ...
}

Move Method

Existing tools offer little support for MoveMethod because they haven’t considered how to refactor the references. It is difficult to retain binary compatibility unless the class has a reference to class that now has the method we are interested in.

[DeprecatedMethodMoved("StockController", "Add", "1.1.0.0")]
public bool AddStock(DateTime arrival, int quantity) {
  return stockController.Add(this, arrival, quantity);
}

Let’s say the current calling code looks something like:

stockController.DoSomething();
selectedProduct.AddStock(DateTime.Now, input.Value);

However with a little ingenuity the IDE could examine the new method and map existing parameters based on name and type. If it still doesn’t have enough information consider local variables and properties of the objects it does have to present choices. This works especially well if your parameters are not primitives. Our code becomes:

stockController.DoSomething();
stockController.Add(selectedProduct, DateTime.Now, input.Value);

Keeping it clean

We don’t want our classes being cluttered with deprecated code indefinitely so the solution should contain two extra revision numbers, one detailing the oldest revision of attributes to keep in the source, the other for the oldest revision to compile into the binary. All the [Deprecated] marked methods and properties can slip into another file, perhaps Product.deprecated.cs so they stay out of sight until needed.

For .NET it would need somebody at Microsoft to take this on board and move us forward from ObsoleteAttribute as the facility should be cross-tool and so adding it solely to SharpDevelop would be of limited gain.

[)amien