Wednesday, 30 April 2008

Software, a factory approach - code generation

This is the fifth post in this series, you can find the landing page here
The code for this step of the series can be downloaded here.

So, in the previous posts we created both the data, service and fault models.
In fact, all we've done is created abstract definitions of how we want our code to look like.

So the next thing to do is to choose the implementation technology to use for these services.
For the purposes of this series I'm going with WCF implementation.

Add a project
Right click the solution and choose Add\WCF implementation project

1. add implementation project

When clicking OK in this dialog, visual studio adds a number of projects to the solution, giving you a solution explorer like:

2. solution explorer

Configure the models

Next step in the generation of code is to configure the models you've created to use WCF and to set the generation target projects.  Open the three diagrams, set the properties of each diagram as per the image below and save all.  Afterwards, right click and select validate all.

3. model properties

Validation errors

So, after validation you should have 32 errors!
While this may seem a bit wtf, it's quite normal and I've hinted at the source of these errors before (see data model).
My point was to address these points only after making the choice between WCF and ASMX implementation

First off, let's go and fix the errors:

Data model

  • error: All the datamembers in the datacontract class '...' must have a Unique 'Order' property.
    right click inside the Model diagram and choose "Order all DataMembers", afterwards right click and select validate all

Service model

  • error: you must use the DataContractSerializer on the service contract model...
    in the properties of the service model, set the serializer to Data contract serializer
  • error: The message '...' cannot have the property 'IsWrapped' set to false and contain more than one message part
    select the appropriate message and set IsWrapped to true

After these corrections, you should have no more errors and you can continue to generate the code (right click the model and select generate code).

Generated code

Now, take a moment to bask in the light of generated code ;)

Tuesday, 29 April 2008

Spec # - contract based c# (joy!)

The Spec# programming system is a new attempt at a more cost effective way to develop and maintain high-quality software.  Spec# is pronounced "Spec sharp" and can be written (and searched for) as the "specsharp" or "Spec# programming system".  The Spec# system consists of:

  • The Spec# programming language.  Spec# is an extension of the object-oriented language C#.  It extends the type system to include non-null types and checked exceptions.  It provides method contracts in the form of pre- and postconditions as well as object invariants.
  • The Spec# compiler.  Integrated into the Microsoft Visual Studio development environment for the .NET platform, the compiler statically enforces non-null types, emits run-time checks for method contracts and invariants, and records the contracts as metadata for consumption by downstream tools.
  • The Spec# static program verifier.  This component (codenamed Boogie) generates logical verification conditions from a Spec# program.  Internally, it uses an automatic theorem prover that analyzes the verification conditions to prove the correctness of the program or find errors in it.

