Daniel Cazzulino's Blog :

Subscriptions

News

Source code published in this blog is public domain unless otherwise specified.

 

kzu in LinkedIn

  Microsoft MVP Profile

 Contact

Post Categories

All Technology (RSS)

How to merge your referenced assemblies into the output assembly for improved usability

Something we've been doing in moq since the very beginning is to have a single assembly as output: Moq.dll. This reduces the clutter for users and lets them focus on what they need from our library, rather than getting the noise of whatever third-party (or internal) libraries we use to implement it.

This is good from the deployment point of view too, and if all your libraries are actually internal infrastructure assemblies, you can even make them all internal types of your output assembly.

The key to all this is ILMerge, and it's very easy to setup in a project. You just need to download the installer, copy the included executable somewhere (i.e. "Tools") near your project and reference it from a post-build task in the project. The following configuration merges all referenced assemblies that have "Copy Local" set to true into the output assembly, and internalizes all the types in those libraries (makes them all internal to the output assembly), except for those in the optional (can be empty) exclude file (which can contain a full type name per line, to leave their visibility untouched):

<target name="AfterBuild" condition=" '$(Configuration)' == 'Release' ">
        <createitem include="@(ReferenceCopyLocalPaths)" condition="'%(Extension)'=='.dll'">
                <output itemname="AssembliesToMerge" taskparameter="Include" />
        </createitem>
        <exec command=""$(MSBuildProjectPath)..\..\..\..\Tools\ILMerge.exe" /internalize:"$(MSBuildProjectPath)ilmerge.exclude" /ndebug /keyfile:$(AssemblyOriginatorKeyFile) /out:@(MainAssembly) /targetplatform:v4,$(MSBuildToolsPath) "@(IntermediateAssembly)" @(AssembliesToMerge->'"%(FullPath)"', ' ')" />
        <delete files="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')" />
</target>

After merging the assemblies (only for release builds, in this case), it will delete the embedded assemblies.

 

Enjoy!

Update: turns out I had blogged about this before more extensively :).

posted Thursday, March 11, 2010 10:24 AM by kzu with 4 Comments

Simplified INotifyPropertyChanged Implementation with WeakReference Support and Typed Property Access API

I've grown a bit tired of implementing INotifyPropertyChanged. I've tried ways to improve it before (like this "ViewModel" custom tool which even generates strong-typed event accessors).

But my fellow Clarius teammate Mariano thought it was overkill and didn't like that tool much. He mentioned an alternative approach also, which I didn't like too much because it relied on the consumer changing his typical interaction with the object events, but also because it has a substantial design flaw that causes handlers not to be called at all after a garbage collection happens. A very simple unit test will showcase this bug.

I also looked at the new WeakEvent Patterns page in MSDN but it's even worse in terms of implementing and exposing it to consumers.

So, with my ever growing love for lambdas and my strong-typed reflection approach (used by the first alternative too, btw), I thought I could do better :). Here's the result of that, which I think improves all the above choices.

Why you need weak reference support

The importance of this cannot be understated. A delegate that you pass around has a strong reference to the instance that exposes it. This is the Target property on the delegate class. What this means is that even if the subscribing object goes out of scope and is ready to be collected, it will not be as long as the event source (the object exposing the PropertyChanged event, for example) holds a reference to it. And as long as the event subscription is there, the reference will be there too. That's why it is typically important to remove your reference once you're ready to "go" (i.e. on Dispose, you detach from the events you're listening). Needless to say, this is a repetitive, error-prone activity.

Another typical side-effect of this is that you cannot use anonymous delegates or lambdas if you need to unsubscribe, as you need to keep a reference to the originally subscribed lamdba in order to unsubscribe:

var target = new Foo();

target.PropertyChanged += (sender, args) => Console.WriteLine(args.PropertyName);

// How do you unsubscribe now??

// This clearly doesn't work because even if the actual source is the same, 
// the delegate is still a brand-new one.
target.PropertyChanged -= (sender, args) => Console.WriteLine(args.PropertyName);

// So you need to keep the lambda around:
PropertyChangedEventHandler handler = (sender, args) => Console.WriteLine(args.PropertyName);

// Just so you can use that to subscribe/unsubscribe:
target.PropertyChanged += handler;
target.PropertyChanged -= handler;

// So typically you're better off just adding a full instance method on your 
// consumer just so you have a clear pointer for unsubscribing:
target.PropertyChanged += OnTargetPropertyChanged;

// But now if you need contextual state in the event handler that exists 
// at subscription time, you need to promote that state to class fields
// so that you can use that in the event handler
this.someState = currentMethodState;

// This is looking like .NET 1.0 already ;)

The PropertyChangeManager way

I therefore decided to take a TDD approach to the issue with the following requirements:

  1. The programming model for consumers must not involve creating any new objects. They already have the object that will be raising property change events.
  2. The "old style" way of attaching to property changed events must still work, but add the weak reference support that's so badly needed. And this must be transparent to consumers.
  3. A new style should involve using lambdas to avoid property names as strings
  4. The new style should be trivial to implement for an author exposing INotifyPropertyChanged.

So I came up with these BDD-style test specifications:

  • WhenSubscriberIsAlive_ThenNotifiesSubscriber
  • WhenSubscriberIsNotAlive_ThenDoesNotNotifySubscriber
  • WhenAddingPropertyChangedHandler_ThenNotifiesSubscriber
  • WhenAddedPropertyChangedHandlerTargetIsNotAlive_ThenDoesNotNotify
  • WhenRemovingPropertyChangedHandler_ThenDoesNotNotifySubscriberAnymore

These should cover all use cases.

Consuming PropertyChangeManager-enabled objects

The fact that a given object is internally (remember requirement 1.) using this PropertyChangeManager is completely hidden from the consumer:

var source = new Foo();

source.SubscribeChanged(
    x => x.Name,
    foo => Console.WriteLine(foo.Name));

The first argument specifies which property you're interested in, and the second is an Action in this case for the callback when the property changes. It can of course point to a class method:

source.SubscribeChanged(
    x => x.Name,
    this.OnRenamed);

Optionally, if unsubscribing from the event will be needed at some point, you can just keep a reference to the returned IDisposable object from the call to SubscribeChanged:

// this could be assigned to a field, for example.
IDisposable onRenameSubscription = source.SubscribeChanged(
    x => x.Name,
    foo => Console.WriteLine(foo.Name));

// at some later point (i.e. IDisposable.Dispose implementation of the consumer)
onRenameSubscription.Dispose();
// now the subscription is removed, even if I didn't keep the lambda around! 

The source object can still implement INotifyPropertyChanged, but you may want to do so explicitly just for its support for databinding infrastructure. The consumer would still be able to cast the object to INotifyPropertyChanged if he wanted to use the "unsafe" property name strings ;). The implementation can still be made public, though.

