Daniel Cazzulino's Blog :
How to get wi-fi network connectivity using Hyper-V
  1. Create a new Local Network with Virtual Network Manager (name it Hyper-V, for example)
  2. In the VHD, run msconfig.exe, in the Boot tab, click the Advanced options button, and select the Detect HAL option.
  3. Reboot the VM, reinstall the integration services and reboot again. Now you should get the new network adapter detected.
  4. Use ICS on the wi-fi network and select the local network Hyper-V as the one to share the connection with.
  5. To allow VPN access, you need to open a port (GRE) in the windows firewall as explained in http://help.wugnet.com/vista/VPN-server-configured-Generic-Routing-Encapsulatio-ftopict116489.html

posted Thursday, June 25, 2009 3:51 PM by kzu

Live Mesh as an application platform

The potential

You surely read quite a bit about Live Mesh. Oran Dennison has number of very technical and insightful posts on various aspects of the underlying platform.

Recently, we run an internal prototype to  build an application on top of Live Mesh. I’m not talking about the kind of the typically showcased consumer-centric application where it’s all about sharing my personal photos, apps and videos with friends and family. I’m talking about a typical app for collaboration, involving group discussions (conversation-oriented like gmail), chat and shared calendar. Think about the aspects of Groove that are missing today from Live Mesh :).

The benefits of building an application on top of Live Mesh infrastructure are compelling:

  1. Built-in authentication, authorization and membership/account management via Live IDs
  2. Built-in transparent offline support (programming against the local Live Operating Environment is the same as for the cloud one)
  3. Automatic synchronization across nodes/users, with built-in conflict detection and preservation (which is different than conflict *resolution*, which is typically application-specific)

All these you’d have to build yourself if you were to develop an app requiring offline support. And compared to the other offerings such as Astoria Offline, Live Mesh certainly seems to be the one ahead of the crowd in terms of maturity.

