Organised by the UK Windows Azure User Group, this free all day conference provided a great opportunity to catch up on the latest developments, particularly given the Microsoft announcement a couple of weeks back.

Core to this announcement was Microsoft’s move into Infrastructure-As-A-Service (IaaS), and the key note by Scott Guthrie positioned IaaS (described as Virtual Machines) alongside Microsoft’s current Cloud offerings which to date has focused on Platform-As-A-Service (PaaS – now labelled Cloud Services by Microsoft) and Software-As-A-Service (SaaS – Office 365 for example).

MS Cloud Day

Despite the lack of internet connectivity for a large part of the presentation (what is it with Cloud demos and loss of connectivity?!?) Scott did a great job talking through the slides, clearly describing the alignment of each of the deployment options: On-premise vs Virtual Machines vs Cloud Services vs SaaS.

In addition to Virtual Machines, the new Web Sites service was also discussed which gives Azure customers up to 10 web-sites and 1GB of storage for free (whilst in preview period, see here for further details). The demonstration showed how easy it is if you simply want to re-host an existing web-site on Azure whether it be ASP.NET, Node.js, PHP or even classic-ASP. So the new Web Site and Virtual Machine services provide a simple route to hosting applications on the Azure platform, but there is the added benefit of the Azure management aids, real time statistics and in the case of Web Sites incremental deployments and continuous integration (through TFS or GIT) too.

So where does this fit with Paas? Well Steve Plank from Microsoft provided some answers with another demonstration. With Cloud Services you get host of services to call upon including Storage, Database, Identity, Caching and Service Bus and the demo showed that if you design your application from the ground-up utilising these services, you benefit from an end-to-end application architecture that can be deployed and running in minutes at the click of a button. It is this architecture that really gives you the elasticity and flexibility in the places you need it.

A good day and exciting times with the options and landscape constantly changing. Nicely summed up by another Smartie (Andy Carter), ‘I guess there’s a load more stuff I need to learn about’, when a couple of days after passing the Azure certification MS announced the new services…(Well done btw!)

Planky getting an error!On Tuesday night last week I attended my first London Windows Azure user group meeting – it’s the second time this new group have met, but the first one I’m managed to make it to. My colleague Simon Hart blogged about the inaugural event here.

There were about 35 attendees or so and it felt like a good crowd, asking intelligent questions and I had some interesting chats during the breaks with some other user group members and I also caught up with Yossi Dahan (a Microsoft technical architect I’ve met before) – it really feels like this young user group has some momentum – so hats off to the organisers for getting this off the ground! The good pizza, chips, and beer also always helps :) – this must be one of the best catered user group meetings I’ve ever been to – there was even someone opening my beer bottle for me…

Planky (aka Steve Plank from Microsoft) presented on two topics relating to different strategies for identity federation and application access control – Azure’s Access Control Service (ACS) and Azure Connect.

Most of the the presentation time was allocated to ACS – which is pretty intricate to use. Well – it’s probably fairer to say that there are plenty of moving parts and technologies to get to grips with if you want to federate identities from Active Directory on-premise using ADFS2, via ACS in Azure to a set of applications hosted in Azure (which will typically using Windows Identity Foundation – WIF – to process the security token issued by ACS). None of it is particularly tricky in itself, but the great man himself hit some issues along the way (which always makes for a better presentation anyway :) ) and I was left thinking that it was a bit of nightmare to troubleshoot exactly why user access to the end application (the “relying party”) was being denied (see the image above) – it’s just the joys of debugging a distributed architecture I guess.

Azure Connect is essentially a VPN and IPSEC tunnel offering that I guess is very roughly equivalent to the Virtual Private Cloud (VPC) offering from AWS, but with some significant differences – but it’s trying to address the same key requirement – seamless but secure network connectivity between on-premise and cloud-based networks. It’s still in beta (at least until Summer 2012) and has some inherent limitations such as the fact that it requires a separate installation of agent software on every on-premise server that will talk to/from Azure, but it looks like an interesting technology. My main concern was just whether our customer’s security team’s could live with this model though – as in addition to the installation requirement, it essentially avoids any corporate firewall by creating an out bound SSL (port 443) connection to the Relay Service on Azure, effectively creating a client-to-site VPN from each individual on-premise server to the Relay Service.

So overall – a very useful and interesting evening, I’m glad I attended and I recommend my Smart421 colleagues to make the effort to attend future events (which are planned to be monthly) – the next event (register here) is on the 7th Feb and relates to “Parallel Processing with Azure and HPC Server“, so I’m personally very interested to hear how this compares to AWS’s offerings in this area.

DavidTuppenSQLServerArticleOne of the Smarties in the our Microsoft practice, David Tuppen, has published an article on the SQLServerPro web site (what was called SQL Mag) about how to work around the limitations of the Business Intelligence Wizard in SQL Server Analysis Services (SSAS).