(from http://research.microsoft.com/SpecSharp/#docs)

 

 

download spec# (for visual studio 2008)
download simplify

Things to look at on 29.04.2008

Monday, 28 April 2008

c# 3.0 - putting it all together part 4

This is part 13 in the c# 3.0, didn't think it would take this long, you can find the landing page here.
This is also the last part in this series.  I guess I've reached what I wanted to do, show you the largest new features in .net 3.5 and how they are used in LINQ.  As always, feedback is welcomed :)

So, last time you got a list of LINQ operators, indicating if they are (non) deferred and (non) streaming. 
This post goes into some more detail on a few query operators.  As per the previous post, any deferred execution is done via an iterator, so I won't repeat that here - you can use reflector on the System.Core dll if you want to find out more about it.

 

Where
= filters  items into a sequence
= deferred
= the where method offers two implementations, one which has already been discussed in a previous post, and a second one:
public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
the overload method for Where receives an extra integer, which is actually the index from the item in the collection.

eg: List<string> names = new List<string>()  {"john","bob","tom"};
       var query = names.Where( (n,i) => i > 1); 

the output of this query will be tom, as he's the only name with an index > 1.

 

Select
= returns a sequence of S from a sequence of T
= deferred
= overloaded with indexed version (see above)

One thing is of note on the select method:
public static IEnumerable<S> Select<T, S>(  this IEnumerable<T> source,  Func<T, S> selector);

Func<T, S> => the selection does not need to return the same type
eg: List<Customer> customers = new List<<Customer>(){new Customer(){Name="Bob", Id="1"}, ... };
       var query = customers.Select( c => new {Name=c.Name});

 

SelectMany
= selects zero or more elements S for each element of an input sequence T
= deferred
= overloaded with indexed version (see above)

public static IEnumerable<S> SelectMany<T, S>(  this IEnumerable<T> source,  Func<T, IEnumerable<S>> selector);

eg: the following will return an IEnumerable with all the products in it

public class ProductCategory{
public List<Product> Products {get;set;}
}

List<ProductCategory> categories = new List<ProductCategory>(){...};
IEnumerable<Product> = categories.SelectMany(category => category.Products);

 

Join
= Correlates the elements of two sequences based on matching keys. The default equality comparer is used to compare keys
= deferred

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(   this IEnumerable<TOuter> outer,    IEnumerable<TInner> inner,     Func<TOuter, TKey> outerKeySelector,    Func<TInner, TKey> innerKeySelector,   Func<TOuter, TInner, TResult> resultSelector
)

eg: the following returns a sequence of items with two fields= CustomerId, OrderId

List<Customer> customers = new List<Customer>(){...}
List<Order> orders = new List<Order>(){...};

var query =
customers.Join(orders       
, customer => customer.Id   //key for customers is the ID
, order => order.CustomerId // key for the order is the CustomerID
, (customer, order) => new { CustomerId = customer.Id, OrderId = order.Id } // given a customer and an order, select the two id's
    );

Sunday, 27 April 2008

Software, a factory approach - services

This is the fourth post in this series, you can find the landing page here
The code for this step of the series can be downloaded here.

In the previous post we created the data model for our tracker application, now we'll tackle the services model.  For the sake of brevity I'll only discuss creating one of the two services that are in the example code, the second is completely similar.

Services

First  off, right click the Tracker node in the solution explorer, and click Add\New model

1. create service contract model

Once more, you're greeted with a blank designer surface, one that's just yearning for some service model components. 
The following images shows you the Toolbox items you get for this designer:

2. toolbox

You can put the components on the designer surface in any order, connecting them as you want.  I mostly start by adding a service, then the contract and using the connector to connect them, as per the following image.

3. service   contract

Of note here is that you create a service contract without the habitual I prefix, the I will get added automatically.

Operations

Next step is adding the operations to the service contract. You start by dragging an operation shape onto the designer, renaming it to CreatePickupRequest and connecting it with the service contract with the connector tool.

So now you've created a void method on the contract.  However, seeing as this probably isn't what you want, you should add some parameters.

Add two messages onto the designer surface, and rename them to CreatePickupRequestIn and CreatePickupRequestOut.  Using the connector tool create a connection from the CreatePickupRequestIn message to the operation and from the operation to the CreatePickupRequestOut message.

This should give you the following result:

4. service model start

Right clicking the message allows you to add either a primitive data type or a data contract type, which is similar to designing data contracts.

Faults

As stated in the previous post, and as the image above already shows, each operation allows you to add faults to it. 
For the fault unsavy, this is what Mr Wcf himself, Juval Löwy, has to say about faults in his most excellent book "Programming WCF Services":

Any service operation can at any moment encounter an unexpected error. The ques-
tion is how (if at all) that error should be reported back to the client. Concepts such
as exceptions and exception handling are technology-specific and should not tran-
scend the service boundary. In addition, typically error handling is a local implemen-
tation detail that should not affect the client, partly because the client may not care
about the details of the errors (other than the fact that something went wrong), but
mostly because in a well-designed application, the service is encapsulated so that the
client does not have anything meaningful to do about the error anyway. A well-
designed service should be autonomous as much as possible, and should not depend
on its client to handle and recover the error. Anything beyond a blank error notifica-
tion should in fact be part of the contractual interaction between the client and the
service.

The pickup service requires you to specify a number of parameters to create a pickup request:

  • Pickup (Location)
  • Delivery (Location)
  • CustomerId (long)

For the sake of simplicity I've identified two possible faults for this service:

  • missing parameter
  • unknown customer id

For this next step, I normally create a new DataContract model, with the namespace http://company.com/Tracker/Services/Faults/2008/04, but this is a matter of taste more than anything else, you could also add these to the existing data contract model.

In the end you'll have the following faults (I added a Message member):

5. faults

After which you can update your service model :

6. service model finish

So this concludes the services part of our example application.
Validating the models should give some errors concerning the fact that you haven't chosen an implementation technology, but we'll deal with that in the next installment.

Things to look at on 27.04.2008

Saturday, 26 April 2008

Dependency Injection & Object configuration

 

This post was sparked off by another post by Chris.
In his "Should classes by DI friendly?" post he talks about one DI issue he's having,  the need to pass "other" configuration data to the object you want to DI.  Let's take a quick tour of the issue at hand:

Say you have the following class

public class ServiceImplementation : IService{
   public ServiceImplementation(ILog log){}
}

then the DI usage scenario becomes quite simple:

public class Usage{
public void Test(){
  UnityContainer container = new UnityContainer();
  IService svc = container.Resolve<IService>();
}
}

However, now add a requirement for an extra configuration parameter:

public class ServiceImplementation : IService{
   public ServiceImplementation(ILog log, string someValue){}
}

Now, the question becomes: how can you add this extra information?

Configurator class
The first solution that comes to mind, an also one i tried to submit to his blog, but I'm not sure Feeddemon actually sent it ^^, is to add a new Configurator class which provides the necessary data and adding that configurator class as a constructor argument:

public class ServiceImplementationConfigurator{
  public string GetSomeValue(){}
}

public class ServiceImplementation : IService{
   public ServiceImplementation(ILog log, ServiceImplementationConfigurator configuration){}
}

The big advantage here is that you don't need to embark on a journey to subclass the unity container, you just add another dependency to the container. Disadvantage here is that your class depends on another object, but honestly I don't really mind this :)

As always, if you want to comment feel free :)

Software, a factory approach - getting started

This is the third post in this series, you can find the landing page here
The code for this step of the series can be downloaded here.

First step in the creation of the tracker platform is creating the visual studio project, so open up your favorite IDE and get cracking..

Create a project

File\New\Project leads you to the following:
1. create model project

An ok later we have the following in our solution explorer:

2. solution explorer

 

DTO

The next step is the creation of the Data Transfer Objects, the messages that are exposed to your services clients.

Right click on the Tracker project and choose Add\New Model

3. add datamodel

This leads you to an empty designer surface, with a toolbox looking like this:

4. Toolbox

Of note here is the fault contract, to which i'll return later.

The data contract tools allow you to model your data contracts (no big surprise there ).
I think the interface is pretty straightforward, so you shouldn't have too much problems getting this running. 

First off I created the data contracts specified in the previous post, plus some more support classes (name, address and so on).

Second step is to add the required properties to each data contract. Use the aggregation tool when adding another contract as a property.