With such an infrastructure in place, surely to be included sooner or later in every Windows box (with support for Mac and hopefully ported to Linux maybe via http://mesh4x.org?), it could become the obvious choice for pretty much any application. You’d be using Live Mesh as a general purpose store for your data, like a database. Imagine not having to think about offline, synchronization, authentication and authorization ever again! It almost sounds too good to be true.

In true Microsoft fashion, they have set to build a platform for all developers to leverage, not just a “file sync thinghy” like Dropbox, FolderShare or the myriad others. Being based on open standards (ATOM and FeedSync), it also allows others to join the platform and clears the doubts regarding vendor lock-in: you own the data, and it’s readily available for you to consume via a standard and documented API and format.

Social Applications

A somewhat less evident benefit of the platform is the ability to incorporate social networking capabilities right inside the application. Rather than going to a social network site/app to tell your friends which movies you liked, just rank the movie from within the player when you’re done watching it: all your friends using the same app can not only receive the rank but also know what you’re watching *right-now*.

Same principle applies to any application, where you could start ad-hoc collaboration with other users based on the current activity (i.e. we’re all filling out a form and you’re having a problem understanding something: you could just ask the other users who are working on the same form, or who have just completed it successfully), and even perform some of those together, such as browsing, authoring a document, etc. If you add the live mesh remote desktop functionality in the mix, you can imagine some very interesting possibilities.

So far, Live Mesh hasn’t introduced the concepts of networks and friends. Invites are for any Live ID user, regardless of whether they are in my contacts list or not. And it’s good that they haven’t mixed the two things at this point. We can share an application/Mesh object without being “friends” (we’re not in each other’s Messenger contact list). Over time, it would be interesting to allow the application developer to leverage something more social networking-oriented, such as inviting “my family” or “my coworkers” to share an application. I think this will eventually come to the platform, as the concept of groups in Live Messenger has silently evolved quite a bit, but they already have enough on their plate to work on for now.

The current shortcomings

The prototype didn’t end up very well, unfortunately. A number of limitations of the current (as of Apr 2009) Live Framework CTP prevent it from being used for general purpose client application development (I have no idea of mesh-enabled web application scenarios).

As a believer on the usefulness of reporting suggestions and bugs to Microsoft via Connect, each issue is followed by a link for you to vote if you think it’s important to get it fixed.

Invitations

First and foremost, there is a serious problem with the way invitations work: there is simply NO way for an application to accept invites, and currently the only way is to get an invitation *email* in your inbox with a link to your (web) live desktop site where you can accept the invitation. This is totally unacceptable for most applications. If we’re both using the same live mesh-powered application, and you invite me to share some data for it (in our prototype case, I could be invited to a discussion group), the obvious thing would be for me to receive a notification *in the application* that I’ve been invited, and be able to accept it right from there. Alternatively, I could receive the invitation via the Live Mesh notifier tray icon, and accept it from there too. Either way would work, but the current approach is simply impractical. Moreover, the UI says you’ve been invited to a “Live Mesh Folder”, which is totally misleading as accepting the invitation takes you to the live mesh desktop UI where nothing new seems to have happened after accepting (‘cause there’s no new folder to show!). I believe this to be a drawback of focusing too much on the file sharing “sample app” (I still believe Microsoft should open source it and use it as a showcase of what great things you can do on top of Live Mesh, but it should still be just another regular citizen in the mesh, with no more privileges as my own apps).

Generic Data Store

In order for Live Mesh to succeed as an application platform that you rely on to replace your typical database, it has to provide the same capabilities we’ve come to expect from them, and efficient and flexible querying is a critical part of it. Currently, even though Live Mesh allows you to store custom data (i.e. your entities, albeit in a rather XML-ugly way) in the entries, rich querying over that data is impossible. It’s even impossible to query over custom attributes or elements at the item level if you decide to go with the low-level Syndication API way.

Beyond just XPath-like querying, I think Live Mesh as a generic store should provide a LINQ provider like Astoria does, so that you can work with your data at the domain/entity level, and let the infrastructure handle the serialization and storage (i.e. partition entities across feeds, ensure referential integrity, etc.). I doubt anyone wants to be writing queries over ATOM feeds once you’ve become addicted to LINQ querying.

Online/Offline Inconsistencies

Even though API-wise it doesn’t matter whether you’re talking to the local LOE (Live Operating Environment) or the cloud LOE, the operations you can do vary in somewhat unpredictable (and certainly undocumented) ways. For example, you cannot create a MeshObject (the elemental unit of authorization and sharing) if you’re offline, or invite users, etc.

In order to enable true offline apps, at the bare minimum the current inconsistencies need to be addressed.

It’s also unclear how authentication works (or doesn’t) when you’re offline, or how you can achieve peer-to-peer synchronization in the absence of internet connectivity.

Conclusions

I remain excited by Live Mesh possibilities. I think it will be a game changer, and it will play an increasingly important role as a general purpose application platform. It won’t achieve all that overnight, and it will take a couple of revs to get the platform there.

I wouldn’t advise you to take a hard dependency on Live Mesh right-away. The Live Framework CTP is ahead of the public Live Mesh beta

posted Thursday, June 25, 2009 9:02 AM by kzu

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

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

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

Announcing the free ViewModel Tool

If you're doing any kind of WPF development, you probably read at least some of the links in this entry on WPF Patterns.

One common theme across all variants of the ViewModel pattern is that it always has to implement the INotifyPropertyChanged interface, which is the core interface driving the whole data-binding infrastructure in both WinForms and WPF. Implementing this interface is quite boring and repetitive, more so if you're using C# 3.5 automatic properties:

public class Customer
{
    public string FirstName { get; set; }
    public Address Address { get; set; }
    // other properties
}

We need now to add the event raising call to every setter, but in order to do that, we have to convert the automatic properties into regular ones, with the corresponding backing field, etc.:

public class Customer : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    Address _address;
    string _firstName;
 
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; this.RaisePropertyChanged("FirstName"); }
    }

    public Address Address
    {
        get { return _address; }
        set { _address = value; this.RaisePropertyChanged("Address"); }
    }

    // other properties

    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Pretty standard stuff. But wait, that Address property seems like it should also implement INotifyPropertyChanged! What's more, seems like we should also be tracking changes in nested/child objects and raising the change from the parent property too! (i.e. someone changes Address.City, the Customer.Address should be considered changed).