Implementing INotifyPropertyChanged with PropertyChangeManager

The implementer defines a private field to hold a reference the manager:

public class Foo : INotifyPropertyChanged
{
    private PropertyChangeManager propertyChanges;
    private string name;
    private int value;

    public Foo()
    {
        this.propertyChanges = new PropertyChangeManager(this);
    }

Note that the manager is generic and receives the type of the "change event source", in this case Foo.

Next, your properties need to be turned into "old-style" .NET properties with a backing field, because you need to add a call to the manager in the property setter:

public string Name
{
    get { return name; }
    set { name = value; this.propertyChanges.NotifyChanged(x => x.Name); }
}

Note that the call to the manager also leverages lambdas to avoid using strings.

In order to provide a custom implementation of the INotifyPropertyChanged.PropertyChanged event, you need to implement the interface explicitly and pass-through the implementation to the manager:

public PropertyChangedEventHandler PropertyChanged
{
    add { this.propertyChanges.AddHandler(value); }
    remove { this.propertyChanges.RemoveHandler(value); }
}

This is a restriction in the language, which prevents this event from being public. But it's not as bad as it sounds, as you want to encourage adoption of safer lambda-version subscription, which is the last bit to implement:

public IDisposable SubscribeChanged(Expression> propertyExpression, Action callbackAction)
{
    return this.propertyChanges.SubscribeChanged(propertyExpression, callbackAction);
}

 

How PropertyChangeManager works

The manager works by dismembering the received delegates into their actual target and method info, to be able to weakly reference the former, while remaining able to call the latter. It's a plain list internally, which is scavenged every time an action is performed in the manager (this could be optimized somehow to only happen on Notify, but it simplified the implementation a bit, and it's not like property change performance is a big issue in UIs anyway).

Here's the full source.

 

Some tooling such as a custom tool, item template, or code snippets would be nice, I'll try to provide those in the future.

Enjoy!

posted Monday, March 08, 2010 10:30 AM by kzu with 11 Comments

How to set the startup program for debugging a project for the entire team

You surely have set the startup application for a project countless times:

image 

But that setting goes your user options file, the rest of the team doesn't get to reuse the setting. And what if you repave your machine or start working on a new virtual machine and just got the sources from source control? You have to re-set this value again and again.

Turns out that this setting goes to a file named after your project file plus the ".user" extension. This file is just a fragment of an MSBuild file, and would look something like:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
    <StartAction>Program</StartAction>
    <StartProgram>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe</StartProgram>
    <StartArguments>/rootSuffix Exp</StartArguments>
  </PropertyGroup>
</Project>

And because this just plain MSBuild properties, you can copy the entire PropertyGroup to your main project file, delete this .user, and check-in your change. From now on, everyone on the team will have this setting enabled, and you will have it too if you get a clean environment eventually :)

posted Friday, March 05, 2010 4:01 AM by kzu with 2 Comments

How to install Reactive Extensions for .NET 4.0 Beta 2 on VS2010 RC
  1. Get the .NET 4.0 Beta 2 download from MSDN.
  2. Open the downloaded .exe with 7zip (i.e. right-click on file, select 7-Zip > Open Archive)
  3. Navigate to the .rsrc\RCDATA\ "folder" and open the CABINET file:

    image
  4. Extract the contained MSI, install and enjoy!

    image

I thought I'd need to crack the MSI open with the good old Orca tool, but turns out I didn't have to!

Stay tuned, my Reactive Framework Extensions Generator will be soon updated to RC too :)

 

Enjoy!

posted Tuesday, March 02, 2010 8:18 PM by kzu with 1 Comments

How to quickly setup the best free Diff/Merge tool with VS 2010

First go get the tool. It's free and it rocks.

Next, save this XML to a file with a .vssettings extension:

<UserSettings>
    <ApplicationIdentity version="10.0"/>
    <Category name="Source Control_TeamFoundation" Category="{2A718788-A6D9-44C5-90EF-438BF5B06A74}" Package="{4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}" RegisteredName="Source Control_TeamFoundation" PackageName="Microsoft.VisualStudio.TeamFoundation.VersionControl.HatPackage, Microsoft.VisualStudio.TeamFoundation.VersionControl, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
        <PropertyValue name="UserTool1" extension=".*" operation="Compare" command="C:\Program Files (x86)\SourceGear\DiffMerge\DiffMerge.exe" arguments="/title1=%6 /title2=%7 %1 %2"/>
        <PropertyValue name="UserTool2" extension=".*" operation="Merge" command="C:\Program Files (x86)\SourceGear\DiffMerge\DiffMerge.exe" arguments="/title1=%6 /title2=%8 /title3=%7 /result=%4 %1 %3 %2"/>
    </Category>
</UserSettings>

Finally, go to Tools > Import and Export Settings in VS and import that file by clicking Browse on the third and final page.

What this does is set the great SourceGear DiffMerge tool as the diff and merge tool to use for all your files. I find it much more usable and smart than the built-in TFS one.

For the ultimate collection of settings for diff/merge tools in VS, see James' blog post.

 

Enjoy.

posted Tuesday, March 02, 2010 8:17 PM by kzu with 9 Comments

Software Development Productivity

Scott Bellware has an interesting series of posts where he discusses how to get back to productive development teams. As usual in his writing (IMO), in a rather verbose way he brings up quite a few good points. Please go ahead and read them. He links from the first entry to the next so you can follow the flow.