Please note that at this stage (before choosing the implementation technology) you don't need to specify the Order property on the properties, as it's not certain you really need to. (I'll get back to this in a later post).

5. property detail

The only (minor) gripe I have is with the defining of the type.
having to open a pop up window to get to System.int64 seems a bit ... cumbersome.
  6. type selector

The image below depicts my finished model diagram. 
7. datamodel

 

When you right click on the diagram and choose Validate, you'll get two validation errors, saying that you've not chosen any implementation technology and that the projectmapping is empty.  This is normal, don't worry about it :).

So now we have successfully created a data model using the wssf data contract designer!  In the next post we'll go on to create the services.

Friday, 25 April 2008

c# 3.0 - landing page

This will serve as a landing page for the c# 3.0 series, it's a bit late in the game, but meh ^^

Thursday, 24 April 2008

Mesh

I already hinted at this yesterday, today's there's some more Mesh buzz on the internet:

This looks like Microsofts next step in the S + S initiative. With mesh they deliver more than just another piece of cloud-storage, basically this is a new platform to develop applications for!

We live in exciting times :)

Software, a factory approach - requirements

This is the second post in this series, you can find the landing page here.

The objective of this series is to develop a new platform called Tracker for a fictional package delivery company. The tracker platform needs to have the following features:

web application for customers

  • registered customers can make a package pickup request
  • registered customers can view a master and detail page of past and current packages
  • anonymous users can view a package status based on a shipment id

web application for employees

each delivery comes equipped with a laptop with a wireless (gprs) connection.  Employees must be able to update the status of the shipment they are trying to deliver.

As everyone loves a nice little diagram:   

tracking system overview

 

Domain Model

As the application we're creating is built around shipping packages it may not be the biggest surprise ever that the domain is shipment central:

(Please also note that the model is heavily simplified, it doenst' take into account a lot of the concentps that would be required to make a real functioning solution)

  • Shipment
    At the core of the system is the Shipment Entity, which is the sum of a package (what to send), a pickup location (where to get it), a delivery location (where to deliver it) , a customerId (who to bill for this shipment) and a status (where is the delivery in it's lifecycle).
  • Shipment id
    A shipment id is a composite key made up out of
    • Code of the pickup office
    • Code of the delivery office
    • Date of the pickup request
    • Sequential id for that day
  • Package
    Properties of the package include height, width and weight
  • Location
    A location is comprised of an address, a name of the contact person and a telephone number
  • Shipment status
    The status depicts the different stages in life for a shipment, from the moment the pickup is requested until the final delivery.
    • When a customer enters a pickup request, a shipment is created as ToPickup
    • When the employee has picked the shipment up, the status evolves to PickedUp
    • When the package arrrives into the pickup office the status evolves to InPickUpOffice, unless the pickup office is alos the delivery office, then the status evolves immediately to InDeliveryOffice
    • When the package leaves the pickup office on it's way to the delivery office the shipment becomes InTransit
    • When deliverd to the delivery office it becomes InDeliveryOffice
    • When going out to the delivery location it becomes ToDeliver
    • When dropped off at the delivery location it evolves to Delivered, if the delivery was impossible (no one was home), it goes back to InTransit.
  • Shipment History
    The shipment history shows all of the transitions of the shipment's status

In the next installment I'll be creating the datamodel using the WSSF, stay tuned ;)

Software, a factory approach - landing page

This post serves as the landing page for the Software, a factory approach series. (this will be updated after every post)

Software, a factory approach - preface

With the Web Service Software Factory (wssf for short) our friends at P&P release have yet again released a nifty piece of software! 

For those that have no clue what a software factory is, I'd like to point to the MSDN series on software factories.  Basically (or at least what I make it to be), a software factory allows you to (partially) automate the development of common scenario's (web clients, web services and so on).

Microsoft - or more specifically P&P - have taken the idea of a software factory to the next level with their tools:

  • guidance extensions and toolkit
  • Domain specific languages
  • Software factories
    (DSL + guidance recipes)

Couple all of the above with the (in)famous Entreprise library and you get a sense of where Entreprise development is at today.

For the coming series you'll need:

In the next post in this series, I'll be explaining some more about the application we're trying to build.

c# 3.0 - putting it all together part 3

Part 3 of the putting it together monster post shows you, in more detail, the standard query operators and  their method of execution:

  • immediate
  • deferred
    see previous post
  • streaming
    these operators can start returning data as they process it
    eg: a where clause that tests the name of a customer can return a customer after processing it.  This is done via the yield statement
  • non streaming
    these operators only return data after reading all of the data source. eg Except needs to filter on all the other items...

The original list can be found at
http://msdn2.microsoft.com/en-us/library/bb882641.aspx 

 

 

If an operator is marked in two columns, two input sequences are involved in the operation and each sequence is evaluated differently. In these cases, it is always the first sequence in the parameter list that is evaluated in a deferred, streaming manner.

Standard Query Operator

Return Type

Immediate Execution

Deferred Streaming Execution

Deferred Non-Streaming Execution

Aggregate

TSource

X

 

 

All<(Of <(TSource>)>)

Boolean

X

 

 

Any

Boolean

X

 

 

AsEnumerable<(Of <(TSource>)>)

IEnumerable<(Of <(T>)>)

X

 

Average

Single numeric value

X

 

 

Cast<(Of <(TResult>)>)

IEnumerable<(Of <(T>)>)

 

X

 

Concat<(Of <(TSource>)>)

IEnumerable<(Of <(T>)>)

 

X

 

Contains

Boolean

X

 

 

Count

Int32

X

 

 

DefaultIfEmpty

IEnumerable<(Of <(T>)>)

 

X

 

Distinct

IEnumerable<(Of <(T>)>)

 

X

 

ElementAt<(Of <(TSource>)>)

TSource

X

 

 

ElementAtOrDefault<(Of <(TSource>)>)

TSource

X

 

 

Empty<(Of <(TResult>)>)

IEnumerable<(Of <(T>)>)

X

 

 

Except

IEnumerable<(Of <(T>)>)

X

X

First

TSource

X

 

 

FirstOrDefault

TSource

X

 

 

GroupBy

IEnumerable<(Of <(T>)>)

 

 

X

GroupJoin

IEnumerable<(Of <(T>)>)

X

Intersect

IEnumerable<(Of <(T>)>)

X

X

Join

IEnumerable<(Of <(T>)>)

X

X

Last

TSource

X

 

 

LastOrDefault

TSource

X

 

 

LongCount

Int64

X

 

 

Max

Single numeric value, TSource, or TResult

X

 

 

Min

Single numeric value, TSource, or TResult

X

 

 

OfType<(Of <(TResult>)>)

IEnumerable<(Of <(T>)>)

 

X

 

OrderBy

IOrderedEnumerable<(Of <(TElement>)>)

 

 

X

OrderByDescending

IOrderedEnumerable<(Of <(TElement>)>)

 

 

X

Range

IEnumerable<(Of <(T>)>)

 

X

 

Repeat<(Of <(TResult>)>)

IEnumerable<(Of <(T>)>)

 

X

 

Reverse<(Of <(TSource>)>)

IEnumerable<(Of <(T>)>)

 

 

X

Select

IEnumerable<(Of <(T>)>)

 

X

 

SelectMany

IEnumerable<(Of <(T>)>)

 

X

 

SequenceEqual

Boolean

X

 

 

Single

TSource

X

 

 

SingleOrDefault

TSource

X

 

 

Skip<(Of <(TSource>)>)

IEnumerable<(Of <(T>)>)

 

X

 

SkipWhile

IEnumerable<(Of <(T>)>)

 

X

 

Sum

Single numeric value

X

 

 

Take<(Of <(TSource>)>)

IEnumerable<(Of <(T>)>)

 

X

 

TakeWhile

IEnumerable<(Of <(T>)>)

 

X

 

ThenBy

IOrderedEnumerable<(Of <(TElement>)>)

 

 

X

ThenByDescending

IOrderedEnumerable<(Of <(TElement>)>)

 

 

X

ToArray<(Of <(TSource>)>)

TSource array

X

 

 

ToDictionary

Dictionary<(Of <(TKey, TValue>)>)

X

 

 

ToList<(Of <(TSource>)>)

IList<(Of <(T>)>)

X

 

 

ToLookup

ILookup<(Of <(TKey, TElement>)>)

X

 

 

Union

IEnumerable<(Of <(T>)>)

 

X

 

Where

IEnumerable<(Of <(T>)>)

 

X

 

Wednesday, 23 April 2008

c# 3.0 - putting it all together part 2

In the previous installment I talked about how combining the power of Fluent Interfaces and lambda's leads to a nice and concise way of programmic, which was a sneaky way to introduce some LINQ upfront

A few concepts beg introduction:

  • sequence
    any collection implementing IEnumerable<T>

    For the poor non generic collections (those in the System.Collections namespace) the  Enumerable class (see Standard query operators) contains two methods:
    • Cast<T>
      casts each of the elements in the non generic collection to the T type.  Throws an exception if the element can not be cast to the desired type.
    • TypeOf<T>
      acts a filter on the old non generic collection, returns only those elements that can be cast to the desired type.
  • element
    an item in a sequence
  • lambda queries
    queries written using lambda expressions

    IEnumerable<Customer> filtered =
    customers.Where(c => c.ZipCode == "9000");
  • comprehension queries
    queries written using comprehension syntax (sql like syntax)
    IEnumerable<Customer> filtered =
         from c in customers
         where c.ZipCode == "9000"
         select c;

Standard query operators
The standard query operations are extension methods defined in the System.Linq.Enumerable class. These methods extend the IEnumerable<T> interface.

Looking more closely at these methods you might see that most of the return an IEnumerable<T>, which allows for a fluent interface style of programming. 

Another thing you might notice that a lot of the overloads accept a parameter of the type Func.  If you paid close enough attention you may know that lambda expressions boil down to delegates. Delegates of the type Func to be more precise.  Long story short, you can pass in a delegate instead of an explicitly created Func delegate.

Deferred Execution

The next thing to pick up on is that Linq works using deferred execution, which basically means that you get an object back that when called will execute the query and return the results.
To me this object is a filter-like object. Consider the following code:

List<Customer> customers = new List<Customer>(){
            new Customer(){Id=1,Name="Tom"},
            new Customer(){Id=2,Name="Bob"},
            new Customer(){Id=3,Name="Bart"},
            new Customer(){Id=4,Name="Robert"}
            };

IEnumerable<Customer> filter = customers.Where(c => c.Name.Contains('b'));

The filter object you receive doens't really contain the customers whose name has the character b in it. That's because the IEnumerable you get back isn't a list! Rather, and i'll save you the trouble of opening reflector and so on, what you really get back from the Where method is an WhereIterator.
I'll spare you the complete code from this one, as it's generated and it took me about 10 minutes to clean it up and even then it's not the most readable of code.

Basically, when a call to the MoveNext method is made the iterator

  • checks the underlying collection for a nex item
  • gets the collection's item
  • checks the item if the answers to the where clause
    • if true, return the item
    • if false, rinse and repeat

public class WhereIterator<T>
{
    private T current;
   private IEnumerable<T> source;
   private IEnumerator<T> sourceEnumerator;
    private Func<T, bool> predicate;

    bool IEnumerator.MoveNext
    {
        get
        {
           bool found = false;
            // while not found and the original collection has a next item
            while (!found && sourceEnumerator.MoveNext)
            {
                found = CheckCurrent();
                if (found) { return true; }
            }
            return false;
        }

    }
    private bool CheckCurrent() {
        T item = sourceEnumerator.Current;
      //item answers to the where clause
        if (predicate(item)) {
            current = sourceEnumerator.Current;
            return true;
        }
        return false;
    }

}

 

To show this off, let's revisit the code example:

IEnumerable<Customer> filter = customers.Where(c => c.Name.Contains('b'));

foreach(Customer c in filter){
    Console.Write(c.Name + " ");
}

// will produce Bob Bart Robert

customers[1].Name="john";

foreach(Customer c in filter){
    Console.Write(c.Name + " ");
}

 // will produce Bart Robert

So, as you can see, the "filter" is re-executed (the second foreach leads to the Iterator being reset, so checking the collection again).

If you do need a list, with the objects that answer to the deferred query in them, all you need to do is call ToList<T> on the query:

List<Customer> result = customers.Where(c => c.Name.Contains('b')).ToList<Customer>();

Things to look at on 23.04.2008

- Mesh
Live Mesh is mostly a file-sharing and folder-synchronization service, as well as a nice, easy way to access a PC remotely. Down the road though, it's Microsoft's latest attempt to find preeminence in a world in which Microsoft-based devices are just part of the mix. (according to www.news.com)

- Composite Web Application Block + Unity
Michael Puleio is trying to refactor the CWAB to use the DI container Unity*! Unfortunately he walks into a couple of obstacles during the development...

*This is actually what I was hoping for, a re-engineering effort which will leave the various application blocks in a much cleaner, conciser way.. giving my poor brain less code to grok!

Tuesday, 22 April 2008

c# 3.0 - Odds and ends

C# 3.0 doesn't only give us the big features previously discussed, it also has a number of smaller improvements:

- HashSet<T>
Deep within the bowels of the System.Core dll a new generic collection can be found: HashSet<T>, which is the generic HashTable that was missing up till now..

- TimeZoneInfo
   yet another PITA has been resolved in 3.0..  The new TimeZoneInfo class allows you to recalculate time to other timezones, which in previous version was hairy at best.

- System.Data.DbType
The DbType enumeration has a few new types, mainly to support the coming of SQL 2008. Just one question here: DataTime2? Who's in charge of naming these things? :p

Things to look at on 22.04.2008

- Tom Opgenorth has a series of posts dealing with the sessions he followed during the ALT.net conference in Seattle, which was organized on the heels of the MVP Summit.  Basically it's just a series of brief summaries, but it makes me wish I had been there :sadness:

- Ayende has a DSL article on InfoQ

- I want to be a development hobo

Rhino Mocks + Unity

Roy has a post up about creating an autmocking container using Unity and Rhino mocks. Not only is it a nice example of mocking dependencies, it also uses a custom implementation of the lifetimemanager :)

Friday, 18 April 2008

Unity DI Container

Unity is the new DI container from our good friends at Patterns & practices.  It's based on Objectbuilder v 2.0, which is a refactored version of the original Objectbuilder which is at the core of Entreprise library.

Unity is just like any other of the big DI containers, but here and there with a few twists :) .