This quickly adds to the tedium, not to mention how error-prone all this is (just one copy/paste where you forget to change the property name) and also how annoying it gets when you need to refactor the code with all those strings.

Well, quite some time ago (back in 2007) we released an early version of a custom tool that would generate all this repetitive stuff for you. This tool has evolved quite a bit as we used it in various projects, and now we have a revamped release, which has been renamed to ViewModel Tool. The tool supports VS2008 on both C# and VB projects.

 

The tool can also generate (opt-in) ISupportInitialize, ISupportInitializeNotification and IChangeTracking implementations.

 

Enjoy and please report any issues you may find via the Issue Tracker (select ViewModel Tool as the component). Go get it!

posted Monday, March 30, 2009 1:03 PM by kzu

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

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

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

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

Moq 3.0 RTM!!!

I've just released the latest version of Moq :))))

It's quite late on an intense week at Redmond, so I'm just going to paste the relevant portion of the changelog:


Version 3.0


* Silverlight support! Finally integrated Jason's Silverlight contribution! Issue #73


* Brand-new simplified event raising syntax (#130): mock.Raise(foo => foo.MyEvent += null, new MyArgs(...));


* Support for custom event signatures (not compatible with EventHandler): mock.Raise(foo => foo.MyEvent += null, arg1, arg2, arg3);


* Substantially improved property setter behavior: mock.VerifySet(foo => foo.Value = "foo"); //(also available for SetupSet


* Renamed Expect* with Setup*


* Vastly simplified custom argument matchers: public int IsOdd() { return Match<int>.Create(v => i % 2 == 0); }


* Added support for verifying how many times a member was invoked: mock.Verify(foo => foo.Do(), Times.Never());


* Added simple sample app named StoreSample


* Moved Stub functionality to the core API (SetupProperty and SetupAllProperties)


* Fixed sample ASP.NET MVC app to work with latest version


* Allow custom matchers to be created with a substantially simpler API


* Fixed issue #145 which prevented discrimination of setups by generic method argument types


* Fixed issue #141 which prevented ref arguments matching value types (i.e. a Guid)


* Implemented improvement #131: Add support for It.IsAny and custom argument matchers for SetupSet/VerifySet


* Implemented improvement #124 to render better error messages


* Applied patch from David Kirkland for improvement #125 to improve matching of enumerable parameters


* Implemented improvement #122 to provide custom errors for Verify


* Implemented improvement #121 to provide null as default value for Nullable<T>


* Fixed issue #112 which fixes passing a null argument to a mock constructor


* Implemented improvement #111 to better support params arguments


* Fixed bug #105 about improperly overwriting setups for property getter and setter


* Applied patch from Ihar.Bury for issue #99 related to protected expectations


* Fixed issue #97 on not being able to use SetupSet/VerifySet if property did not have a getter


* Better integration with Pex (http://research.microsoft.com/en-us/projects/Pex/)


* Various other minor fixes (#134, #135, #137, #138, #140, etc.)

 

 

As usual, get it at http://moq.me/get, browse the API at http://api.moq.me or go to the project homepage at http://moq.me.

 

Enjoy!!!

posted Thursday, March 05, 2009 11:31 PM by kzu

Freeing up data and collaboration via the mesh

Last weekend, during the ALT.NET Seattle conference, I spoke for quite a while with Miguel de Icaza on the work we're doing with InSTEDD in the area of data synchronization. He was very excited, and wondered how come this wasn't more broadly known.

I realized that I hadn't blogged about it in a while, and it seems to me that this seemingly niche technology isn't getting the broad publicity it deserves. So I'll try to explain in simple terms what it is, and why it matters in many, many scenarios.

Imagine you have an application (mobile or desktop), which can be partially connected, and needs to synchronize data with a server, bi-directionally. That's not very innovative or disruptive, is it? Of course NOT. We have been doing this with various degrees of success and complexity for years.

What IS new, is that this time around we're not in front of a one-off, proprietary solution (more on that below). Also, there are many scenarios where the synchronization is not client-server, but true peer-to-peer: imagine doctors collecting disease reporting information, and sharing that with other doctors in the same area, but also with a central authority, which happens to just be one more node in the mesh. And what's also new

Such a scenario was implemented by contributing the mesh4x.org stack and the necessary plug-ins to the JavaROSA project. We also enabled such a scenario for the National Center for Public Health Informatics, US CDC, whose Director mentioned Mesh4x as one three key disruptive new technologies.

Eduardo Jezierski has an extensive for-geeks-only explanation on the whole Mesh4x vision and architecture, which you will surely find interesting.

How

Sync technologies have existed before. What's unique (I think) about Mesh4x is that it's based on an open specification that defines not only the wire format for these sync exchanges between nodes, but also the accompanying algorithm to detect conflicts in a consistent manner throughout the mesh. This specification is FeedSync, which is also embraced by Live Mesh, Sync Framework, etc. Mesh4x is an open source implementation of the specification, plus a set of adapters that expose data from multiple disparate data stores as a feedsync-compatible stream (i.e. MySQL, Excel, Access, SQL Server, KML files, whatever).

The importance of this adapter-driven approach is that instead of developing one-off sync strategies for every app/product you build, you only need ONE adapter per store TYPE (i.e. MySQL adapter will happily handle ANY such database). This frees you to focus on your value add, rather than the specifics of the not-so-simple problem domain of two-way sync.

 

The coolest feature ever, IMO, is the one that allows you to sync any adapter/data source with any other endpoint (which in turn may be any other adapter/data source) over plain ***SMS*** without any kind of data/internet connection. Just let that sink in your mind for a sec: we have a compressed, highly optimized, diff-based mechanism to sync ANY data source with ANY other data source over SMS (i.e. Access with MySQL over SMS, etc.), and this works TWO WAYS. (we do have HTTP-based sync too, of course!)

kind of like this

 

Marcelo Tondato has been the brain and dev behind these awesome features.

 

The main driving force for Mesh4x at this point is the work in the early detection and disaster response, part of InSTEDD's charter, but this technology applies to a wide range of scenarios. It's extremely exciting stuff, which is still providing real value right now, while at the same time evolving to include more and more features and scenarios.

Head over to http://mesh4x.org to give these guys feedback or learn more about the feature!

posted Thursday, March 05, 2009 4:05 PM by kzu

Leveraging ILMerge to simplify deployment and your users experience

ILMerge is one of those little-known gems that are an absolute must-have once you know how to apply them effectively to scenarios you didn't even think about.

Specifically, whenever you work on a multi-project solution that may also use external projects in turn, forcing your users to add (say) five assembly references just to your "entry point" library is clearly a bad experience. One example that comes to mind is Enterprise Library, where you add a minimum of 3 (IIRC) assembly references to use just about *any* block in isolation. If you use more than one, it quickly becomes quite a big list. Wouldn't you want to just give your users a single EnterpriseLibrary.dll?

Of course, you wouldn't do it if the price of that end-user simplicity was that you had to merge all your projects into a single one, complicating the dependency management and isolation between layers.

Also, if you use a bunch of external libraries, do you think your users care? Having a single Dll gives a feeling that "this is small, I can manage to take a dependency on this single library".

ILMerge to the rescue

The two scenarios are precisely ILMerge targets. It allows you to merge multiple assemblies into a single one, offering various options when doing so.

Let's see a concrete example: Moq. Moq is a (fairly popular) mocking library for .NET. It depends on two awesome external libraries: Castle.Core.dll and Castle.DynamicProxy2.dll, which provide the runtime interception infrastructure that Moq builds upon. Moq users are not exposed to that internal implementation detail ever: they just add a reference to a single Moq.dll assembly and that's it.

Typically, you will merge all the assembly references that have Copy Local = true (that is, dependencies that you distribute with your project as local, non-GAC'ed assemblies). So in order to automate this, in Moq we use an MSBuild target that is enabled only on release builds:

<Target Name="AfterBuild" Condition=" '$(Configuration)' == 'Release' ">
 <Exec Command="&quot;$(MSBuildProjectPath)..\Tools\Ilmerge.exe&quot; /ndebug /keyfile:$(AssemblyOriginatorKeyFile) /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(ReferenceCopyLocalPaths->'&quot;%(FullPath)&quot;', ' ')" />
 <Delete Files="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')" />
</Target>

Let's go over it:

  • The target has a condition that it will run only on Release builds.
  • The /ndebug parameter to ilmerge tells it to merge the PDB/debug files if present. Very handy :)
  • The /keyfile ensures that the merged assembly is signed with the same key file as your original project.
  • The /out is obvious, and we specify the MainAssembly item reference so as to replace the main output of the compilation.
  • Finally, the ilmerge tool receives the list of assemblies to merge. In addition to passing the IntermediateAssembly item which is the current output of the compilation process, we need to build a list of references that have CopyLocal set to true. We use the ReferenceCopyLocalPaths items, which is conveniently populated by the core MSBuild targets file Microsoft.Common.targets which is automatically imported in all your projects (and contains the resolved primary assembly references). We basically project the full path of those references and build a coma-separated list for ilmerge.
  • Finally, we delete all these references as they are now merged in the main assembly.

ILMerge Silverlight assemblies

For Silverlight, the above command will generate a desktop .NET assembly, which doesn't work in Silverlight, even if the original assembly was a Silverlight one. You need to pass a couple more arguments to ilmerge:

  • /targetplatform: need to explicitly specify v2 as well as the platform directory, which is basically the folder that contains mscorlib.dll. In my case, for Windows x64 and Silverlight 2.0, I specified: /targetplatform:v2,"C:\Program Files (x86)\Microsoft SDKs\Silverlight\v2.0\Reference Assemblies"
  • /lib: all other non-mscorlib assemblies need to be resolved to the Silverlight folder too, rather than the GAC/desktop ones. This switch receives the same path as the previous one.

So for Silverlight, the full task looks like this for Moq.Silverlight:

  <Target Name="AfterBuild" Condition=" '$(Configuration)' == 'Release' ">
    <Exec Command="&quot;$(MSBuildProjectPath)..\Tools\Ilmerge.exe&quot; /targetplatform:v2,&quot;C:\Program Files (x86)\Microsoft SDKs\Silverlight\v2.0\Reference Assemblies&quot; /lib:&quot;C:\Program Files (x86)\Microsoft SDKs\Silverlight\v2.0\Reference Assemblies&quot; /ndebug /keyfile:$(AssemblyOriginatorKeyFile) /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(ReferenceCopyLocalPaths->'&quot;%(FullPath)&quot;', ' ')" />
    <Delete Files="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')" />
  </Target>

Internalizing Dependencies

Merging multiple assemblies into one gets you a long way towards making your library look dead-simple. However, it may be the case that after adding a reference to your main assembly, users get a ton of foreign namespaces that they don't know about and they will never need to know about. These are the external dependencies of your library that are only used internally in your product.  You can change the visibility of all these dependencies just by specifying one additional switch to the ilmerge tool: /internalize.

Internalize receives an optional "exclude file" which is a text file containing a type name on each line for types you don't want to touch (leave their visibility intact). In Moq case, the runtime interception needs for runtime-generated code a few public types from Castle, so we provide an exclude file with the following content:

Castle.Core.Interceptor.IProxyTargetAccessor
Castle.DynamicProxy.AbstractInvocation
Castle.DynamicProxy.Generators.AttributesToAvoidReplicating

So the full Exec task looks like the following:

<Exec Command="&quot;$(MSBuildProjectPath)..\Tools\Ilmerge.exe&quot; /internalize:&quot;$(MSBuildProjectPath)ilmerge.exclude&quot; /ndebug /keyfile:$(AssemblyOriginatorKeyFile) /out:@(MainAssembly) &quot;@(IntermediateAssembly)&quot; @(ReferenceCopyLocalPaths->'&quot;%(FullPath)&quot;', ' ')" />

 

Happy ILmerging ;)

posted Monday, February 23, 2009 11:55 AM by kzu

Making extension methods amenable to mocking

The question of how to mock extension methods comes up frequently enough that I though I might give my opinion and solution to it (which does NOT include using TypeMock ;)).

A first differentiator is whether you control the definition of the extension methods or not. The latter case would be, for example, the built-in Linq extension methods (First, Count, etc. on IEnumerable<T>) and there's no way to mock them unless you use TypeMock. The former would be your own logic that you decide to place in extension methods for whatever reason, and that can be mocked using the technique I'll explain in this post.

 

Say you want to add the following extension method:

someType.SendTo(address); 

Such a method would be a static method on a static class:

public static class MessagingExtensions
{
    public static void SendTo(this SomeType target, string address)
    {
        // Do something
    }
}

Now, instead of declaring it like that, which makes it impossible to mock it using Moq or Rhino Mocks, you define a static method "entry point" for your extensions related to (say) messaging of objects, like so:

someType.Messaging().SendTo(address); 

And your static class changes as follows:

public static class MessagingExtensions
{
    public static IMessaging Messaging(this SomeType target)
    {
        return MessagingFactory(target);
    }

    static MessagingExtensions()
    {
        MessagingFactory = st => new Messaging(st);
    }

    internal static Func MessagingFactory { get; set; }
}

The basic idea is that you take all the static extension methods (i.e. SendTo) and move them to an interface, which can be easily mocked, and make the static class use a factory to construct instances of that interface. This factory can be replaced by a friend test assembly for mocking purposes.

Note that the actual class that will expose the former extension methods will need to have access to the target instance that was "dotted" to enter the extension. Hence, it will basically keep that instance around ready for the time you invoke an actual method without passing the target (it's like caching the "this" if you think about it, which you do get on the extension method):

public interface IMessaging
{
    void SendTo(string address);
}

internal class Messaging : IMessaging
{
    SomeType someType;

    public Messaging(SomeType someType)
    {
        this.someType = someType;
    }

    public void SendTo(string address)
    {
        // Do something with someType and the address.
    }
}

A test would simply replace the factory and make it return a mock:

var mockMessaging = new Mock();
MessagingExtensions.MessagingFactory = st => mockMessaging.Object;

This is more work, I know, but now you can mock this dependency without resorting to black magic. Plus, it's all plain OO once you get past the initial extension method call, and you also gain better control of "extension explosion" by defining the entry points that group related functionality.

 

This may be useful if you have objects that are heavily extended by external classes or modules.

 

And here I dub this technique the "Extension Method Entry Point Pattern" :)

posted Thursday, February 19, 2009 10:15 AM by kzu

How to install Intel WiFi Link 5300/5100 drivers for Windows 7 Beta

I just couldn't resist going for the brand new beta which is being praised quite a bit when I got my new Lenovo X200.

I used a trick I got from Pablo on how to quickly install Windows 7 from a pendrive (quickly as in <15'!!!), and was up and running pretty fast. Right out of the box I got LAN connectivity, and installing all remaining updates I was in pretty good shape. A few drivers missing, but nothing critical, except for the ***WiFi*** drivers!

See, the page for the Lenovo X200 shows you the Intel WiFi Link 5100 and 5300 as options (which I used to built mine), but the Lenovo X200 drivers downloads page doesn't show ANY downloads for them for ANY OS!!!

So I went to the source, got the bare drivers, unzipped them, right-clicked the unrecognized device (Network Device or something like that), clicked "Update Driver" and specified the path to the unzipped drivers. Worked like a charm and I'm now thoroughly enjoying the new taskbar...

posted Tuesday, February 17, 2009 1:29 PM by kzu

Tip: how to tell a regular method apart from property getter/setters and event add/remove

Rather than typical code like:

private static MethodInfo GetFirstMethodWithReturnType(Type type)
{
    return
        type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
            .Where(method => !method.Name.StartsWith("get_") &&
                                !method.Name.StartsWith("set_") &&
                                !method.Name.StartsWith("add_") &&
                                !method.Name.StartsWith("remove_"))
            .FirstOrDefault(method => (method.ReturnType != typeof(void)));
}

You can simply do:

private static MethodInfo GetFirstMethodWithReturnType(Type type)
{
    return
        type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
            .Where(method => !method.IsSpecialName)
            .FirstOrDefault(method => (method.ReturnType != typeof(void)));
}
IsSpecialName returns true for property getters/setters and event add/remove :)

posted Friday, February 06, 2009 7:02 PM by kzu

How to upgrade Atom 0.3 feeds on the fly with a custom XmlReader for use with WCF Syndication APIs

Even now that Atom 1.0 has been approved and official for some time, there's a feed every now and then that still uses Atom 0.3 (i.e. Google News! http://news.google.com/?ned=us&topic=w&output=atom).

The .NET APIs for feeds, System.ServiceModel.Syndication, handles RSS 2.0 and Atom 1.0 fine, and you just have to make a single call to load a feed regardless of its format:

SyndicationFeed.Load(xmlReader);

I searched the web looking for an easy answer, but I couldn't find any that would let me seamlessly plug into the .NET APIs to do the feed format upgrade on the fly. So I put one together myself :)

I found Aaron Cope had created XSLT stylesheets to transform Atom 0.3 to RSS 1.0 and 2.0, so I could use that. That used the XSLT Standard Library too. So, I wanted something that would be blazingly fast and transparent to users of WCF: I wanted a compiled XSLT and a custom XmlReader layered on top!

So, after a couple very minor fixes, I got Aaron's XSLT to compile with the following command:

xsltc /out:Atom03ToRss20.dll /class:NetFx.ServiceModel.Syndication.Atom03ToRss20XslTransform atom03-to-rss20.xsl

That gave me an assembly I could reference, containing the specified type, which can be used as follows:

var atom03ToRss20 = new XslCompiledTransform();
atom03ToRss20.Load(typeof(Atom03ToRss20XslTransform));

// transform the document with the compiled XSLT into an output writer
atom03ToRss20.Transform(someXPathDocument, someXmlWriter);

That's the fastest way of doing XSLT transformations in .NET, mind you.

Now for the custom XmlReader, I used a base class we created for the Mvp.Xml project, the XmlWrappingReader, which makes creating the derived LegacyFeedXmlReader a breeze:

#if NetFx    
    public class LegacyFeedXmlReader : XmlWrappingReader
#else
    internal class LegacyFeedXmlReader : XmlWrappingReader
#endif
    {
        static XslCompiledTransform atom03ToRss20;
        MemoryStream mem;

        static LegacyFeedXmlReader()
        {
            atom03ToRss20 = new XslCompiledTransform();
            atom03ToRss20.Load(typeof(Atom03ToRss20XslTransform));
        }

        public LegacyFeedXmlReader(XmlReader baseReader)
            : base(baseReader)
        {
            if (baseReader.ReadState == ReadState.Initial)
                baseReader.MoveToContent();
            
            UpgradeReader();
        }

        private void UpgradeReader()
        {
            if (BaseReader.NamespaceURI == "http://purl.org/atom/ns#")
            {
                var doc = new XPathDocument(BaseReader);
                mem = new MemoryStream();
                using (var writer = XmlWriter.Create(mem))
                {
                    atom03ToRss20.Transform(doc, writer);
                }

                mem.Position = 0;
                BaseReader = XmlReader.Create(mem, BaseReader.Settings);
            }
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (mem != null)
            {
                mem.Dispose();
            }
        }
    }

Note how the reader will only run the transformation and expose the transformed content if the root element namespace matches that of Atom 0.3 :). So, for Atom 1.0 and RSS 2.0 feeds it will do nothing and delegate all calls to the underlying reader.