I agree with the analysis that unnatural organizational structures kill productivity, motivation and leadership. And I believe this is one of the reasons why even big companies turn to so-called "boutique development shops" (shameless plug there): by being small and very cohesive, these shops offer creativity and productivity levels that "mere big" ISVs can only dream of.

And it's not always only a matter of design principles, I'd add. Sometimes you need a specific area of expertise which you're better off outsourcing (i.e. Visual Studio extensibility, hardcore WCF, framework/runtime libraries, WPF/Silverlight/Blend UEX, etc.). Small shops of highly specialized professionals can save you tons of money and time. But your own dev team will certainly benefit from applying sound design principles for what matters most to your business: the business rules and logic.

posted Monday, February 08, 2010 3:15 PM by kzu with 3 Comments

How to transform old properties to automatic properties with a simple search and replace

Say you have a (typically autogenerated) class with properties like:

public partial class Project : IExtensibleDataObject
{
    public System.Runtime.Serialization.ExtensionDataObject ExtensionData
    {
        get
        {
            return this.extensionDataField;
        }
        set
        {
            this.extensionDataField = value;
        }
    }

Now you can fire up the Find & Replace dialog in VS and enter the following "simple" expression in Find What:

\n:b*\{[:b\n]*get[:b\n]*\{[.:b\n]*.*[.:b\n]*\}[.:b\n]*set[:b\n]*\{[.:b\n]*.*[.:b\n]*\}[.:b\n]*\}

And use the following expression for the replace:

 { get; set; } 

image

Don't forget to set the Use: Regular expressions option.

Running it will get you automatic properties for the entire file (or files):

public partial class Project : IExtensibleDataObject
{
    public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get; set; }

    [System.Runtime.Serialization.DataMemberAttribute()]
    public int AffiliateId { get; set; }

    [System.Runtime.Serialization.DataMemberAttribute()]
    public Galleries.Domain.Model.Category[] Categories { get; set; }

 

Yeah, I know, that expression looks like crap ;)

posted Tuesday, January 12, 2010 12:50 PM by kzu with 4 Comments

How to get out of the GAC all the registered assemblies

You know how annoying the GAC shell extension makes it to access the actual assemblies:

image

Utterly useless.

Of course, you surely know that you can get to those elusive assemblies via the command-line and side-step the shell extension:

image

But, now you need to go to each assembly folder, then its version, and so the actual assemblies are scattered through various locations.

This one-liner powershell command will get them all out in a folder of your choosing for easy Reflector-ing (create the target before running it):

Get-ChildItem C:\Windows\assembly\GAC_MSIL -filter *.dll -recurse | Copy-Item -destination C:\GAC

posted Friday, January 08, 2010 7:06 AM by kzu with 3 Comments

Why Windows Media Center is dead

Windows Media Center (WMC) is based on a relatively simple (albeit awfully implemented) principle: you have ONE "server" PC holding and running your media, and then you associate any number of Media Center Extenders to it that are typically (except for the XBox 360) single-purpose devices that can only act as such and are fancy and silent enough to deserve a place in your living room.

I guess back in 2005, the entire model and most of Microsoft design decisions on this product may have be justifiable. 5 years later, none of them make any sense and IMO mean that WMC is currently a totally flawed, doomed and generally useless product for most common needs.

Why it (kind of) made sense back then

  • Hardware: In 2005, you wouldn't dare subject your family to the noise, ugliness, quirkiness, uex, power comsumption, and cost of a full-blown "Home Theater PC" (HTPC) or an XBox power sucker. The Media Center Extender model made sense because you couldn't buy a full PC that was silent and nice-looking enough for the price of an extender. (but the extenders weren't without limitations either, a good review of it at the time at the supersite)
  • The user experience is quite cool (but the extenders' lower processing profile meant their UI rendering capabilities were significantly worse)

Why it doesn't make sense anymore

  • Hardware: nowadays you can buy a full blown PC, small, silent and power-efficient for $199-$249. Why would you want a crippled, single-purpose device when you can have the full power of a desktop, with the capability to play back any weird format you can possibly throw at it, provided you just install the right codec. No more hardware limitations and being stuck with an obsolete device.
  • Software: back then, the Media Center team invented their own markup language to accommodate disparate rendering capabilities between a full PC, the XBox and a crippled extender. Nowadays we have WPF and Silverlight, no need to learn a new UI markup language. The extenders UI is sluggish at best, compared with what's possible in a PC with WPF/Silverlight.
  • OS: Windows 7 is a kick-ass operating system, with a ton of features. It's a snappy, sleek, touch-friendly, smart connected (i.e. "Play To"/DLNA, HomeGroup, etc. etc.) platform. And it runs great on the smallest chips out there (it gave new life an 'old' Dell Mini 9 I had, for example).
  • Home Server: having all your media in a "plain" PC is risky. You need to take care of backups, redundancy, fault-tolerance, etc. Today, it's a no-brainer to buy a Windows Home Server and let it manage all this for you, automatically, transparently, and just dead easily.

This combination makes desktop media management software a viable alternative and can certainly power your living room and projector. I believe we're at the beginning of a revolution in smart homes and connected media, just because of this new synergy and convergence.

If I had to start a project like that right now, I'd make it so that:

  • It runs full WPF on the HTPCs connected to every TV.
  • It supports a centralized repository for the entire house (which could be a regular PC or a Windows Home Server-WHS)
  • It has a built-in extensibility model based on some dependency injection technology (i.e. MEF), and *everything* including the core functionality is a plugin
  • It leverages WHS to provide mostly the same UI over the internet by leveraging Silverlight (single programming model for both), so that I can access all the same content from everywhere, and automatically takes advantage of Smooth Streaming for videos.
  • It integrates with home security cameras and provides those both in the home (i.e. monitor the baby upstairs on a PiP window) or via the web (i.e. watch my home while on vacations) leveraging Live Smooth Streaming.
  • It empowers a huge plugin community that can create cool advanced features like face detection on photos and videos and security recordings, provide filtered views of those, map pictures with geocoding, provide a "home connection point" where a GPS could submit road trip info, etc. etc.

 

For now, I got my Dell Zino HD (shipping soon) and I'm looking forward to selling the assorted Frankenstein media setup I have right now.

The future looks bright for the smart home :)

posted Sunday, January 03, 2010 12:55 PM by kzu with 4 Comments

How to mock extension methods

. without paying for a TypeMock Isolator license to do it ;-)