Registering types

Unity provides a few ways to register up the types

  • RegisterType

    The registerType (both generic and non generic) method allows you to register an interface and a concrete implementation.

    UnityContainer container = new UnityContainer();
    container.RegisterType<ILog, EventLogLogger>();

    and the non generic variant:

    container.RegisterType(typeof(ILog), typeof(EventLogLogger));
  • LifeTimeManager

    The above syntax registers a type, resolving returns a new implementation each time. An additional parameter can be added, which allows you to control the object's initialization. 

    The LifeTimeManager below makes your type a singleton.

    UnityContainer container = new UnityContainer();
    container.RegisterType<ILog, EventLogLogger>(new ContainerControlledLifetimeManager());
  • Named instances

    An further possibility allows you to register named instances, these methods are overriden to allow you to specify a LifeTimeManager as well.
    UnityContainer container = new UnityContainer();
    container.RegisterType<ILog, EventLogLogger>("Event");
    container.RegisterType<ILog, DatabaseLogger>("Db");
  • Register instances

    Unity also allows you to pass in already constructed instances, which are then treated as a singleton.

    DatabaseLoggerlog = new DatabaseLogger();
    container.RegisterInstance<ILog>(log);

Resolve

  • Resolve

    The resolve method allows you to retrieve an instance of a certain interface as follows

    ILog log = container.Resolve<ILog>();

  • Named instances

    Named instances are retrieved the exact same way, only add the name required

    ILog log = container.Resolve<ILog>("Event");
  • ResolveAll

    ResolveAll returns all the named instances of a currently registerd interface:

    IEnumerable<ILog > list = container.ResolveAll<ILog >();

Buildup

Up to now, I've talked about the registering and retrieving of classes, the ServiceLocator piece of the Unity framework.  Let's not concentrate on the DI section.

  • constructor

    Unity can do constructor injection in two ways:
    • classes with one constructor

      Classes that have only one constructor can be automatically constructed, as long as the arguments to the constructor are mapped within the container..

      public class Example {
         private ILog log;

        public Example(ILog log) {
                      this.log = log;
          }
      }

    • InjectionConstructor

      When a class has multiple constructors, Unity needs to be told which one to use. This is done via a attribute placed on the appropriate constructor:

      public class Example {
                  private ILog log;
                  [InjectionConstructor]
                  public Example(ILog log) {
                      this.log = log;
                  }
                  public Example() {

                  }
      }

  • properties

    Unity also provides us with property injection:

    public class Example {
        [Dependency]
        public ILog Log { get; set; }
    }

  • BuildUp

    So how does the injection work?
    there are, again, two possibilities:
    • Unity creates the object:
      ILog log = container.Resolve<ILog>()
      the dependency injection is done out of the box, the object returned has all it's dependencies mapped.
    • Unity didn't create the object:
      If unity didn't create the object and you still want the object to have it's dependencies mapped:

      Example example = new Example();
      container.BuildUp<Example>(example);