Usage is straightforward: you just instantiate your XmlReader as usual, but wrap the new legacy one on top before passing it to the SyndicationFeed class:

WebRequest request = CreateWebRequest(feedUri, credentials, modifiedSince);
XmlReaderSettings settings = new XmlReaderSettings { CloseInput = true };
using (XmlReader reader = XmlReader.Create(request.GetResponse().GetResponseStream(), settings))
{
    using (var legacyReader = new LegacyFeedXmlReader(reader))
    {
        SyndicationFeed feed = SyndicationFeed.Load(legacyReader);
        return feed.Items;
    }
}

This code is part of the NetFx project, a collection of utilities to augment various pieces of .NET. You can grab just the Syndication folder if you want. The goal of the project is to provide reusable pieces that you can just use in isolation (i.e. linking or copy/pasting a file or a folder). For your convenience, you can also just download the ZIP.

Enjoy!

posted Friday, February 06, 2009 5:42 AM by kzu

Buenos Aires MSDN and TechNet Briefing 2009

From my friend Pablo:

I just got an email from Miguel Angel Saenz confirming the date of the next biggest Microsoft event in Buenos Aires Argentina, "MSDN briefing", which will take place on March 25th.

They are now accepting proposals or suggestions for possible sessions in the event, or to give an specific name to event itself :).