There's going to be no magic here. You have to explicitly design for testability. That's one of the things I like about mocking: if you can mock a dependency, then it means your design is loosely coupled (e.g. not tied to a particular implementation of that dependency), and you're not "cheating or taking any shortcuts. If a test can replace a dependency at test-time, your'll surely be able to replace the real implementation with something different when/if time comes to do so.

Extension methods are tricky because they are static methods, really just syntactic sugar for a "good" old static class with static methods (typically a "helper" of some sort. But what is special about them, is that they show up (provided you have the right usings/imports) in the target type API as if they were its own instance methods. This is significant, because it also means that it's very easy to pollute the target type API as you (and other referenced libraries) keep piling up these methods on it.

I therefore prefer an approach where you group your extensions under a single API, and access that API via a single extension method on the target type that becomes the entry point to your extensions. For example, say you have an IPerson interface, and you want to add secutity-related helper methods that you can use consistently from other logic or services. One way of adding a GetPermissions security helper extension method (that will get the rights of the user over a given resource, for example), would be to plug it right into IPerson as an extension method:

[Flags]
public enum Permissions
{
    Read = 0, 
    Modify = 1, 
    Delete = 2, 
    FullControl = Read | Modify | Delete
}

public static class SecurityExtensions
{
    public static Permissions GetPermissions(this IPerson person, Uri resource)
    {
        // get permissions for the given resource from somewhere
    }
}

This would get you the API right on the IPerson object:

plainextension

If you go overboard with this "extension in the root" approach, you might end up with an ugly looking assorted collection of helpers attached to the main class, such as what happened to the UML APIs in Visual Studio 2010. Look at the before and after we reference and import the assembly containing the extensions to IClass (the interface that represents a class in a UML Logical Class Diagram):

classplain

After referencing Microsoft.VisualStudio.Uml.Extensions.dll and adding the corresponding using/import:

classextensions

(I pasted together four pages of intellisense for added effect, but you see the point, rigth?)

Extension Interfaces

Another alternative is to group extension methods that provide related functionality under what I'd extension interfaces. In our person example, we might find out that the security-related methods start growing, and we'd like to keep the main API clean, so we introduce the ISecurity extension interface, and provide an extension method that is the entry point to it:

public interface ISecurity
{
    Permissions GetPermissions(Uri resource);
}

public static class SecurityExtensions
{
    public static ISecurity Security(this IPerson person)
    {
        throw new NotImplementedException();
    }
}

Now, the consumer of the IPerson object can see that there is security-related behavior available to him, but won't see what those are unless he needs to:

extensioninterface

Typically, the SecurityExtensions class will instantiate a non-public implementation of ISecurity that does the real work, passing the person to work on as a constructor argument:

internal class Security : ISecurity
{
    private IPerson person;

    public Security(IPerson person)
    {
        this.person = person;
    }

    public Permissions GetPermissions(Uri resource)
    {
        // get the real permissions for the person 
        // field we have received, for the given resource
        throw new NotImplementedException();
    }
}

public static class SecurityExtensions
{
    public static ISecurity Security(this IPerson person)
    {
        return new Security(person);
    }
}

The attentive reader might have noticed that, being a regular interface, the extension interface now can expose properties where it makes sense, overcoming the lack of support for extension properties in C#. For example we could add a Roles property quite easily:

extensionproperty

And because the extension interface is nothing more than a fluent interface in the end, you can use the trick I blogged about before to hide those pesky System.Object members:

fluentextension

How to mock extension methods, again?

Back to the testing subject, in order to test the Update method above, we'll need to replace the ISecurity implementation, right? Because we followed the extension interface design approach, we now have a single extension method to replace, the one that creates the default implementation of the ISecurity inteface. And if you look at that method, all it is being a factory for creating an implementation of ISecurity given an IPerson:

public static class SecurityExtensions
{
    public static ISecurity Security(this IPerson person)
    {
        return new Security(person);
    }
}

So for testing purposes we can just add an internal factory that will isolate the extension method behavior, and that we'll replace for testing purposes:

public static class SecurityExtensions
{
    internal static Func<IPerson, ISecurity> SecurityFactory = person => new Security(person);

    public static ISecurity Security(this IPerson person)
    {
        return SecurityFactory(person);
    }
}

The test for the Update method above, which will have internals visibility enabled from the project under test, will simply replace the factory with one that returns a mock:

public void WhenPersonHasNoModifyPermission_ThenThrowsSecurityException()
{
    var security = new Mock<ISecurity>();
    security.Setup(x => x.GetPermissions(It.IsAny<Uri>())).Returns(Permissions.Read);

    SecurityExtensions.SecurityFactory = person => security.Object;

    var controller = new DocumentsController();

    Assert.Throws<SecurityException>(() => 
        controller.Update(new Mock<IPerson>().Object, new Uri("http://foo")));
}

And voila! We have just passed a test where the class under test uses an extension method:

public class DocumentsController
{
    public void Update(IPerson person, Uri document)
    {
        if (!person.Security().GetPermissions(document).HasFlag(Permissions.Modify))
            throw new SecurityException();

        // ...

Also note that the intenal Security class that implements ISecurity can also be fully tested in isolation.

 

Happy moqing!

 

PS: remember the focus of this post is on mocking extension methods, not on how to design security for your domain ;-). Feel free to mentally replace ISecurity with IFoo, GetPermissions with DoSomething, etc., as needed.

posted Tuesday, December 22, 2009 11:27 AM by kzu with 6 Comments

Resetting Visual Studio Experimental Instance to its super-clean initial state

If you are doing Visual Studio extensibility (VSX) work, you are probably aware of the existence of the Visual Studio "Experimental" instance. This is basically an instance of VS that has its own isolated registry, settings, extensions, etc. This allows you to test your extensions to VS without polluting your main development environment.

Sometimes, the environment might get corrupted for whatever reason, or it might be that you just want to test your extension with a clean environment after messing with it for a while.

The Visual Studio SDK does come with a tool to reset the experimental instance, available from your Start menu with the name "Reset the Microsoft Visual Studio 2010 Experimental instance". That will not, however, give you the pristine environment you got the first time you start the experimental instance to test your first extension.

In order to get a super-clean environment, here's what you need to do:

  1. Close any running instance of VS Experimental.
  2. Delete the entire folder %LocalAppData%\Microsoft\VisualStudio\10.0Exp
  3. Run regedit.exe
  4. Delete the registry key HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0Exp
  5. Delete the registry key HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0Exp_Config
  6. Run the command "Reset the Microsoft Visual Studio 2010 Experimental instance" from your start menu.

 

Now you'll have a fully restored environment. Also, any existing extensions you have in your main environment will be copied over to the experimental instance, with one caveat: you'll have to manually enable them from the Extension Manager UI from a running experimental instance to get them running.

If you've been doing VSX work in previous versions of VS, you'll sure appreciate the drastically simplified install/reset experience enabled by the new deployment mechanism in VS2010 via Extension Manager and VSIX files. If you have not, then this doesn't sound so scary anymore, does it? ;-)

 

Happy extending!

posted Tuesday, December 22, 2009 11:24 AM by kzu with 1 Comments

Linq to Mocks is finally born

Last time I announced Linq to Mocks, some said Moq didn't actually have anything to do with Linq. Despite the heavy usage of lambda expressions and expression trees, the "q" in Linq is for "query" after all. And they were right, of course, but it was fun anyway, and the name is definitely cool IMO :).

But this time around, I'm happy to say that it's finally true. What the next version of Moq (early beta readily available now) allows you to express in a very declarative way essentially is:

from the universe of mocks, get me those that behave like this
(thanks Fernando Simonazzi for coming up with this phrase :))

Rather than procedurally defining how the mock will behave, its specification is part of the query:

ControllerContext controllerContext =
    (from context in Mocks.Query<ControllerContext>()
     where context.HttpContext.User.Identity.Name == "kzu" &&
           context.HttpContext.Request.IsAuthenticated == true && 
           context.HttpContext.Request.Url == new Uri("http://moq.me") &&
           context.HttpContext.Response.ContentType == "application/xml"
     select context)
    .First();

A few things to notice:

  1. The query returns an infinite list of mocks that behave according to the specification/query. You typically get the first of such list.
  2. The resulting objects are of the actual mocked type, not Mock<T>, so there's no need to do controllerContext.Object anymore. The reasoning for that is that typically you would be able to fully setup the mock in the query, hence there'd be no need to get the Mock<T> back, unlike new Mock<T> where you do need to set it up.
  3. Fluent mocking happens automatically within the query. And even better, you're NOT limited to just property accesses. *Anything* that is a valid Setup on a mock can appear anywhere in the fluent mock traversal (i.e. context.HttpContext.GetSection("server") == configuration)
  4. You can have multiple mocks within the query and set them all up together.
  5. If you want to access these multiple mocks afterwards, you can just return all of them using an anonymous type projection (select new { Context = context, Configuration = configuration } ).

Here's a more comprehensive example of setting up two mocks at the same time:

ControllerContext controllerContext =
    (from context in Mocks.Query<ControllerContext>()
     from configuration in Mocks.Query<ServerSection>()
     where context.HttpContext.User.Identity.Name == userName &&
           context.HttpContext.Request.IsAuthenticated == true && 
           context.HttpContext.Request.Url == new Uri("http://moq.me") &&
           context.HttpContext.Response.ContentType == "application/xml" &&
           context.HttpContext.GetSection("server") == configuration && 
           configuration.Server.ServerUrl == new Uri("http://moq.me/api")
     select context)
    .First();

Finally, if you needed to access both the context as well as the configuration from the results of this query, you could do:

var mocks =
    (from context in Mocks.Query<ControllerContext>()
     from configuration in Mocks.Query<ServerSection>()
     where context.HttpContext.User.Identity.Name == userName &&
           context.HttpContext.Request.IsAuthenticated == true && 
           context.HttpContext.Request.Url == new Uri("http://moq.me") &&
           context.HttpContext.Response.ContentType == "application/xml" &&
           context.HttpContext.GetSection("server") == configuration && 
           configuration.Server.ServerUrl == new Uri("http://moq.me/api")
     select new { Context = context, Configuration = configuration }))
    .First();