Extensions

It is actually possible to extend Untiy, alltough it requires a deeper knowledge of how ObjectBuilder2 works...

Configuration

Unity also allows you to specify the type mappings into the application config (app.config / web.config) file, providing you thus with the ability to change which implementation is used without recompiling you code!  all praise the dynamic factory ;)

While this may seem something unimportant, image the following:
your application offers services to and depends on third parties.  These interactions are contract based (interface based).  This means that you can develop your code while the third party services aren't there yet and then with a simple switch of configuration enable the proxy for the third party service.

  • configuration code

    UnityConfigurationSection section = ConfigurationManager. GetSection("unity") as UnityConfigurationSection ;
    if (section != null) {
                    section.Containers.Default.Configure(container);
    }
  • config section
    <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </configSections>

    <unity>
    <typeAliases>
    <!-- Lifetime manager types -->
    <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
    </typeAliases>

    <containers>

    <container name="containerOne">
    <types>
    <!-- Type map with no lifetime defaults to "transient" -->
    <type type="Custom.MyBaseClass" mapTo="Custom.MyConcreteClass" />
    </types>

    <instances>
    <add name="MyInstance1" type="System.String" value="Some value" />
    </instances>

    <extensions>
    <add type="MyApp.MyExtensions.SpecialOne" /> </extensions>
    <extensionConfig>
    <add name="MyExtensionConfigHandler" type="MyApp.MyExtensions.SpecialOne.ConfigHandler" /> </extensionConfig>
    </container>

Conclusions

Imho, Unity looks a lot like the other DI containers already out there. It's main advantage is that it comes from the P&P group, so I'll probably be using it a lot on a number of upcoming projects.

The main question will be the integration of the unity container within the existing P&P application blocks and factories.

The community site already contains a number of proposals/feature requests, one which i can endorse: integrate the PIAB block within object builder!

Links

A screencast from David Hayden

download

Communtiy

Entlib v4 CTP, sadly without integration

Thursday, 17 April 2008

c# 3.0 - putting it all together part 1

So what does the combination of the various c# 3.0 features deliver us?  The answer: Linq.  Linq stands for Language Integrated Query and is perhaps the most significant change to programming coming from Redmond since the invention of the .net framework.

 

Fluent Interfaces

First off, let me talk a bit about fluent interfaces.
Fluent interfaces are nothing more than a programming style that allows you chain method (function) calls.

A basic example is

string s = "test";
s.ToUpper().Replace('t', 'x').ToCharArray().Length;

in this example the ToUpper and Replace method both return an instance of string, upon which method can be called. 

A second, perhaps more understandable example would be

namespace FluentInterfaces {
    public class Example {
        public void Test() {
            Query q = new Select("Id, Name").From("Customers").Where("ZipCode", Operator.Equals, "9000");
        }
    }

    public class Query {
    public Query Where(string field, Operator op, string value) {... }
    }

public enum Operator {
    Equals,
    Like,
}

   public class Select {
        private string _columns;
        private string _tableName;

       public Select(string columns) {
            _columns = columns;
        }
        public Query From(string tableName) {
            _tableName = tableName;
        }
    }
}

Framework extension methods
Before getting to Linq itself one more topic needs a bit of attention.  In one of the previous posts I already talked about extension methods, and how they allow you to add substantial functionality to existing classes.

The .net framework contains a whole slew of these methods themselves, conveniently grouped in the System.Linq namespace withing the System.Core dll. 

As an example, look somewhat close at the System.Ling.Enumerable class, this is a static class full of extension methods for the IEnumerable interface.

I want to treat one method in particular:

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
return WhereIterator<TSource>(source, predicate);
}


Looking at the method, you can see it's a generic extension method for a IEnumerable<T> that takes a predicate as a parameter to return an IEnumerable<T>.



Remember predicates?

A predicate is a method that takes a input parameter of type T which returns a bool :)



so you can use the extension method as follows:



public class SimpleFluentExamplePredicate {


   public void Test() {


        List<Customer> customers = new List<Customer>();


        IEnumerable<Customer> filtered = customers.Where(new Func<Customer,bool>(LivesInGent));


    }


    public bool LivesInGent(Customer c) {


        return c.ZipCode == "9000";


    }


}



but that's a bit too much code don't you think?

Here's the same, with a lambda mixed in it :)


public class SimpleFluentExampleLambda {


   public void Test() {


        List<Customer> customers = new List<Customer>();


        IEnumerable<Customer> filtered = customers.Where(c => c.ZipCode == "9000");


    }


}

 



Less code, me happy.

Wednesday, 16 April 2008

Things to look at on 16.04.2008

  • The Viewpoint flip: interesting note on what makes true SOA
  • Null transport for WCF.aspx
    Personally i'd done this a bit differently (my IOC container returns an implementation of an interfacec - wether that is a proxy or just a class).

  • OSLO . It seems like the MVP's are getting some advanced information on the new SOA paradigm/toolkit/approach.. poor me for being left in the dark.

c# 3.0 - lambda expressions

Lambda expressions are the logical consequence of .net 2.0's anonymous methods.  In fact had lambda's existed, there would never have been a raison-d'être for anonymous methods.

Let's start with a recap of delegates and anonymous methods..

Consider the following piece of code.  Connecting to the Example class's OnDoSomething event is done by creating a new DoSomething delgate.

namespace Delegates {
    public delegate void DoSomething(string s);

    public class Example {
         public event DoSomething OnDoSomething;
     }

    public class AnonymousMethods {
         public void Test() {
            Example example = new Example();
            example.OnDoSomething += new DoSomething(HandleDoSomething);
        }
         void HandleDoSomething(string s) {
            Console.WriteLine(s);
        }
     }
}