If you are interested in participating, check out this website.

Hope to see some of you there!

posted Thursday, February 05, 2009 7:28 PM by kzu

Crazy Linq: render a method invocation and its arguments as a string

Context: invocation represents a method invocation, has a method and the array of arguments passed-in. We want to render the call such as: MyClass.MyMethod(1, true, null, "foo"). Note how null values should render as the string "null", and string values should be enclosed in quotes.

Here you go:

return
	invocation.Method.DeclaringType.Name + "." +
	invocation.Method.Name + "(" +
	String.Join(", ",
		(from x in invocation.Arguments
		 select x == null ?
			"null" :
			x is string ?
				"\"" + (string)x + "\"" :
				x.ToString())
		.ToArray()
	) + ")";

posted Thursday, February 05, 2009 9:05 PM by kzu

Updated WLW Cross-Post plugin

Now that there's an official installer of Live Writer that works on x64, I updated my plugin that allows you to cross-post a blog entry to a second WLW account, optionally summarizing the entry and always linking back to the source blog. I summarized the reasons why you might need to do this as well as the feature set in How to cross post entries across blogs from Windows Live Writer.

The plugin options are still the same:

image

And after you posted successfully your original entry, cross-posting to the selected account is one click away:

 image

The cross-posted entry, if summarized, will be intelligently stripped at the specified *content* characters (i.e. 300 chars counting actual text content, not markup/attributes) while preserving your markup surroundings, therefore properly cutting not only text paragraphs:

image

but also right in the middle of bullet lists:

image

and even inside code blocks which might even include formatting markup:

image

Go get the WLW Cross-Post Plugin, another resounding success from your friends at ClariusLabs :)

posted Thursday, February 05, 2009 1:45 AM by kzu