MyController controller = new MyController { ControllerContext = mocks.Context };
// Do something with the configuration object...
ServerSection config = mocks.Configuration;

Next question would be how to setup exceptions to be thrown, and how to verify? You just use the existing Mock.Get functionality:

Mock.Get(controllerContext).Setup(...)
// or verify
Mock.Get(controllerContext).Verify(...);

Just for the sake of comparison, the equivalent "procedural" code to setup the same mock shown in the complete example above, you'd currently do:

var context = new Mock<ControllerContext>();
var configuration = new Mock<ServerSection>();

context.SetupGet(c => c.HttpContext.User.Identity.Name).Returns(userName);
context.SetupGet(c => c.HttpContext.Request.IsAuthenticated).Returns(true);
context.SetupGet(c => c.HttpContext.Request.Url).Returns(new Uri("http://moq/me"));
context.SetupGet(c => c.HttpContext.Response.ContentType).Returns("application/xml");
context.SetupGet(c => c.HttpContext.User.Identity.Name).Returns(userName);
context.Setup(c => c.HttpContext.GetSection("server")).Returns(configuration);
configuration.Setup(c => c.Server.ServerUrl).Returns(new Uri("http://moq.me/api"));

Yes, the query version has one more line of code, the .First() call. Yes, it's gonna be largely a matter of personal style and preference, just like many prefer invoking .Where(…) and .Select(…) instead of from…where…select.

Choice is good in this case, IMO.

There are many more features in this upcoming version of Moq. I'll try to blog about those too before/after we ship :). But this is my favorite!

Go get it!

posted Thursday, August 13, 2009 6:53 AM by kzu with 6 Comments

Improved type safety when dealing with generic types, generic methods and reflection

Compile-time safety is always important, as it reduces the chances that a refactoring can break existing code that compiles successfully. This benefit took me previously to the path of using expression trees to achieve strong-typed reflection.