.net 2.0 provide us with anonymous methods, thereby eliminating the need for the explicit delegate.

namespace Anonymous{
    public delegate void DoSomething(string s);

    public class Example {
         public event DoSomething OnDoSomething;
     }

    public class AnonymousMethods {
         public void Test() {
            Example example = new Example();
            example.OnDoSomething += delegate(string s) {
            Console.WriteLine(s);
        };

        }
         }
}

.net 3.0 allows us to eliminate even more code, as per the next piece of code.

namespace Lambda{
    public delegate void DoSomething(string s);

    public class Example {
         public event DoSomething OnDoSomething;
     }

    public class AnonymousMethods {
         public void Test() {

  Example example = new Example();
example.OnDoSomething += (s => Console.WriteLine(s));
        }
     }
}

So let's take a better look at the expression itself..

(s => Console.WriteLine(s));

you can split up a lambda expression as follows:

- incoming arguments
  in this case there's only one incoming argument: s
  There's no type specified, it is the c# compiler doing type inference.
However, if you want to you can specify the type by

(string s => Console.WriteLine(s));

multiple arguments are aslo possible (however that would require a different delegate type)

(s, i) => Console.Writeline(s);i++;

- lambda sign: the => part
  there are a number of interpretations on how to pronounce the =>

  The following is a direct quote from Eric White:
Sometimes developers wonder how to pronounce the => token.

If the lambda expression is a predicate, expressing some condition: c => c.State == "WA" then the => can be spoken as "such that". In this example, you could say "c such that c dot state equals Washington". If the lambda expression is a projection, returning a new type: c => new XElement("CustomerID", c.CustomerID); then the => can be spoken as "becomes". In the above example, you could say "c becomes new XElement with a name of CustomerID and its value is c dot CustomerID". There is still some discussion here at MS about how best to pronounce =>, but this is how I say it. It was suggested by one of the people here to pronounce it as "goes to".

A quick note: predicates are simply boolean expressions that are passed to some method that will use the boolean expression to filter something. A projection is a lambda expression that takes one type, and returns a new type.

- the method implementation
  int his case Console.WriteLine

 

In the end, lambda's provide a more concise (and sometimes less readable) syntax for delegates. 

Tuesday, 15 April 2008

.net rocks - alt.net

a new .net rocks episode, this time the topic is alt.net!

clicky

new certification exams

according to Microsoft Certifications three new .net 3.5 exams have gone live:

70-502: Windows Presentation Foundation

70-503: Windows Communication Foundation

70-504: Windows Workflow Foundation

Monday, 14 April 2008

c# 3.0 - Extension Methods

A significant new feature is extension methods.
Extention methods allow you to extend the public API of a given class by adding methods to it.  This comes in handy in a number of scenario's, not in the least when you consume someone else's code...

Extensions are wrought by creating a static method on a static class with an incoming "this" parameter, after which the method becomes available on instances of the incoming parameter type (when the namespace of the extension method is in scope).

public class Example {
        public void Test() {
            int stuff = 5;
            stuff.Foo();

            string someString = "test string";
            someString.Foo();
        }
    }
   public static class Extensions {
        public static void Foo(this int i) {
            Console.WriteLine(i.ToString());
        }
        public static void Foo(this string s) {
            Console.WriteLine(s);
        }
    }

There are a few nice extension examples online concerning enumerations:
http://geekswithblogs.net/sdorman/archive/2007/09/25/Generic-Enum-Parsing-with-Extension-Methods.aspx 
http://www.codeproject.com/KB/cs/enumdatabinding.aspx

 

Compiler wise extension methods boil down to static method calls

4. extension methods - reflector

 

Usage of extension methods can be both a blessing and a curse.  It should be clear that extension methods, while useful, should not be used to replace good ol'fashioned class design. Creating a

public static void PrintOut(this string s){ Console.WriteLine(s);}

will still get you taken behind the barn and bludgeoned to death with a household utensil of your own choosing.

Note that generic extension methods are possible!

public interface Test<T>{}
public static SomeMethod<T>(this Test<T>){}

Rethrowing exceptions

As you may or may not know, rethrowing an exception using the code below - destroys the original stacktrace. Using throw (without the ex) solves that issue, you get the original stack trace back.

catch(Exception ex){

//do some stuff 
throw ex;

}

However, for remote exceptions this was always impossible, or so I tought.. Brad Wilson has a solution for that issue.

Yay for code hacks from microsoft :p

Sunday, 13 April 2008

.net 3.5 training kit released

 

Overview

The .NET Framework 3.5 Enhancements Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the .NET 3.5 Enhancement features including: ASP.NET MVC, ASP.NET Dynamic Data, ASP.NET AJAX History, ASP.NET Silverlight controls, ADO.NET Data Services and ADO.NET Entity Framework.

clicky

c# 3.0 - anonymous types

Anonymous types is another new feaure to c# 3.0, one that is central to LINQ.  Combining the var keyword wiht the new object initialization syntax leads to:

var address = new { Street = "somestreet", Number = 45, City = "Gent", ZipCode = "9000" };
Console.WriteLine(address.City);

If you've been paying attention, you probably get that the compiler is doing some magic behind the screens..

Reflector gives us:

3. anonymous types - reflector 1

So, at first view, no cigar, however digging a little further reveals a (generated) namespaceless internal sealed class:

3. anonymous types - reflector 2

Of special note here is the Equals & GetHashCode methods:
As per the msdn documentation, equality depends on the values of the properties of the generated class.
Multiple instances of the same anonymous class can reuse the same generated type, as long as the properties have the same name and are specified in the same order 
(a limitation coming from the DebuggerDisplay attribute).
 
 
 