It’s very clear and detailed. Have a read!

Last week 4 Smarties including myself were lucky enough to attend Microsoft Tech.Days Windows Azure Bootcamp in London. Usually for days like this Microsoft estimate (and allow for) around a 50% attendance rate, however 90% of the registered attendees for this event showed up which showed how much interest in cloud computing is taking off and required some quick provisioning of additional space from the organisers (akin to provisioning additional storage space in the cloud).

The camp was presented by Steve Plank (http://plankytronixx.com/default.aspx), with the content being a mixture of lecture / demo and try for yourself. This provided the audience with an overview of the current Azure platform and enough knowledge to walk away and start creating cloud based apps capable of exercising a number of basic Azure features.

There was also a quick 10 minute presentation during break time from the recently formed London Windows Azure User Group (http://www.lwaug.net) who’s first meeting is on the 6th December and sounds like it will be well worth regularly attending to both hear from their guest speakers and touch base with a number of other Azure developers to talk through experiences using the platform. Plus mention was given to the upcoming ‘6 Weeks of Azure’ programme (http://www.sixweeksofazure.co.uk/) beginning at the end of Jan 2012 where 6 weeks of free help will be given to UK companies wanting to have a look at the platform.

Based on the content presented on the day it is clear that a lot of thought has been put into the features within Azure and making sure that these will be easy to integrate into both existing and new developments where appropriate (and not just using Microsoft development tools or languages).

The main area that I am looking forward to diving deeper into is the Azure App Fabric, particularly the Azure Service Bus (http://msdn.microsoft.com/en-us/library/windowsazure/ee732537.aspx) as this looks like it will be incredibly useful in stitching together dispersed applications and also hooking existing on-premise solutions into new cloud based offerings and also the Caching Service (http://msdn.microsoft.com/en-us/library/windowsazure/gg278356.aspx) which will be really great  for both distributed and high bandwidth apps.

On the day the only part of the App Fabric that was demoed was the Access Control Service which under the covers used SAML.  Before the event I had dismissed as being just another way to validate users. However after seeing how easy this is to implement and use plus the ability to integrate with Active Directory via the use of ADFS2 (http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=10909)  and a number of other authentication providers such as Google, Yahoo or LiveID I can see it becoming part of most Azure developments.

One question we had been kicking around prior to the event was ‘how production ready is Azure?’ as with other cloud service providers (such as AWS) we have tended to see our customers start by using these services for test / development or disaster recovery environments rather than production.

Although not fully answered it was clear that Microsoft are looking for customers to place production as well as development systems in Azure and have also been doing their homework on the problems previously experienced by other providers architecting the underlying infrastructure accordingly to cope with this.

Microsoft are offering a 99.95% SLA for external connectivity for compute hosted services that meet their criteria (at least 2 host instances configured for a service) which is the same as AWS for EC2 instances however the  Azure terms are measured monthly rather than yearly for AWS.

Azure also contains additional features such as the recently released SQL Azure Data Sync which allows data to be synchronised between SQL Azure instances in different locations and it was hinted that resilience features like this along with a huge number of other enhancements are currently under development across the platform.

Based on what was shown and discussed during the event it looks like there are exciting times ahead in the Windows Azure space and I am looking forward to architecting, developing and supporting applications that make use of its features.

The reason for this post is because I am still seeing Helper, Utility and Singleton implemented code in large enterprise scale solutions today. It is almost as bad as coding in Hungarian notation. Now this is to say that practices like Hungarian notation had a place and a purpose, notably when using dynamically linked languages such as C++ for example where you did not have type safety. Things have moved on since those days so PascalCase and camelCase are now the preferred convention, certainly within the .NET space and camel case preferred in the Java space.

Microsoft has a good post on Design Guidelines for Class Library Developers.

So really Helpers or Utilities come from (in my view) procedural languages and by definition they tend to be static types that often equate to “general stuff” that doesn’t fit anywhere else which is very much a procedural mind-set as when you build software in OO languages such as C# or Java, everything has a single responsibility.

This discussion has been flogged for years especially when .NET was becoming popular. But it seems all these discussions haven’t really changed peoples mind sets. Many developers still believe that a helper is a good thing. I am not sure how these patterns are perceived in the Java space but in .NET they are generally considered anti OO and there are good reasons for this which we will go into in this post. Nick Malik from Microsoft wrote this post 6 years ago about this very topic. I have to say I agree 100% to Nick’s comments. It’s actually quite scary to the responses Nick got to that post.

I have copied a particular comment here for reference from a chap named Nate on Nick’s blog, not to pick on Nate but purely for a discussion and example perspective:

This is all good and all, but if helper classes are undesirable, where do you put miscellaneous code that you would normally put in a helper class? Where does that method go that say, helps encode a URL? Or that function that converts an array to a comma delimited list? Or in C#, that wrapper for a certain Win32 API? In all practicality, I find that I often have these piddely tasks that don’t really lend themselves to encapsulation within an object and are pretty much on their own, but are called from myriad places. If I was coding in C++, I would place it outside of a class, but languages like C# and VB.NET don’t allow me to do that. Does it violate OO principles? Of course it does. But OO principles are not meant to be a straightjacket. All that said, I do agree that if they show up in a UML diagram, your helper class is probably doing more than isolating a “piddely task” and that something is probably wrong.

Helpers

For starters I’d like to say what “miscellaneous” stuff. This is one of the biggest issues with things like Helpers actually more with Utilities, they start out being quite small, but before you know they become a dumping ground for all things to man and beast. And to make things worst they tend to be of type static so very hard to test.

In Nates response above, I’d respond to possibly putting URL encoded functions as an extension method to the String class. But then you might say two things:

  1. Extension methods were not available back in 2005 when that blog post was written
  2. Extension methods are really helper classes anyway

The answer to the above is yes and yes! With point 2 the usage is rather different. Extension methods are helper classes in that you can only write static methods. But there is one major difference; you do not actually call the helper class directly. Instead extension methods are an extensibility point in the .NET type system that extends .NET. They often should only be very short functions that normally should not have dependencies. So the developer using an extension method should be very clear what the function is doing and should be able to use those functions in his unit tests without issues.

By the way, my extension method post linked above needs updating. Extension method classes should have the name <class>Extensions. I.e. for IEnumerable extensions, it should be IEnumerableExtensions. So here it’s very clear what are extension method classes and what are not.

So where should those URL encoded functions go back in .NET 2.0 before extension methods existed? The answer, I would incorporate a new class called URL with no static methods and make it part of my framework for my application. This then gives me the power to inject dependencies in the future should I need to and makes testing very easy.

So if class URL required dependencies I.e in the future we might want to send a sample message to a given URL which has a dependency on a custom communication adapter for example, it wouldn’t be a suitable candidate for extension methods anyway.

So take above scenario, if we had a helper class that looks like the following:

public static class Helper 
{ 
    public string static EncodeUrl(Url url) 
    { 
       // call encryption 
    } 
}

That looks ok, so for now forget about testability. But for one thing the class name is not particularly useful. So we could change it, or leave it as is. Often it will get left as is. So then another developer will think, “oh there’s a helper class for library functions”. “I’ll add my FoobarAppSpecificFeature method to it”. And so it goes on and then you end up with a god class.

God Classes

God classes are classes that do or know too much. They breach the Single Responsibility Principle. They are often a result of a procedural developer trying to implement an object oriented system with a global variable mind-set. They often do not fit in well with TDD (Test Driven Development) purely because the classes are hard to test in that they rely on external dependencies which are very hard to mock out. Also, they do not model the system in any way so maintainability comes into question as if you have god classes, you will also have god unit test classes and projects too.

Are Singletons Really bad?

I personally don’t think they are when used in conjunction with an IoC container. The reason here is that a singleton when used in conjunction with an IoC container looks no different from a non-static instance type. This is one of the major benefits of using IoC in that the life cycle is controlled by the container and not the consumer consuming the class. And this configuration should be in the composition root.

There are many valid reasons you would want such a class and the fact you can piggy back on an IoC gives great power and flexibility.

Singletons when used with IoC do not prevent you from testing unlike static types which are mostly bad for reasons already mentioned and should be avoided when possible.

Singletons <> Static types

The moment you define a static type, you immediately write off any use of IoC and testability. That really is the key message here.

The other thing to remember is that, if you implement a static type via an Extension Method or other means, remember that the developer needs to understand what is actually happening and that he wouldn’t be interested in mocking out those calls in a unit test. If the consuming developer would be interested in mocking out those calls, then reconsider the use of an extension method/static type.

So I think Singletons are ok so long as they are not static types and are made singletons are part of the container configuration they are part of.

Utilities

Utility and helper classes in terms of naming are often interchangeable. A Utility class is often equal to a helper god class.

I’m interested in your views on this post, so please comment.

Microsoft has recently started to embrace all things from the ALT.NET community. If you’re not an ALT.NET’er, then what I mean by this is most good things in terms of current thinking, design patterns, technical architecture etc spawns from ALT.NET and the wider community. Microsoft tends to jump on things when they become popular, then they tend to roll these things into their development tools and products. Some of these make it into the actual products like Visual Studio, .NET etc. Some get given to the patterns & practices team to implement and some go to other development teams within Microsoft.

Some examples of this are as follows:

  1. IoC/DI – Unity comes from Windsor, StructureMap, Ninject
  2. MVC – ASP.NET 3 (latest cut) comes from Castle MonoRail (and Smalltalk!)
  3. ORM – Entity Framework comes from NHibernate – among others
  4. etc

The patterns & practices team whose job it is to lay down guidance and best practices using Microsoft technology and to also provide application blocks and frameworks that work with Microsoft’s toolset. The p&p team are best known for the Enterprise Library. I find most of what comes out of the p&p team is somewhat over complex and configuration heavy, although some things like Prism for WPF is very good.

Note what I said above “configuration heavy”. The industry has been moving away from angle brackets (XML) for sometime. XML is often massively over used and it has quite a heavy payload often not that suitable for embedded mobile devices, not to mention quite nasty to work with not only to parse but to read.

Many platforms/tools frameworks has in recent years been adopting this thing called “Convention over Configuration” CoC for short. It is essentially something that conforms to a convention i.e. a certain way or assumed way of working unless told otherwise – namely using configuration – whether this is XML or something else is not important.

Microsoft started (at least the only thing I can think of) to introduce CoC with ASP.NET MVC. Since then other products are showing signs of CoC such as Prism for WPF and Silverlight, WCF 4.0. Which kind of brings me to the reason for this post.

WCF in the past has required a lot of configuration even just to get a service up and running with a basic binding. The fact that I label my service contract with an attribute (ServiceContract) should be enough! At last Microsoft has recognized that you shouldn’t have to do this.

Take the following configuration which is what you had to do prior to WCF 4:

My configuration above is slightly more simple than it would normally be due to the fact I am using configSource. i.e. separating out WCF sections for easier maintainability.

But what if I wanted to knock up a really simple service that looks like the following:

[ServiceContract]
public interface ICustomerService
{
   [OperationContract]
   RetrieveCustomersResponse RetrieveCustomers(RetrieveCustomersRequest r);
}

The fact I have decorated my service with the needed attributes, should I have to do any more? why do I need to wire up a basic HTTP binding class to my service in config code or XML? Now in WCF 4 you don’t!

Now consider the amended config below:

Notice in the system.serviceModel sections we no longer have any configuration. Will this service still work? lets try it, by navigating to the endpoint using a web browser:

How is this possible??!? Well now WCF has a default configuration which comprises of default bindings and behaviours. WCF now exposes 4 protocols by default: basic HTTP, net TCP, named pipes and MSMQ. This is known as protocol bridging in WCF 4.0. You can easily change any of these things i.e. behaviours protocols, bindings etc globally or per service in the normal way with one difference which I’ll show in a second. But first, notice the service above no longer exposes a WSDL document because we no longer have any behaviours enabled and the default ones locks down the metadata exchange MEX endpoint.

We can soon fix that globally by using the following small bit of config, I have also lost the log4net config here to add more clarity:

The behaviours config file looks like so:

Notice how we have enabled debugging exception details. You would normally only do this in debug mode (development and not production). Notice the difference between this and a normal WCF behaviour?? This one has no name, which means it will be applied to all services. So this feature is really powerful, you can apply blanket configuration across your enterprise without having to specify the config per every service!

Now if we ask for the WSDL, we get the following back from the WCF 4 service:

So here the convention is the pre-configured protocols and bindings, we still have the ability to change this convention if we want to using normal config.

In the next part to this post, I’ll show examples on how to change protocol bridging i.e changing default basicHttpBinding to wsHttpBinding.

Anyone doing modern enterprise software engineering today will be practicing or partially practicing Continuous Integration, otherwise known as CI.

If you have never heard of CI before, Martin Fowler has a really good post on the subject here: http://martinfowler.com/articles/continuousIntegration.html

Just quickly, CI really comes down to a few main key points – at a minimum (some of which lifted from Fowlers post above):

  1. Automate the build
  2. Make your build self testing
  3. Everyone commits/check’s in to trunk every day
  4. Every commit/check in should build trunk on an integration machine
  5. Support for buddy builds
  6. Keep the build fast
  7. Must be able to run a local command-line single build that does everything that represents the build machines process

As far as I am concerned those 7 items are mandatory. There are of course many more that make up a really good CI strategy which I’ll go into in a future post but for now, lets concentrate on those 7 items.

I’m not going to go into detail into each item, but will pick out the ones I think are the most important.

2. Make your build self testing

The thing is everyone seems to know about CI now, which is good. But many are still getting it wrong.

Number 2 on the list need explaining in order to get it right. I’ve seen so many large companies get this wrong, let me explain.

There are normally two types of automated testing:

  1. Unit testing (by no means should the component being tested go down a rabbit hole and test a whole bunch of other components, these dependencies should be isolated out)
  2. Integration testing or acceptance testing

So if unit testing is done right i.e. they are *not* integration testing and the tests test the smallest testable unit, then unit testing honors point 6 (keep the build fast) on the above list. Who cares whether the build is fast? well you normally only have a finite number of build servers and on those servers you have a finite number of CPU’s and RAM which means a limited number of agents. When all your agents are busy serving multiple simultaneous check-in’s, builds get queued, the more queued builds the longer it takes to see feedback from a check-in/commit.

If you don’t have a buddy build system (point 5 on the list – I’ll explain what a buddy build is in a minute), imagine what can happen when you get lots of queued builds, if 1 fails, then it is very likely all the following builds will fail. This means someone has to sort out the mess. This mess then break downs the benefits of CI.

So going back to my original point, keep the build fast is very important that often gets missed or not really thought about too much. I often see unit tests doing too much meaning that they take too long to execute. I often see unit tests being a mix between integration tests (like BDD/acceptance tests) and unit tests more like a hybrid. Unit tests should only test a single class – where possible, this keeps the build very fast.

But then what about acceptance/integration/BDD tests? normally such tests will execute end-to-end i.e. from a UI all the way to the database or downstream system and back. If you practice BDD you’ll have these tests for all your use cases main and alternate flows. So often you will have hundreds of these tests for a typical enterprise large system. So with that, these tests will take much longer to run due to the fact the tests are testing the full stack. Sometimes the downstream system will be on another network perhaps communication to it is via a IPsec VPN tunnel to the other side of the world. Or could be over the internet. Whatever it might be, incorporating these tests with the unit tests is not a good idea.

So when should you run these long running integration tests and when should you run unit tests? Integration tests should normally run nightly i.e. like 02:00am when the build servers are quiet and don’t have much activity. Unit tests should run on every check-in/commit during the day for constant feedback.

My CI tool of choice is Microsoft Team Build (comes with Team Foundation Server). In Team Build 2010 it allows you to easily setup controllers so I often use one controller for integration and one for CI. These controllers can delegate to n number of build servers. So with this kind of configuration, I normally have quite a meaty set of CI build servers (for running unit tests on each check-in) then have a less powered build server for deploying code and running integration tests.

The power of this is such that the whole daily build activities is fast, thus satisfying the fast build and constant feedback requirement. Developers can also start an integration build anytime they wish during the day which will not affect the day-to-day running of a software development team.

5. Support for Buddy Builds

What the heck is a buddy build I hear you say! I’m not sure if this is just a Microsoft term or not that has come from Redmond. But a buddy build is a way of ensuring your changes will integrate with the version on the server before your changes are actually committed into the branch. So how do you do that? in the old days before software products did this, you would send your changes to a buddy who would merge your changes with his, then he would attempt to compile/run tests etc before you committed your changes.

In TFS 2010, Microsoft has introduced the concept of a gated check-in. So when you check-in, you actually check-in as a shelveset (not to the main branch) then Team Build will execute the build scripts against your shelveset first, if it succeeds, then your changes will be committed to source control – hence it is impossible to break the build!

I’m not sure about other build server technologies like, Jenkins, TeamCity, Hudson etc but if you want to read more about TFSÂ 2010 gated check-in, see here: http://blogs.msdn.com/b/patcarna/archive/2009/06/29/an-introduction-to-gated-check-in.aspx

7. Must be able to run a local command-line single build that does everything that represents the build machines process

Now this is very important. I see all to often that there are no command-line builds at all! and if there are some, you sometimes have to run more than one to get a complete picture of whether your check in will succeed on the server or not.

The benefits of having a local command build are huge, here are a few reasons:

  1. It allows you to get a local copy of the solution running, i.e. setting up a web server, adding users setting security permissions, deploying web sites into a web server
  2. Have one single command-line build script batch file or power shell script that does everything your check-in will do, i.e. compile, run code analysis, run code style rules, run tests etc
  3. Enables faster development, geeks love command-line tooling!

If you have read this far, congratulations! until next time..

Happy building…

I have been using the Service Locator pattern for years and I think it has a place in some circumstances – I’ll explain what I mean by that in a minute but first for some scene setting…

If you’re not familiar with the Service Locator then the following shows a simple class diagram that depicts its use:

The following descrription of what the Service Locator pattern is, is detailed here from Wikipedia:

The service locator pattern is a design pattern used in software development to

encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the “service

locator” which on request returns the information necessary to perform a certain task

Often the Service Locator is used in conjunction with other patterns such as IoC and DI. (self promotion here, I’ve put together a IoC/DI container with support for event aggregation for Silverlight on Windows Phone : http://wp7.codeplex.com)

If you are a Microsoft shop, then the Common Service Locator is a very popular implementation of this pattern. You can download the code here (by the patterns & practices team at Microsoft): http://commonservicelocator.codeplex.com/

In fact the above website contains some providers for popular Inversion of Control containers such as StructureMap, Unity, Castle Windsor and so on.

Anyway back to the point of this post, when should you implement a Service Locator and is it an anti-pattern? According to this post and many others it is an anti-pattern. My view to that question is it is an anti-pattern if used in the wrong way. The example given in the above post is an anti-pattern because the benefits of IoC are not realised due to lack of understanding in IoC – I see this a lot in enterprise. In fact you can use a vanilla IoC container as a service locator (kind of) it’s more of a factory than service locator but bear with me.

Here is an example of a good use of IoC and DI – to which many of you reading this will already be doing today and will continue to do in the future:

public class Foobar : IFoobar
{
    private readonly IFoobarAdapter _adapter;
    private readonly IFoobarAdapter2 _adapter2;

    public Foobar(IFoobarAdapter adapter, IFoobarAdapter2 adapter2)
    {
        _adapter = adapter;
        _adapter2 = adapter2;
    }

    public void DoStuffWithAdapters()
    {
         //...
    }
}

Now the above code is nothing new, we are using IoC and DI to abstract dependencies which thus enables us to write good software code that is easilly testable and maintainable. There is no requirement for Service Locator here. The code also tells any human or software program to generate some metrics as to how coupled or otherwise loosely coupled our software might or might not be. So the above, NDepend (my tool of choice for metrics) can easilly figure out the dependencies between class Foobar and the adpaters (interfaces).

Now what if we introduced the Service Locator pattern to the mix here. Consider the following changes to the above Foobar class that now uses Microsofts IServiceLocator:

public class Foobar : IFoobar
{
    private readonly IFoobarAdapter _adapter;
    private readonly IFoobarAdapter2 _adapter2;
    private readonly IServiceLocator _serviceLocator;

    public Foobar(IServiceLocator serviceLocator)
    {
        _serviceLocator = serviceLocator;
        _adapter = serviceLocator.GetInstance<IFoobarAdapter>();
        _adapter2 = serviceLocator.GetInstance<IFoobarAdapter2>();
    }

    public void DoStuffWithAdapters()
    {
         //...
    }
}

So what’s happening here, and why is the new code not so good? but more importantly, why would you use Service Locator as it seems to be complicating things somewhat…

Firstly, the code is not so good for the following reasons:

  1. In order to test this class, I’m going to have to new up a IServiceLocator type and ensure it responds to GetInstance for types IFoobarAdapter and IFoobarAdapter2. I know I can use mocking tools like Rhino Mocks here, but I’m just giving myself more work and I’m not getting anything from that change.
  2. It gives any human and tool such as NDepend an artificial view of the actual coupling between the layers.

By the way it’s worth pointing out here that I can’t remember whether Microsofts implementation of IServiceLocator includes generics. I think I might have added the generic GetInstance to the interface in order to make my implementation cleaner and easier to code.

The above could be worst still..consider the following additional “hack”:

public class Foobar : IFoobar
{
    private readonly IFoobarAdapter _adapter;
    private readonly IFoobarAdapter2 _adapter2;
    private readonly IServiceLocator _serviceLocator;

    public Foobar(IServiceLocator serviceLocator)
    {
        _serviceLocator = serviceLocator;
    }

    public void DoStuffWithAdapters()
    {
        _adapter = _serviceLocator.GetInstance<IFoobarAdapter>();
    }

    public void DdoStuffWithAdapters2()
    {
        _adapter2 = serviceLocator.GetInstance<IFoobarAdapter2>();
    }

So you *might* be thinking, well what’s wrong with that, shame on you if you are! Foobar here is quite light in that there arn’t many lines of code, but when it gets larger it will be more difficult to figure out Foobar’s dependencies from both a tools and a humans perspective.

So this then is leading to the conclusion that Service Locator is an anti-pattern right? wrong! take the following slightly different scenario.

I am using the command pattern and have a command that looks like so:

public class EmailCustomerConfirmationCommand :
           ICommand<EmailCustomerConfirmationContext>
{
     private IEmailAdapter _emailAdapter;    

     public EmailCustomerConfirmationCommand(IEmailAdapter emailAdapter)
     {
          //inject dependencies here.
          _emailAdapter = emailAdapter;
     }       

     public void Execute
       (EmailCustomerConfirmationContext context)
     {
         _emailAdapter.Send(context.Customer);
     }
}

So with the above I have a nice implementation of the command pattern (I’ll talk about the command pattern in a later post) that takes a context as a generic. We register this command with the context so it can be picked off the container easily. This command gets registered like so:

container.AddComponent<ICommand<EmailCustomerConfirmationContext>,
 EmailCustomerConfirmationCommand>();

This of course will look different depending on your container of choice. Here I am using the Compact Container.

So my requirement is to now wireup the calling of the above command in my Foobar class. This is easy, I could just inject ICommand via the constructor like I do with all the other types, right? well I could but this will not scale very well as I might have potentially 10′s or 100′s of commands. Imagine testing that. Foobar could be a presenter layer in a MVP application or Controller layer in an MVC application or some sort of domain event. Instead, I’d like to delegate the execution of commands to another responsibility outside of class Foobar honouring the SRP (single reponsibility principle). So with that, what I want to do is something like this:

public class Foobar : IFoobar
{
     private readonly IFoobarAdapter _adapter;
     private readonly IFoobarAdapter2 _adapter2;
     private readonly Icontroller _controller; 

     public Foobar(IFoobarAdapter adapter,
          IFoobarAdapter2 adapter2,
          IController controller)
     {
          _adapter = adapter;
          _adapter2 = adapter2;
          _controller = controller;
     } 

     public void DoStuffWithAdapters()
     {
     } 

     public void DoStuffWithAdapters2()
     {
     } 

     public void SendNotificationEmailToCustomer(Customer customer)
     {
        _controller.Execute
         (new EmailcustomerConfirmationContext(customer));
     }
}

I have now added a dependency named IController that handles the actual execution of commands. This class could look like the following:

public class Controller : IController
{
    private readonly IServiceLocator _serviceLocator;
    public Controller(IServiceLocator serviceLocator)
    {
         _serviceLocator = serviceLocator;
    } 

    public void Execute<TContext>(TContext context)
    {
         var command =
           _serviceLocator.GetInstance<ICommand<TContext>>();
         if (!command.IsNull())
         {
             command.Execute(context);
         }
         var disposable = command as IDisposable; 

         if (disposable != null)
             disposable.Dispose();
     }
}

So here the Controller class is nice and clean in that we are not injecting commands via the constructor or any other means. Instead we are asking Service Locator for a given command based on the context passed to it. The power of this is that the Controller class in this example also doesn’t know the underlying container it is working with.

So hopefully you can see the power the Service Locator gives us here. We have made our Foobar class very clean with little dependencies which makes it easy to test and separated out responsibilities for the actual execution of commands – much like Microsoft’s WPF framework does.

Microsoft is starting to embrace these patterns. The IDependencyResolver is Microsoft’s version of Service Locator in MVC 3. I will write a blog on that soon.

So to conclude, the Service Locator pattern is *not* an anti-pattern so long as you have a good reason to use it!

In the meantime, happy coding!

Sometimes you have a requirement to generate your C# class contracts from an existing WSDL document so they can be used by consumers. It might be that the customer simply wants to keep the existing service contract and in this case only the implementation needs to be developed.

The way to do this in .NET is to use the SVCUTIL.exe command-line tool that you get when you install Visual Studio. Most people will know about this tool for generating C# client proxy classes to handle the service invocations and marshalling of simple and complex data contracts from the client side. It can also handle generation of the C# service contracts – although not pretty and will need to be cleaned up afterwards.

Just to note, when I say C# above, the tool also supports VB.NET, you just need to pass in the /l:VB switch. It defaults to C#.

So to generate your concreate service contract from an existing WSDL you can use the following syntax:

svcutil /dconly myservice.wsdl

If you’re lucky you’ll get a single myservice.cs source code file that contains everything i.e. all data contracts and the service contracts that you need in order to implement your service. You’ll need to clean this up though as the tool makes a mess of creating these contracts. You’ll also get a .XML file that can be added to your web.config or app.config file as it specifies the address, bindings and contracts for your service. It takes the address from the WSDL document and applies it to the config file.

If you’re not so lucky, you might get an error similar to the following:

D:\Workspaces\Simon\Project_Foo\Trunk\Foo\Source\Artefacts\WSDL>svcutil myservice.wsdl
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 4.0.30319.1]
Copyright (c) Microsoft Corporation. All rights reserved.

Error: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Schema with target namespace ‘http://schemas.foo/Services/Foo/2009&#8242; could not be found.
XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:com:foo:services:foo:function:2011']/wsdl:portType[@name='PortType']

Error: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='urn:com:foo:services:function:feature:2011']/wsdl:portType[@name='PortType']
XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:com:foo:services:function:feature:2011']/wsdl:binding[@name='EndpointBinding']

Error: Cannot import wsdl:port
Detail: There was an error importing a wsdl:binding that the wsdl:port is dependent on.
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='urn:com:foo:services:function:feature:2011']/wsdl:binding[@name='EndpointBinding']
XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:com:foo:services:fucntion:feature:2011']/wsdl:service@name=’Service’]/wsdl:port@name=’EndpointPort’]

Generating files…
Warning: No code was generated.
If you were trying to generate a client, this could be because the metadata docu
ments did not contain any valid contracts or services
or because all contracts/services were discovered to exist in /reference assembl
ies. Verify that you passed all the metadata documents to the tool.

Warning: If you would like to generate data contracts from schemas make sure to
use the /dataContractOnly option.

Looking through the error, the first thing that comes to mind is it looks like the separate namespace being imported could not be found as per the following error message:

Schema with target namespace ‘http://schemas.foo/Services/Foo/2009&#8242; could not be found

This might be the case if your WSDL document looks something like the following:

<wsdl:types>
<xs:schema>
<xs:import namespace=”http://schemas.foo.com/Services/Foo/2009&#8243; schemaLocation=”Context.xsd”/>
</xs:schema>
</wsdl:types>

You look at the above WSDL snippet and think, well Context.xsd is present in the same folder as the WSDL document to which I’m trying to generate a code contract, so why can’t SVCUTIL find it.

It can’t find it because it’s not looking for it. You have to supply SVCUTIL with all the dependent XSD files on the command-line with the name and location of the WSDL document file like the following, i.e.

SVCUTIL myservice.wsdl context.xsd

Once you execute that command, you’ll notice you’ll get a single C# file with the same name as the WSDL document (in this case myservice.cs) containing all the code required to implement the WSDL. This includes correctly decorated service contracts (interface) and the correctly decorated data contracts for use with WCF (Windows Communication Foundation). I admit it makes a mess of this but it’s a starting point and saves you a great deal of time especially if your data contracts are large and complex as often seen in SOA environments.

Have you ever wanted to package up your Windows Mobile/Phone or Windows CE applications into CAB files as part of your automated nightly build process. This can easily be achieved using either TFS 2010 or TFS 2008.

This article assumes you are using the Upgrade Template if using TFS 2010 as this allows you to carry on using the TFSBuild.proj file that gets created in the TeamBuildTypes folder off of the Team Project structure instead of Workflow Foundation to build and deploy your code.

Wait a minute….your’re probably thinking – why don’t I just use the CAB project template in VS and build that? well this would be good if it was XML. The Windows CE CAB project template is very old and not XML so you can’t build it using MSBuild as an automated build process. This does mean you will have to create your own INF file for the CABWIZ.exe application to call. CABWIZ is the tool that actually packages up the INF and artefacts into a distributable CAB file. In Windows CE/Mobile/Phone, the CAB file is like a Microsoft Installer (.MSI) file on the desktop.

This article: http://msdn.microsoft.com/en-us/library/ms839402.aspx shows you how to create an INF and use CABWIZ to execute it on the command-line.

1.  Once you have your INF file you’ll need to take this and the CABWIZ.exe, MAKECAB.exe and the cabwiz.ddf files from your development machine and check them into source control. A good location for things like this is as follows: $/TeamProject/Trunk/Product/Library/cabwiz/

2. Next you need to create a project file that will actually do the execution of the CABWIZ application. Create a .proj file, make it a meaningful name something like company.product.Installer.proj i.e. SimonrHart.Foo.Installer.proj

The project file needs to look something like the following:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
DefaultTargets="CreateCab">

<Target Name="CreateCab">

  <Exec
  Command='"$(SolutionRoot)\Product\Library\cabwiz\cabwiz.exe"
  "$(BinariesLocation)\SimonrHart.Foo.Installer.inf"
  /err $(DropLocation)\cab_error.txt' />

</Target>

</Project>

Check this file into source control, the location is not important but sometimes can be something like the following: $/TeamProject/Trunk/Product/Source/Scripts. The benefit of this is when you branch or have multiple streams, your scripts can be different without changing the name.

Now in the TFSBuild.proj file or in a targets file it doesn’t matter which, create a custom target named something meaningful like Deployment that looks something like the following:

<Target Name="Deployment">

<Message Text="Generating CAB file" Importance="high"/>

<Copy
SourceFiles="$(SolutionRoot)\Hermit\Source\Scripts
\Installer\SimonrHart.Foo.Installer.inf"
DestinationFolder="$(BinariesRoot)\Release" />

<MSBuild
Projects="$(SolutionRoot)\Product\Source\Scripts\Installer
\Simonrhart.Foo.Installer.proj"
Targets="CreateCab"
Properties="BinariesLocation=$(BinariesRoot)\Release;
SolutionRoot=$(SolutionRoot);
DropLocation=$(DropLocation)\$(BuildNumber);"
/>

<Copy
SourceFiles="$(BinariesRoot)\Release\MyProduct.cab"
DestinationFiles="$(DropLocation)\$(BuildNumber)\Product_$(BuildNumber)
_$(VersionNumberComponent).cab" />

</Target>

The above target copies the INF to the drop location, executes the INF, generates a CAB named MyProduct.cab and copies the output to the DropLocation that’s configured as part of the Team Foundation Server build definition.

The next thing is to wire all this up in the TFSBuild.proj file to execute when the build actually runs on the build server.

The perfect place to call this target is in the AfterDropBuild event in the TFSBuild.proj file:

<Target Name="AfterDropBuild">
<Message Text="Configuration flavour is:
%(ConfigurationToBuild.FlavorToBuild)"
Importance="high"/>

<!-- Call the Deployment which creates the CAB file.-->
<CallTarget Targets="Deployment" Condition=
"'%(ConfigurationToBuild.FlavorToBuild)' == 'Release'"   />
</Target>

So this will execute after the code is built, tests executed and been dropped to the drop location.

Simply check in the TFSBuild.proj into source control, queue a build, then check the drop location for a fully packaged up application ready for the testers to install!

Follow

Get every new post delivered to your Inbox.

Join 801 other followers