There is, however, an alternative that works on previous versions of .NET and doesn’t involve expression trees. It essentially involves creating a delegate of the target method, and using the delegate properties to get to the corresponding MethodInfo:

Action<string> writeLine = Console.WriteLine;
MethodInfo writeLineMethod = writeLine.Method;

Note that the code above is very explicit about which overload of the WriteLine method to pick: the one with a single string argument and a void return value. You can leverage Action and Func various overloads to represent pretty much any method invocation. Also, if those do not fit, you can still create your own delegate type. The benefit, clearly, is that you now can refactor the defining class or method and the change will be picked automatically.

The above example dealt with a static method call. Instance methods require an actual instance, but you can still use the technique to reflect over the method metadata What about instance methods? You certainly don't want to instantiate the target type just to do a more safe reflection over it, right? Well, because we're only retrieving a delegate to a method, but not actually executing it, passing a null is perfectly fine:

Func<object> cloneable = aCloneable.Clone;
MethodInfo cloneMethod = cloneable.Method;

How do you deal with generic classes, though?

public interface IFoo<T>
{
   void Do();
}

In order to get the method, you need to have an actual concrete type of IFoo<T>, so you can just any type:

Action doMethod = aFooOfString((IFoo<string>)null).Do;
MethodInfo doMethodInfo = doMethod.Method;

The same trick applies to generic methods, but you need to get the generic method definition at the end:

public static class Factory
{
    public static T Create<T>() { ... }
}
...
Func<string> createMethod = ((IFactory)null)Factory.Create<string>;
MethodInfo genericCreate = createMethod.Method.GetGenericMethodDefinition();

With these combined tricks, you don't need to (ab?)use expression trees for certain scenarios and it's backwards compatible with .NET 2.0.

posted Monday, August 10, 2009 8:00 AM by kzu with 3 Comments

MAB ContainerModel / Funq: a transparent container

From the point of view of the user of the container, he doesn't have to do anything at all. He just creates classes as usual:

public class EditCustomersPresenter
{
    public EditCustomersPresenter(IEditCustomersView view, ICustomerRepository repository)
    {
        this.view = view;
        this.repository = repository;
        view.Presenter = this;
    }
    ...
}

Container configuration is done through lambdas that specify which object to construct for the registered type. For the view used by this presenter (an EditCustomersView form), it would look like:

var container = new Container();

container.Register<IEditCustomersView>(
        c => new EditCustomersView());

In this sense, you can think of Funq as a glorified dictionary of delegates to instantiate objects (it does a bit more than that, though). In the above case, the class we're constructing doesn't need any dependencies. If it did, such as the presenter above, you can use the "c" argument to the lambda, which is the container itself, which you can use to express that you'll need to resolve the dependencies to pass on:

container.Register(
    c => new EditCustomersPresenter(
        c.Resolve<IEditCustomersView>(),
        c.Resolve<ICustomerRepository>()));

Note that because this is a lambda/delegate, it won't actually be executed until the presenter is needed. Moreover, note how the type to register can be omitted if it matches the created object type (i.e. you don't want to register the presenter as an interface).

Because this is configuration, you can also pass configuration data on your registrations:

container.Register<ICustomerRepository>(
    c => new CustomerRepository("[CONNECTION STRING TO DB / AppSetting / etc]"));

Moreover, the object itself can expose properties that affect its behavior, which can also be initialized at this point using C# 3 object initializer syntax:

container.Register<ICustomerRepository>(
    c => new CustomerRepository("...") { IsAudited = true });

More lambda "magic" makes it possible to arbitrarily initialize the object when it's constructed, by using the InitializedBy fluent method:

container
    .Register<ICustomerRepository>(
        c => new MemoryCustomerRepository())
    .InitializedBy((c, r) =>
    {
        // Initialize with some fake data.
        r.Create(new Customer { FirstName = "Joe", LastName = "Doe" });
        r.Create(new Customer { FirstName = "Sarah", LastName = "Smith" });
        r.Create(new Customer { FirstName = "Mary", LastName = "Brown" });
    });

The InitializedBy method receives a lambda with two arguments: the first is again the container, in case we need to further resolve dependencies, and the second is the instance created by the first delegate (at the time it was needed), typed to the registration type (ICustomerRepository in this case, or the constructed instance type if you omitted it) passed on so that you can call methods, set properties, etc. on it.

Lazy resolve

Let's say a service needs to be able to create/resolve a dependency on-demand. Typically, you'd create a factory for that, and have the factory instantiate the object through the container. Funq provides built-in support for this via factory functions as a built-in concept.

If you had a controller that instantiated use cases as needed, you wouldn't want to create all the possible use case classes up-front. So let's say you have a registered use case class:

container.Register<IUseCase>("AddCustomer", c => new AddCustomerUseCase());

Note that instances can be named so that you can register many under the same interface.

The controller class would need to run this use case at some point. It would have a constructor dependency not the actual instance, but on a resolver delegate to it:

public class CustomersController
{
    public CustomersController(Func<IUseCase> addCustomerResolver, ...)
    {
        ...
    }
    public void AddCustomer()
    {
       // invoke the function, which would create the use case as registered.
       IUseCase useCase = addCustomerResolver();
       useCase.Run();
    }
}

You'd register the controller slightly different, by lazy resolving the use case dependency