c# 3.0 - var keyword limitations

In follow up to my previous post on the var keyword, I would like to point out some (obvious) limitations of the var keyword.

- only local variables
  the var keyword can not be used to define return values, parameters or class level fields (privates, protected and so on).
properties are automatically excluded as they are actually just syntax sugar over methods and class level fields (get_Property and set_Property).

- obligatory instantion
   when defining a 'var', it must always be assigned an initial value (so the compiler can find it's type), which can't be null.

var example = null; // -> doesn't compile

   However, after primary initialization the var can be set to null

var example = new MyClass();

example = null;

c# 3.0 - Type inference

c# 3.0 provides us with, among other things, the new var keyword.  While spelling-wise this is equal to the headache inducing var  keyword of vb6, the reality is blessfully different.

The new var keyword allows us to do type inference, which just means that you don't have to explicitly define the variables type anymore.  However, once the variabele has a type assigned, the type can no longer change..

Consider the following code:

        //type inference
        // var gets type of it's first value
        var i = 5;
        i += 1;

// this will not compile
// i = "test";

        var s = "some string";
       Console.WriteLine(s);
        s = "some other string";

From the moment that the variables i or s have been assigned a value, the type of i or s can no longer change.

On top of that, visual studio gives you full support for type inference! The intellisense you get for the i and s variables is respectively that for int and string..

But what you see isn't always what you get...
Below is a screenshot from lutz reflector that shows the compiled code...

3. anonymous types - var keyword. - reflectorjpg

As the compiler can infere the variable's type, it generates type safe code, keeping to the strong typed nature of .net (which is a good thing :)) !

C# 3.0 - Collection Initialization

In addtion to the anonymous constructors, c# 3.0 provides some more capacities for collection classes.

Given the Person class used in the previous example we can now construct a collection class by passing in member of the collection at creation time (like creation of arrays in previous version of the framework).

List<Person> list = new List<Person>() {
    new Person() {    Id = 1,Name = "john doe",BirthDay = new  DateTime(1981, 7, 9),Phone = new Phone() {Prefix="09",    Number="232324"}},
    new Person() {    Id = 2,Name = "jane doe",BirthDay = new DateTime(1981, 4, 5),Phone = new Phone() {Prefix="09",    Number="232323"}}
    };

T 4 Editor

A nifty little tool that allows you to edite t4 templates http://www.t4editor.net

Friday, 11 April 2008

c# 3.0 - anonymous constructors

This is step 2 in my c# 3.0 series, click here for the previous post.

One of the developer productivity gaines that c# 3.0 provides concerns the syntax with which objects are initiailized.

Consider the following c# 2.0 fragment:

public class Person {
        private int id;
        private string name;
        private DateTime birthDay;

        public Person() {}
        public Person(int id, string nme, DateTime bday) {
            this.Id = id;
            this.Name = nme;
            this.BirthDay = bday;
        }

        public int Id {
            get { return id; }
            set { id = value; }
        }
        public string Name {
            get { return name; }
            set { name = value; }
        }
        public DateTime BirthDay {
            get { return birthDay; }
            set { birthDay = value; }
        }
    }

and the subsequent usage:

public class Example{
        public void Test() {
            // no special constructor
            // initialization is done via creation + setting properties line by line

            Person one = new Person();
            one.Id = 1;
            one.Name = "john doe";
            one.BirthDay = new DateTime(1981, 7, 9);

            // custom constructor
            Person two = new Person(2, "jane doe", new DateTime(1981, 4, 5));
        }
    }

So far, the lines of code needed to create a new Person object and populate data to its fields is roughly equal to the number of properties + 1. 

c# 3.0 has the notion of anonymous constructors, which allows for a much more concise syntax.

 

public class Example{
        public void Test() {
            // default syntax still works
            Person one = new Person();
            one.Id = 1;
            one.Name = "john doe";
            one.BirthDay = new DateTime(1981, 7, 9);

            //anonymous constructor
            Person two = new Person() { Id = 2, Name = "jane doe", BirthDay = new DateTime(1981, 4, 5) };
         }
    }
    public class Person {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime BirthDay { get; set; }
    }

But again, this is basically just compiler sugar..
Reflector shows us the following ouput:

2. object initialization - 3.0 -- reflector

Wednesday, 9 April 2008

c# 3.0 : Automatic properties

One of the new features of C# 3.0 is automatic properties.  Basically this eliminates the need to hand code private/protected backing fields for properties

While in .net 2.0 you needed to write the following code:

public class Person {
        private int id;
        private string name;

        public int Id {
            get { return id; }
        }
        public string Name {
            get { return name; }
            set { name = value; }
        }
    }

.net 3.0 allows you to write

public class Person {
        public int Id { get; private set; }
        public string Name { get; set; }
}

 

I guess everyone would agree that the above is a nice concise way to write your classes.
As like most of the changes in c# 3.0  the above is but some compiler sugar (albeit it very useful) as the following comes out of reflector:

1. automatic properties - reflector

c# 3.0 : Preface

Recently we have re-initialized "the Mindshare initiative"  (mindshares for short)@Avanade.  As far as fancy names go, a mindshare is nothing more than one (mostly senior) consultant talking about some new development or new technology in his field.  Seeing as I'm on the brink of seniority, i'm getting ready to do my talk(s) as well.. 

First up is a talk about the new features of c# 3.0, which i dubbed "c# 3.0 - Building the Linq capabilities", later talks could include some stuff about testing, patterns and so on.. time will tell :)

So what you might expect over the coming week is some posts on the above mentionned topic (as absolutely no one  has blogged about this ^^)..

9.04.2008

Another year, another attempt to lift my writing skills to a better level...   so here goes nothing..