Sunday, 29 June 2008

new additions

Through the accumulated magic of amazon.co.uk and my visa card the following additions to ye old bookshelve have arrived:

So finally I can bask in the glory of original copies :) and start off on a re-reading session..
Still on the wish list, and these are just the non-product specifics..

  • Code complete
  • Peopleware: Productive Projects and Teams
  • Refactoring
  • Working effectively with legacy code
  • Extreme programming explained
  • dreaming in code
  • ... 
  • Monday, 23 June 2008

    Entity framework - a vote of no confidence

    image

    With the release of Entity framework v1 coming up a good number of Alt.Net professionals have expressed their concerns in an open letter to Microsoft.  The letter, aka the vote of no confidence can be found here, and here's the list of the people who signed it.

    As you might imagine, this initiative made some ripples in the Alt.net mailing list, as the names on the list are the most famous developers out there. 

    All in all, i'm thinking this is a next step in alt.net vs microsoft.. It's not only interesting to see how the community reacts to a new and upcoming tool from MS that doesn't live up to the expectations of and features we have been made use to by various open source products. 

    What will be worth watching is the reaction from MSFT..  As was said on the mailing list, the probability that changes acutally get into the EF before it's final release is very slim, if not non-existing.  If they do however, it shows that they (finally) are getting the message...
    mort shouldn't be the target developer.. instead mort should be trained so he can become an elvis..

    As an upside, it seems that MS has called a advisory council, with some very fancy names..

    Thursday, 19 June 2008

    wcf primer 8 - location agnostic programming is here!

    Please find the landing page here.

    In the previous post in this series, I talked about the fact that I think that not sharing the interface definition when possible (ie when you have an  assembly/project reference to the dll containing the interface) is a huge mistake. So, this is the promised elaboration on that post.

    When dinosaurs roamed this planet

    If you remember the pre-WCF days we had a number of transport stacks, each with their own needs:

    • remoting
      Inherit from MarshallByRef, objects that are being sent need to be Serializable (Binary, Xml)...
      To build a client, you need to have a common set of dlls (object and contract)
    • web services
      Methods needs to have the [WebMethod] attribute, objects that are being sent are serialized via the XmlSerializer
      To build a web servcie client, you create a proxy to a web service (wsdl), which generates client code.
      There is a way to share the objects sent on both client and server, but that one is frowned upon by SOA purists.
    • ..

     

    location agnostic programming

    LAP stands for one way of programming, regardless of transport/layers and so on.
    As a prerequisite for understanding the next step you might want to read a case for dependency injection
    The essence of that post i can repeat here

    ISomething something = Container.Resolve<ISomething>();

    LAP is typically something that you can do by combining a creational pattern and interface based programming,
    as it always you to get back an object that implements the required interface.

    pre WCF LAP

    So why does LAP become feasable with the arrival of WCF? 
    Consider the following scenario:

    You are building a client to a 'service' which can be exposed via either remoting or web services.
    The choice of transport stack shouldn't have any consequences for the rest of the client code.

    Business logic:

    ISomething myService = SomeFactory.Create();
    myService.Foo();

    Remoting implementation (it's been a while)

    public class RemotingProxy : ISomething{
    private ISometing _remote;
    public RemotingProxy(){
    TcpClientChannel channel = new TcpClientChannel();
    ChannelServices.RegisterChannel(channel);
    _remote = (ISomething) Activator.GetObject(typeof(ISomething),"tcp://something", ISomething);
    }
    public void Foo(){
      _remote.Foo();
    }
    }

    Web service implementation (note here that you're just 'applying' an interface over the web service proxy, something you can also do via partial classes from .net 2.0 onward.

    public class WSProxy : ISomething{
    private Webservice.proxy _proxy = new Webservice.Proxy();
    public void Foo(){
    _proxy.Foo();
    }
    }

    in process implementation (the real business logic)
    public class BusinessLogic : ISomething{
    void Foo(){
    // your logic here
    }
    }

    So in the end, what does this give you?
    One implementation per transport protocol + 1 for business logic

    WCF LAP

    So why is WCF better than sliced bread?  Basically because it takes away the 'one implementation per transport protocol' annoyance.  Or beter said, it should take it away...

    As said before, when creating a new service client using vs2008 the implemented interfaces is renamed to the client's namespace, breaking the desired IOC/DI capabilities.  So, we still roll our own service client's but at least you're only doing it once :)

    Things to look at on 19.06.2008

    Advice

    Aiming for the second floor never got anything anywhere. Aim for the stars, you might get somewhere. (ayende on the alt.net mailing list)

    Now, if we only got the right people to take this to heart ^^

    Sunday, 15 June 2008

    a case for AOP

    In my previous post I took you on a trip covering the evolution of the Dependency Injection pattern.
    I asked for feedback on that post both on the ALT.net mailing list, a few internal message groups and on the microsoft architecture forums.

    This post comes to you directly as a result of that feedback :)
    Credits are to be given where they are due, the guy commenting me on the (somewhat obvious) exclusion of this in the previous post is Gael Fraiteur, the creator of the excellent PostSharp.

    Aspect oriented programming
    According to wikipedia, AOP is:
    In software engineering, the programming paradigms of aspect-oriented programming (AOP), and aspect-oriented software development (AOSD) attempt to aid programmers in the separation of concerns, specifically cross-cutting concerns, as an advance in modularization. AOP does so using primarily language changes, while AOSD uses a combination of language, environment, and method. 

    [as a sidenote here, you should really check out the .net links at the bottom of the page, turns out there are quite a few AOP frameworks I have never even heard of!]

    so, what is (slightly more comprehensible, at least if your the author of this blog) my definition of AOP?
    AOP is nothing more than a way to inject behaviour into existing code. 
    Mostly this should be used for cross cutting concerns like logging, exception handling, security, performance monitoring and so on

    Consider the following pieces of  code:

    public void MyMethod(){
    this.Log.Log("started myMethod");
    // do some stuff
    this.Log.Log("finished myMethod");
    }

    I include exception handling here for the sake of completeness, personally I don't like to use AOP for exceptions

    public void DoSomeTrickyStuff(){
    Try{
    //some tricky stuff that will fail;
    } catch (Exception ex){
    Log.Log(ex);
    }}

    and not to forget, my alltime favorite

    public void SomeMethod(){
    using(Trace("currentmethod", someparameters)){
    //your method implementation goes here
    }
    }

    Basically, Aspect Oriented Programming allows you to focus on the real method implementation and get's the pesky repeated code out of your way.
    Depending on the used framework, AOP is implemented slightly different, giving access to different AOP features.
    I'm going to start off with the simplest thing I can think off, taking baby steps once more:

    Method Interception

    Method interception is a bit of a strange concept at first, but compare it if you will to having a wire tap on a telephone line.
    When you call your buddy the feds are listening in to that call, logging the time of the call, who called who and what was said..

    How would you implement such a thing in .net?
    You could do something like

    event Action<IncomingCall> Called;
    private voidi RaiseOnCalled(IncomingCall  call){..}
    public void AcceptCall(IncomingCall call){
    RaiseOnCalled(call);
    ...
    }

    But this requires you to design your classes to be "interceptable", so it's basically unusable..

    In my previous post on Dependency Injection, I took you on a history trip, going all the way back to the Factory pattern.
    In this pattern you get an instance back of a class/interface, but you don't really know what instance that is..

    So, what would happen if I gave you back a proxy?

     439px-Proxy_pattern_diagram_svg

    A simple Proxy example would be

    public interface ISomething{
    void Foo();
    }

    becomes

    public class SomethingProxy : ISomething {
    private ISomething _worker;
    public void Foo(){
    // the method call is intercepted by the proxy
    _worker.Foo();
    }
    }

    Another example of a proxy is the generated class visual studio gives you when you add a web service/wcf service reference.
    Now, off course this example doesn't really give you any extra features, as you still write it by hand/let vs generate it.
    What you really need to pull AOP off is

    • a way to write what needs to happen when a method is called just once
    • a class that is reusable, no matter the interface(s) you need to implement

    what you need is a:

    Dynamic Proxy

    A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools.

    Now, the problem with .Net is that you're running into the limitations of the CLR on this one..
    So, I'm not even going to try and give you a babystep-example here :p

    Consider the Dynamic proxy from the Castle project

    Here, you have the notion of

    a proxy generator which returns you a proxy (duh)

    an IInterceptor which, as it's name implies, intercepts method calls.

    here's an example:

    public interface ISomething {
                void Foo();
    }
    public class Implementation : ISomething {
    public void Foo() {
    // no logging code here 
    }
    }

    the usage of the proxy becomes:

    ISomething realImplementation = new Implementation();
    ProxyGenerator generator = new ProxyGenerator();
    ISomething proxy = generator.CreateInterfaceProxyWithTarget<ISomething>(realImplementation, new LoggingInterceptor());
    proxy.Foo();

    and this is the IInterceptor implementation:

    public class LoggingInterceptor : IInterceptor  {
    public ILog Log { get; set; }

    public void Intercept(IInvocation invocation) {
    Log.Log(string.Format("start of method {0}", invocation.Method.Name));
    invocation.Proceed();
    Log.Log(string.Format("end of method {0}", invocation.Method.Name));
    }
    }

    So, by using this dynamic proxy and interceptor you've just "injected" behaviour into your class, so welcome to AOP...

    Creational patterns

    I'm guessing you can easily imagine the possibilities with a service locator pattern..
    One thing that you will find however, is that most AOP are marked by some creational pattern which returns a proxy of some sort.
    Personally, I mostly classify these frameworks under runtime AOP, where the type you get aint what you were expecting

    However, some other frameworks, like the already mentionned PostSharp do compile time code injection.
    This means that when you compile your project code is added to the stuff you wrote yourself. 
    The added benefit here (to me at least) is that you're not limited to the creational patterns.

    A loaded gun
    In closing AOP is a way to limit the number of times you write the same "cross cutting concern" code.
    However, if you start using AOP, consider that it really is a loaded gun, it's very easy to shoot yourself in the foot. 

    Maybe the most prominent gotcha is that what you see isn't what you get..
    As a personal war story, an architect once told me that using AOP was not done, as no developer in his company really understood it, the code that logged an error was not in the same location as the code that caused the error and so on.

    this leads me to the tip of the day, rethrowing exceptions without losing the call stack:

    try {
    //cause error
    } catch (Exception ex) {
    // do something with it
    throw;
    }

    notice that it's throw; and not throw ex;
    throw ex makes you lose the original callstack, throw preserves it.

    Saturday, 14 June 2008

    Things to look at on 14.06.2008

     

     

    Monday, 9 June 2008

    Things to look at on 09.06.2008

    • Oslo!
      aka, the product I'd give my left nut to work on :)
    • a decent definition of programming
      Programming is all about knowing when to boil the orange sponge donkey across the phillipines with an orangutang gorilla crossed with a ham sandwich to the fourth power of twelve across the nile with an awful headache from the previous night when all of alfred's naughty jalapeno peppers frog-marched the nordic elves across the loom-lined geronimo induced swamp donkey over and above the fortran fortified kilomanjaro fence past the meticulously crafted anti disgusting sponge cake scenario where all the hats doth quoteth the milk which is not unlike the super werewolf from the infinite realm of ninja-step. it's hard to define, really.

    Thursday, 5 June 2008

    Things to look at on 05.06.2008

    • t#
      A new .net language built for testing
    • www.twitter.com
      because all the cool kids are doing it ;)
    • Ian cooper on architects 
      may be that we need to go back, to go forwards, embrace the craft roots of our profession to find what 'architects' should do and re-embrace notions of mastery at a formal level instead of looking to modern ideas of architects for comparison.
      aka You can't you be an architect when you can't code..
    • James Kovacs' booklist
    • Velocity
      Project “Velocity” is a distributed in-memory application cache platform for developing scalable, available, and high-performance applications. “Velocity” fuses memory across multiple computers to give a single unified cache view to applications.
    • Managed Extensions framework is out
    • Power Threading Library (AsyncEnumerator & SyncGate) release

    A case for Dependency Injection

    [Disclaimer]
    I'm a interface based programming/IOC + dependency injection/location agnostic programming nut.

    why this post
    Recently, it seems that DI has become the new buzzword...
    As a self confessed DI nut I don't find such an issue with this, but I'd like to present the case for it nonetheless.
    Too often the usefullness of DI, nay the programming technique it represents, it looked on as a way to "make testing easier", which is just one of the benefits.

    example
    I'm going to try and take baby steps here, each time using a little bit of (psuedo) code to illustrate what I'm doing.

    public class CustomerLogic{
      private CustomerRepository repository = new CustomerRepository();
      public Customer Save(Customer c){
      return repository.Save(c);
      }
    }

    So what we have here is your basic "business logic" class that allows you to save a customer. 
    In this it uses the customer repository class which is part of the DAL.

    public class CustomerRepository {
      private Logger logger = new Logger();
      public Customer Save(Customer c){
         logger.log("saving customer");
        //save and return object
      }
    }

    OK, so far so good, because it works *cough*.

    Interface based programming
    I find this a tricky one to explain as every explanation only covers a part of the picture:

    • wikipedia
    • An application is made up out of different, logical components.
      When crossing from one type of component into another you prefer to use interfaces.
      eg: CustomerLogic-> IRepository, not Repository
    • prefer interfaces over base classes, thus avoiding the diamond of death :)
    • interfaces allow you to limit the number of members a class can call
      eg: say you are trying to do webforms MVC (i'm not talking about the new MVC framework)
      in this your controller needs a reference to your view (the webform), something like:

      private Controller controller = new Controller(this);

      If you do this with the view type, than every method on the view is visible to the controller, even stuff you'd like not to see.  However, if you do this with an interface IView, then only the methods on the IView interface are visible to the controller.
    • interfaces allow for the "I DON'T CARE" principle
      reusing the previous example, the controller doesn't care who the view is, it just needs an implementaiton of IView to work with.

    Ok, so what does this mean for our running example?

    public class CustomerLogic{
      private IRepository<Customer> repository = new CustomerRepository();
      public Customer Save(Customer c){
      return repository.Save(c);
      }
    }
    public class CustomerRepository : IRepository<Customer> {
      private ILog logger = new Logger();
      public Customer Save(Customer c){
         logger.log("saving customer");
        //save and return object
      }
    }
    public interface IRepository<T>{
      T Save(T item);
    }

    public interface ILog {
    void Log(string message);
    }

    So now we've ended up with

    private ILog logger = new Logger();
    private IRepository<Customer> repository = new CustomerRepository();

    both of these still have a concrete type specified, so applying the interface made it possible for limiting the number of methods that can be called, however, my class still needs to care about who does the work.

    Factory pattern
    Enter the factory pattern, which gives you

    public class CustomerLogic{
      private IRepository<Customer> repository ;
      public CustomerLogic(){
       repository = RepositoryFactory.Create<Customer>();
      }
      public Customer Save(Customer c){
      return repository.Save(c);
      }
    }
    public class CustomerRepository : IRepository<Customer> {
      private ILog logger  ;
      public CustomerRepository(){
       logger = LoggerFactory.Create();
      }
      public Customer Save(Customer c){
         logger.log("saving customer");
        //save and return object
      }
    }

    public static class RepositoryFactory{
      public static IRepository Create<T>(){
        if( typeof(T).Equals(typeof(Customer)){return new CustomerRepository();}
      }
    }
    public static class LoggerFactory{
      public static ILog Create(){
        return new Logger();
      }
    }

    So what has happened here? 

    • we have split out any concrete type information fromthe logic class.
      Finally our logic class doesn't have to care who does the work any more!
    • all creational logic is encapsulated in a factory, so changing what kind of type is created can be done in one place.

    There's only one problem...

    The factory as presented above expects you to know any type you want to return at the moment you are writing the code.
    This means that if after deployment you want to change that type, you need to recompile your application. 
    While this is acceptable in most scenario's it's not always, so here's the next silver bullet: the dynamic factory pattern

    Dynamic factory pattern

    An easy fix for this is to use a configuration driven approach, wherein the type to load is specified via the app/web.config. 
    About a million ways exist to do this, but mainly I used to go for the custom configuration element approach. 
    In the end it all comes down to

    public static class RepositoryFactory{
      public static IRepository Create<T>(){ 
       // check to see if you already have this object, for instance if it's already instantiated and so on
       // life time management is a topic in it's own right..
       T instance = ObjectFactory.Create<IRepository<T>>();
       // save the instance?
       return instance;

      }
    }

    public class ObjectFactory{
    public static T Create<T>(string type){
    Type t = Type.Load("yourtype's fullname / assembly qualified name here");
    return System.Activator.CreateInstance(t) as T;
    }
    }

    which is the configurable approach..
    Again, while this is a lot better than the previous approach, it far from perfect.

    The main issue is that the RepositoryFactory doens't really have a raison d'être anymore.

    Service Locator
    Enter the service locator pattern, which is the factory to rule them all ;)

    public static class ServiceLocator{
    public static T Create<T>(){
    //life time management
    // if type not found, create a new one and return
    T instance = ObjectFactory.Create<T>();
    // life time manangement
    return instance;
    }

    }

    public class CustomerLogic{
      private IRepository<Customer> repository ;
      public CustomerLogic(){
       repository = ServiceLocator.Create<IRepository<Customer>>();
      }
      public Customer Save(Customer c){
      return repository.Save(c);
      }
    }

    public class CustomerRepository : IRepository<Customer> {
      private ILog logger  ;
      public CustomerRepository(){
       logger = ServiceLocator.Create<ILog>();
      }
      public Customer Save(Customer c){
         logger.log("saving customer");
        //save and return object
      }
    }

    less code (no more dedicated factories), me happy

    Dependency injection
    So what is left for us to tackle?
    The biggest issue that still remains is the dependencies we need to manually resolve:

      private IRepository<Customer> repository ;
      public CustomerLogic(){
       repository = ServiceLocator.Create<IRepository<Customer>>();
      }

      private ILog logger  ;
      public CustomerRepository(){
       logger = ServiceLocator.Create<ILog>();
      }

    Wouldn't it be great if this could have been done automatically?
    Unsurprisingly, this is what *your favorite dependency injection container* does.

    if we take Unity as an example, you either decorate properties with the [Dependency] attribute, or have one constructor (which is then used for DI) or have a  [InjectionConstructor] attribute on it.

    public class CustomerLogic{

      [Dependency]
      public IRepository<Customer> repository {get;set} 
     
      public Customer Save(Customer c){
      return repository.Save(c);
      }
    }

    public class CustomerRepository : IRepository<Customer> {
      private ILog logger  ;
      public CustomerRepository(ILog  log){
       logger = log;
      }
      public Customer Save(Customer c){
         logger.log("saving customer");
        //save and return object
      }
    }

    so now your usage becomes

    UnityContainer container = new UnityContainer();
    CustomerLogic logic = container.Create(CustomerLogic);
    logic.Save(customer);

    So, what is the object of Injection

    Recently, I talked to an ex collegae who asked me what I consider to be an appropriate target for DI?

    • never never never domain objects
    • anything which you can call a "logical service", which you can "hide" behind an interface. (service is a badly overused words these days)
      eg: a data layer, an external service, and so on.

    This is also my major gripe with the entlib IV daab, on which I have a post here
    Entlib IV doens't resolve a "logical service", rather it resolves an instance that should be returned by a "logical service" => the Database object.

    Conclusion

    At the beginning of this post I mentionned that all too IOC/DI are considered to be minor enhancements for testability/mocking.
    However, if you've been paying attention, you should have noticed that we have been able to influence the returned type from the dynamic factory onward.

    I hope that this post has shown you that DI actually emerged from the other patterns (factory, dynamic factory, service locator) we have been using for years.
    If you would, take a look at the other posts on Unity I have made.
    Consider if you will that a DI container allows you to build interface driven component - based systems, where the container becomes the central point for resolving other objects.

    Wednesday, 4 June 2008

    wcf primer 7 - creating a client

    you can find the landing page here

    Creating a proxy with Visual studio

    If you're using VS 2008, (if you're not, ask yourself why.), you can easily add a proxy to an existing WCF service by right clicking the project node and using the "Add Service reference" option.  Just one caveat here, you actually need a MEX endpoint to do this.

    Right click on a project node in VS and choose add service refererence, which will give you something like this:

    add service reference

    Using the Advanced button will give you access to some code generation parameters.

    advanced

    Hitting OK gives you

    Service Reference1

    So, the interesting part here lies in the reference.cs file - as it contains:

    • proxy class
    • data contracts (client styled)
    • service interface (client styled)

    Sharing Data contracts

    As indicated above the data contracts generated by the "Add service reference" process are "client styled", which means that they are created on the basis of what you have specified as data members and data contracts.  While this is perfectly acceptable in most cases, and a *pure* implementation of SOA principles, sometimes you need something different.

    WCF gives you the possibility to share your data contracts, just add the data contract assembly to the project and regenerate your service reference!  Presto, your service reference is using the contracts defined in the referenced assembly. So now you have the same *type* of object in both client and server, which makes life a bit easier.

    However, it also enables you to quickly run your project into the ground.. Imagine domain objects with behaviour that should run on the server, but which are shared.

    Sharing Service contracts

    You would imagine that  you can do exactly the same with the service contracts, but unfortunately this is a no go... the proxy keeps on having his own contract version..

    Imho, this is a serious bug, but more on it in a later post.

     

    Creating a proxy manually

    Unsurprisingly, you can also create a channel manually:

    var proxy = ClientChannelFactory.CreateChannel<IService>();

    proxy.Open();

    //do some stuff

    proxy.Close();

     

    What you have to notice here is that you are reusing the service contract and the datacontracts from within their own assemblies, which is better than sliced bread!

    Sunday, 1 June 2008

    Things to look at on 01.06.2008

    general

    on being an expert

    agile development @ MSFT

    Scott Galloway's random .net links

    deepfriedbytes.com

    VS 2008

    visual studio powercommands

    Sacrifice your RAM on the VS altar

    WCF

    WCF best practices

    WCF dependency injection series

    Guess who's back?

    It's been a while.. work.. life.. age of conan.