container.Register(
  c => new CustomersController(
           c.LazyResolve<IUseCase>("AddCustomer"))

The LazyResolve method works (and provides same overloads) just like the Resolve, but it returns Func delegates instead, so that the actual invocation to Resolve is delayed until you execute the delegate. This is very useful in many scenarios, and avoids many one-line factories.

Passing constructor arguments

Another common scenario we wanted to support without sacrificing performance was to allow passing constructor arguments to these registered "factories".  Let's say you have a Queue object that needs the queue name:

If you have the following queue class:

public class Queue : IQueue
{
    public Queue (string queueName)
    {
        ...
    }
}

You'd register it like so:

container.Register<IQueue, string>(
    (c, name) => new Queue(name));

Note how you specify in addition to the service type, the type of the arguments that it requires. In order to resolve it, you must therefore pass a string for the invocation:

var queueOut = container.Resolve<IQueue, string>("outgoing");

This would allow you to configure something like a notifications service with two queues with different names:

public class NotificationService : INotificationService
{
  public NotificationService(IQueue input, IQueue output)
  {
    ...
  }

And its corresponding registration would be:

container.Register<INotificationService>(
    c => new NotificationService(
           c.Resolve<IQueue, string>("in"),
           c.Resolve<IQueue, string>("out")
);

This also works for lazy resolution, so if the service creates the queues on-demand, it could be defined as follows:

public class NotificationService : INotificationService
{
  public NotificationService(Func<IQueue, string> queueResolver)
  {
    ...
  }
  public void Reply(string message, ...)
  {
     using (var queue = queueResolver("out"))
       queue.Enqueue(message);
  }

Note that the service invokes the resolver passing the queue name. Registration would be slightly different now:

container.Register<INotificationService>(
    c => new NotificationService(c.LazyResolve<IQueue, string>())
);

 

Passing arguments can also be done at registration time for dependencies. Imagine you introduce a IQueueFactory service that must receive a queue name in its constructor so that its caller can create multiple instances of the same queue object as needed, without knowing the queue name at all. A notification service would use such a factory as follows:

IQueueFactory factory;

public NotificationService(IQueueFactory factory)
{
    this.factory = factory;
}

public void Send(string text)
{
    using (var queue = factory.CreateQueue())
    {
        queue.Enqueue(text);
    }
}

The service doesn't know which particular queue it's going to send the message to. And (for whatever reason) it needs to create a new queue whenever it needs it. The registration for such an object, would simply be:

container.Register<IQueueFactory, string>(
    (c, name) => new QueueFactory(name));

Note how the registration overload we're using specifies that in addition to the service type, we'll need a string argument to construct the object. Now it's time to register the notification service, which (say) we have two of: input and output notifications

container.Register("outgoing", 
    c => new NotificationService(c.Resolve<IQueueFactory, string>("out-queue")));

container.Register("incoming", 
    c => new NotificationService(c.Resolve<IQueueFactory, string>("in-queue")));

What's happening here is that we're registering the same service twice with different names, and resolving the queue factory dependency passing the desired queue name that will be received by its implementation. This way, we have externalized the dependency on this knowledge from the notification service.

 

The same effect (of "fixing" a lambda parameter to a given value) can be achieved by just currying the function returned from LazyResolve :)

posted Monday, April 20, 2009 9:26 AM by kzu with 4 Comments

Mobile Application Blocks ContainerModel / Funq: an introduction

If you follow my blog, you probably heard about Funq, and maybe you even watched the screencasts I did about it while developing it (yeah, I'm missing a bunch of new ones!).

When we started working on a rev for the original Mobile Client Software Factory v1 for patterns & practices, we had a list of top-priority issues and feature requests expressed by the community and the advisory board. Very high on the list was *removal* of the Composite UI Application Block (CAB) from the blocks, as its performance impact was too great for mobile apps.

Despite all my efforts to make CAB more performant (including compile-time codegen a-la sgen of the injection policies), I just couldn't make it fly. It was simply not designed for a constrained execution environment where things like allocated bytes and JIT compilation DOES matter.

Yet, we didn't want to just rip-off CAB and leave nothing to replace it. Designing an application in a loosely coupled way and enabling testability are important goals that we wanted to encourage in the mobile world. So I decided to start from scratch on the simplest possible DI container we could give mobile developers that could add sufficient value to their architectures without compromising application cold boot speed or general runtime performance.

The culmination of that effort is a very simple container (I claim anyone can crack open the source code and understand it quite easily ;)) that outperforms every other DI container on the market by orders of magnitude. I named the new Mobile Application Blocks (MAB) DI framework ContainerModel. p&p already has a desktop/silverlight offering in the space with Unity, so with their authorization, I forked (but keep 100% in sync) the project into Funq, which provides the desktop and silverlight binaries and source. So, MAB ContainerModel == Funq. It may be that the latter adds features that only apply to the desktop and/or silverlight (i.e. ASP.NET MVC and WCF integration, etc.), but the core will always remain in sync.

 

The performance results for the CF version are:

image

Here you can see how bad ObjectBuilder v1 (the backbone of CAB) was, even at a generous (estimated average) 7x performance gain via compile-time codegen, resulting in a 133x overhead! (without the obgen compile-time tool, it would be ~900x :S).

In comparison, the new ContainerModel is a modest 12x slower than no DI at all, and still orders of magnitude faster than a quick port to CF of both Autofac and Unity.

On the desktop, numbers are also equally encouraging:

image

This shows only the top 3 performing containers, as including others such as Windsor ruins the graph (it's 6x slower than Autofac, about 80x slower than Funq).

As I said, key performance counters you typically don't measure on the desktop are of critical importance on the CF. So I developed the container while carefully watching the impact on those. Here are the results and comparison:

image

As you can see, Unity does significantly better than the original ObjectBuilder, but it was still not enough for CF. The new ContainerModel overhead is barely noticeable across all areas, with consistently low impact.

To be honest, the comparison on the CF is unfair to the other frameworks, because none of them were designed nor optimized for use on mobile devices. I just ported enough of the code to get them to compile and run.


Over the next few posts, I'll explain more about its design and features. Stay tunned!

posted Friday, April 17, 2009 5:27 AM by kzu with 2 Comments

What would you like to see in Enterprise Library 5.0?

There are few groups within Microsoft that are as open and so quick to deliver as patterns & practices. When you give them feedback or request features, chances are you'll see them implemented within months, rather than years (if they get enough support of the rest of the community!).

It's now time to engage in shaping EntLib 5.0! From Grigori's blog:

At this point, we would like to invite you to select and prioritize candidate features/stories you care about. Please review them carefully along with the associated effort estimates and cast your votes.  Do remember to stay within the budget (100 points). Here's the link to the online survey.

I wish the format for the survey was more user friendly, but don't let that stop you from voting!

posted Monday, March 30, 2009 1:13 PM by kzu with 1 Comments

Crazy Linq: replacing multiple and nested foreach statements with a query

Objective of the method: determine whether the given EnvDTE code class contains the given GeneratedCodeAttribute:

"old" foreach/if approach:

private bool IsPresentationModel(CodeClass2 baseClass)
{
    foreach (CodeClass2 pc in baseClass.PartialClasses)
    {
        foreach (CodeAttribute2 attr in pc.Attributes)
        {
            if (attr.FullName == typeof(GeneratedCodeAttribute).FullName &&
                attr.Value.Contains(ThisAssembly.Title))
            {
                return true;
            }
        }
    }

    foreach (CodeAttribute2 attr in baseClass.Attributes)
    {
        if (attr.FullName == typeof(GeneratedCodeAttribute).FullName &&
            attr.Value.Contains(ThisAssembly.Title))
        {
            return true;
        }
    }

    return false;
}

Note that most collections in the EnvDTE code model are not IEnumerable<T>. Here's the linq-ified version:

private bool IsPresentationModel(CodeClass2 baseClass)
{
    return baseClass.PartialClasses
        .OfType<CodeClass2>()
        .Select(cc => cc.Attributes)
        .SelectMany(ce => ce.OfType<CodeAttribute2>())
        .Concat(baseClass.Attributes.OfType<CodeAttribute2>())
        .Where(attr =>
            attr.FullName == typeof(GeneratedCodeAttribute).FullName &&
            attr.Value.Contains(ThisAssembly.Title))
        .Any();
}

The SelectMany invocation is needed to flatten the list of attributes from all partial classes :)

Update: Changed Count() to Any() which is generally more optimal, as I only care about knowing whether there's at least one such attribute, regardless of how many.

posted Friday, March 27, 2009 6:42 AM by kzu with 5 Comments

A picture is worth a thousand words: is XML dying?

XML-dying

(does that answer Jeremy's question too?)

posted Sunday, March 15, 2009 7:16 PM by kzu with 3 Comments

Approaching Behavior Driven Development (BDD) from a Test Driven Development (TDD) perspective

Over the years doing TDD, I'm getting increasingly concerned about the value my test fixtures are bringing to the table in terms of documenting features and expected behavior.

So far, I followed the typical pattern in TDD of creating one class (fixture) per object under test: if I have DirectoryService, I create DirectoryServiceFixture. Inside the fixture (and for the past couple years now), I've been pushing teams I work with to stick to a convention where every test method is prefixed with the word "Should": this seems to be at least a bit aligned with BDD, in the sense that it causes your mind to shift into explaining what behavior you're exercising.

But sometimes a sentence of that format doesn't make a lot of sense, and I started to get sloppy with it. And I'm at the point where I desperately need a better way of thinking about my tests, as right now I can't really look at a test run result and figure out what it is that the system does really, which are the scenarios and the contexts.

I like it that BDD does away with the "Test" word, which in TDD is hopelessly misleading, as mentioned by Scott Bellware, and evidenced in Joel's awful misunderstanding of what it's all about. Starting a presentation or discussion on TDD invariably derives into questions about the value of testing, the role of QA, and so on. I'm tired of that, as it has NOTHING to do with that.

Beware that (in my opinion) there's nothing terrible new or revolutionary about BDD. I believe its value lies in being a form of neuro-linguistic programming (as mentioned in the NSpec page) which leads you to a different way of thinking and expressing the behavior you code. It's mostly a way to structure and name the code you already write if you're doing TDD, so that it has more value as a documentation tool and a communication tool with users and business stakeholders. There are, however, some BDD libraries that go to the extreme of making the code look absolutely alien. You don't have to use them in order to apply the principles, though.

So, during my exploration of BDD, I found the following resources quite useful:

  1. BDD Intro by Dave Astel: the easiest to read and understand, and to map to current TDD practices, without convoluting the practice with too much language noise (unlike Dan North's).
  2. Beyond TDD: BDD, by Dave Astel too. A good introductory video conference to BDD and what are some core principles, although I do not agree on the emphasis he puts in "stay away of state testing", but other than that, pretty good. It makes me realize that something like Moq can support this style very well.
  3. Introducing BDD, by Dan North, who coined the term. Straightforward, easy to understand, and to the point.
  4. Some alternative ways of reading context/specification: a *very* helpful and dispassionate comparison of the various alternative/conventions for doing BDD. I'm kind of leaning towards the AAA syntax as it's more familiar to what I'm doing already.
  5. Behavior-Driven Development: in Scott's typical style, a rather long way to explain it all (still quite useful especially for newcomers). I don't like the Context/Because convention, though. It doesn't flow very well IMO.

 

I'm still learning about it. Will try to apply it in a concrete project and keep you posted.

Got to get my blog on a decent engine so that you can post comments! Sorry :(

posted Friday, March 13, 2009 5:01 AM by kzu with 4 Comments

Making WCF services amenable to testing

You know that using WebOperationContext.Current is BAD for making your service implementation testable, don't you?

My friend Pablo Cibraro continued to evolve his ideas around decoupling your service implementation from this static dependency, and came up with the most simple yet totally unobtrusive (for production code) approach to this, which he calls WCFMock.

The idea is quite simple: you can leverage C# class aliasing functionality (which few know it even exists) to conditionally (i.e. DEBUG vs RELEASE builds) replace the WebOperationContext implementation, like so:

#if DEBUG
using WebOperationContext = System.ServiceModel.Web.MockedWebOperationContext;
#endif

What will happen here is that on DEBUG builds, the actual class invoked when your code calls WebOperationContext.Current will be different, and it will be the one that allows easy testability by providing interfaces for the context and all its properties. You can setup this mock context quite easily in your tests:

Mock mockContext = new Mock { DefaultValue = DefaultValue.Mock };
 
using (new MockedWebOperationContext(mockContext.Object))
{
  var formatter = catalog.GetProducts("foo");
}

// Just making sure the content type was properly set 
mockContext.VerifySet(c => c.OutgoingResponse.ContentType = "application/atom+xml");

 

Of course, WCF service implementations, in my opinion, should not contain much core, and be basically a REST/webservices facade on top of the actual implementation which is something that never depends on any WCF specifics. But for those cases where you must ensure some behavior from your service implementations, this is certainly the best way to do it.

posted Tuesday, March 10, 2009 1:29 PM by kzu with 3 Comments