Kurt Claeys

DEVITECT.NET

  Home  |   Contact  |   Syndication    |   Login
  91 Posts | 42 Stories | 46 Comments | 14 Trackbacks

News

I'm a .NET architect / developer from Belgium an also trainer in .NET topics.

Kurt CLAEYS

 

View Kurt CLAEYS's profile on LinkedIn


Being ...





 


Working ...


and



Reading ...



Riding ...

Article Categories

Archives

Links

Wednesday, May 14, 2008 #

Today the MCT 2008 Welcome Pack arrived. I'll be certified trainer again, for the 4th year now. Last 12 months i've been busy with WCF and WF and I succeeded in both .NET 3.5 exams on these topics (TS: Microsoft .NET Framework 3.5 – Windows Communication Foundation and TS: Microsoft .NET Framework 3.5 – Windows Workflow Foundation). Looking forward to teach the new MOC's.

At the end of the month I'm off to TechEd 08 Orlando as Technical Learning Guide. Technical Learning Guide is a volunteer role as MCT to assist at TechEd. I'll be helping in the Hands-on-Labs. Beside this I will be presenting there the Instructor Led Lab "Workflow Services using the Windows Communication Foundation" (yeah, a training with both names of these great technologies in the title, that's my game) at TechEd. Hope to see someone from Belgium there.


Friday, May 02, 2008 #

WCF uses by default the DataContractSerializer found in System.Runtime.Serialization namespace to serialize an object to XML and back to an object. This is needed to transfer the data in the object through the communication channel as part of the SOAP packet.

The DataContractSerializer supports version tolerance which can be very helpful when versions of WCF Clients are not aligned with the versions of their needed WCF Services. It’s not always possible to upgrade all the clients at once when you deploy a new version of the service. Or maybe an already upgraded client must be able to talk to a previous version of the service and expect data back from it (roundtripping).

You can also use this DataContractSerializer yourself without needing WCF as the infrastructure around it. Based on this idea I started to do some research on how this versioning tolerance works and how it can be implemented.

First I created two generic methods which will do the serialization and deserialization. Very usefull methods I include as helperclasses in every WCF project I do.

* SerializeToString takes an object from a generic type as input and returns the XML containing the data as a string.

static public string SerializeToString(T o)
{
    DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T));

    StringWriter stringWriter = new StringWriter();

    XmlWriter xmlWriter = XmlWriter.Create(stringWriter);

    dataContractSerializer.WriteObject(xmlWriter, o);
    xmlWriter.Close();

    return (stringWriter.ToString());
}

* DeserializeFromString takes the XML string with the serialized data en creates an object out of this data.

static public T DeserializeFromString(string Xml)
{
    DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T));

    StringReader stringReader = new StringReader(Xml);
    XmlReader xmlReader = XmlReader.Create(stringReader);

    T obj = (T)dataContractSerializer.ReadObject(xmlReader);

    return obj;
}

Now ... Let’s consider some scenarios where we need version tolerance.

1. A second version of a class adds another field to it. When the object is serialized from XML created by the first version of the class, like in the case of the client being an older version compared to the service, we want to have a default injected in the missing field.

I’m using a very simple class called PersonClassV1 here.

[DataContract(Name = "Person", Namespace = "PersonNamespace")]
public class PersonClassV1 
{
    [DataMember]
    public string Name;
}

Version 2 adds a country field and also has a method which is attributed with the OnDeserializing attribute. This method will be executed when the DataContractSerializer deserializes the given XML. So it’s easy to check if the country field is not present and give it a default. The operation receiving this object would not see the difference as the country field is given this value before the data enters the operation.

[DataContract(Name = "Person", Namespace = "PersonNamespace")]
public class PersonClassV2 
{
    [DataMember]
    public string Name;

    [DataMember]
    public System.String Country;

    [OnDeserializing()]
    internal void OnDeserializing(StreamingContext context)
    {
        if (Country == null)
        {
            Country = "BE";
        }
    }
}

Notice also that both classes have been given the same name and namespace to simulate how you would work when updating a single datacontract of existing services.

In this drawing the arrow represent the serialization and deserialization.

image

The code for testing this :

PersonClassV1 p1;
p1 = new PersonClassV1();
p1.Name = "Kurt";         

string asXMLv1;
asXMLv1 = GenericDataContractSerializer<PersonClassV1>.SerializeToString(p1);
textBox1.Text = asXMLv1;

PersonClassV2 p2;
p2 = GenericDataContractSerializer<PersonClassV2>.DeserializeFromString(asXMLv1);
//Deserialize the XML from version 1 to an object if version 2
MessageBox.Show(p2.Name + " " + p2.Country);

This shows my name and the countrycode BE which is the given default in the messagebox.

As you can see there is no breaking change in the datacontracts here. Older clients can still send their data to services expecting a newer version. The new version of the datacontract on the service is responsible for defining the defaults.

 

2. A second version of the datacontract is on the client, but the service still uses the first version. The service gets some data in the serialized stream that it doesn’t know and cannot use. Of course the service does not know what it does not know so there’s no logic to use this extra field. WCF also supports version tolerance here, no breaking change. Not really a problem.

But what about roundtrips ? Suppose the operation returns this class again. When returning this class to the client the DataContractSerializer is used to serialize the class to XML. But as it doesn’t know the countryfield this field will be lost and be empty at the client altough the class at the client knows the field.

How can we work this out so that this extra field is not lost during this roundtripping ? The solution to this is to implement the IExtensibleDataObject interface. By implementing this interface a field called ExtensionData which is of type System.Runtime.Serialization.ExtensionDataObject is needed. This field is acting as a bag for the extra XML that is present in the data. This data becomes part of the datacontract although it not there to be used because the lower version of the service will not have logic for the additional data given by the second version of the dataContract. This ExtensionData object is there for roundtripping. When deserializing/serializing this class against the datactontract that has this extra field, the field is filled up with the data from the extensiondata field. The extensiondata field simply holds the XML data (at the service) that it cannot deserialize so it's there again when the data is serialized again at the client.

Code :

[DataContract(Name = "Person", Namespace = "PersonNamespace")]
public class PersonClassV1 : IExtensibleDataObject
{
    [DataMember]
    public string Name;

    #region IExtensibleDataObject Members

    private ExtensionDataObject extensionData;

    public ExtensionDataObject ExtensionData
    {
        get
        {
            return extensionData;
        }
        set
        {
            extensionData = value;
        }
    }

    #endregion
}

 

In this schema you see the serialization from version 2, deserializing this XML into version 1, serializing this again to XML and deserializing this XML again to an object of version 2.

image

Code to test this scenario :

PersonClassV2 p2;
p2 = new PersonClassV2();
p2.Name = "Kurt";       
p2.Country = "US";

string asXMLv2;
asXMLv2 = GenericDataContractSerializer<PersonClassV2>.SerializeToString(p2);

PersonClassV1 p1;
p1 = GenericDataContractSerializer<PersonClassV1>.DeserializeFromString(asXMLv2);

string asXMLv1;
asXMLv1 = GenericDataContractSerializer<PersonClassV1>.SerializeToString(p1);

PersonClassV2 p2bis;
p2bis = GenericDataContractSerializer<PersonClassV2>.DeserializeFromString(asXMLv1);

MessageBox.Show(p2bis.Country);

This shows me "US", the value of the country field given to the first instantiation of version 2.

Conclusion : Version 1 does not know the country field but can remember it in the extensionData field to spit it out when serialized so it's there when deserialized into the second version again.

You could say that it's a good practice in WCF development to always implement IExtensibleDataObject on your datacontracts.


Wednesday, April 23, 2008 #

A great tool every WCF developer could benefit from is SvcTraceViewer.exe. More info here. This tool is an UI to interprete the logfiles WCF can produce and show them in a nice graphical way. It even supports correlation of the activities in the client logfiles with the activities in the service logfile. So you can see when the messages are transported from client to server.

But this tool is kind of hidden gem. It doesn't come with Visual Studio and not with the Visual Studio extensions for WCF. You can not download it anywhere as a standalone executable.

No, the only way (as far that I know of) to have it, is to install the .NET SDK. The latest version of this SDK is 6.1 and is called 'Windows SDK for Windows Server 2008 and .NET Framework 3.5'.

This is a huge install. First you have to download a 1,29 GB .ISO on
http://www.microsoft.com/downloads/details.aspx?FamilyID=e6e1c3df-a74f-4207-8586-711ebe331cdc&DisplayLang=en. After burning it to DVD or mounting it with a ISO mounting tool (like http://www.slysoft.com/en/virtual-clonedrive.html) you can start the setup. Uncheck all the unneeded parts in the install options. To have SvcTraceViewer.exe you only need to select Developer Tools \ .NET Development Tools.

This setup will create the SDK directory which is C:\Program Files\Microsoft SDKs\Windows\v6.1\Bin

SvcTraceViewer.exe is in this directory.

Here is some configuration code to setup you WCF host (and client) to produce the logfiles. I marked the place to configure the path to the logfiles in red.


<system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Verbose,ActivityTracing"
      propagateActivity="true">
      <listeners>
        <add type="System.Diagnostics.DefaultTraceListener" name="Default">
          <filter type="" />
        </add>
        <add name="ServiceModelTraceListener">
          <filter type="" />
        </add>
      </listeners>
    </source>
    <source name="System.ServiceModel.MessageLogging" switchValue="Verbose,ActivityTracing">
      <listeners>
        <add type="System.Diagnostics.DefaultTraceListener" name="Default">
          <filter type="" />
        </add>
        <add name="ServiceModelMessageLoggingListener">
          <filter type="" />
        </add>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add initializeData="C:\Temp\Logs\App_tracelog.svclog"
      type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
      <filter type="" />
    </add>
    <add initializeData="C:\Temp\Logs\App_messages.svclog"
      type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
      name="ServiceModelMessageLoggingListener" traceOutputOptions="Timestamp">
      <filter type="" />
    </add>
  </sharedListeners>
  <trace autoflush="true" />
</system.diagnostics>


Tuesday, April 22, 2008 #

The first thing developers starting to implement Windows Communication Foundation (WCF) should know is the difference between the BasicHttpBinding and the WSHttpBinding.

This is very important as the BasicHttpBinding has some major drawbacks compared to the WSHttpBinding. From the functional view it makes no difference, it's just a client invoking an operation on a service, but there is a world of difference concerning the low level exchange of SOAP packets to achieve this.

BasicHttpBinding is there only to support the old .ASMX style of working (based on WS-BasicProfile 1.1) and aimed for clients which do not have .NET 3.0 installed. As lots of Windows 2000, which cannot run .NET 3.0, are still out there this is the only way to work with WCF. So the BasicHttpBinding it's there mainly for compatibility reasons.

But you have to be familiar with the idea that this basic profile binding is out-of-date and that the protocol does not have enough quality on board to support the requirements of enterprise oriented services, which can have a high SLA.

ASMX does not support secure messaging (I mean by default, without the WS enhancements). When a client calls an operation on a service, all data in the payload is send as a plain XML, human readable, SOAP packet. Scary? Isn’t? It also does not support reliability and ordered delivery. When a call is lost somewhere, the client is not informed and just waits for a timeout and can not know for sure if the call has arrived at the server and if the logic behind it got executed. Also lacking in the basic profile is ordered delivery. This means when a client fires multiple calls to the service it's not guaranteed that they arrive in the same order. Maybe somewhere a router could drop a packet allowing the second call to arrive earlier than the retransmission of the first. This can lead to disasters, which cannot be allowed in enterprise solutions.

In a sentence: do not use basicHttpBinding binding.

The WSHttpBinding fully supports these requirements on security, reliability and ordered delivery. Some of them as default, others have to be configured. But remember this tuning does not influence the functional development; it's all done under the covers!

So there is no excuse to not use the WSHttpBinding.

WSHttpBinding uses (as the name implies) the WS-* protocols. This results in having some additional handshake messaging and other ping-pong exercises (you got it, I got it, you got it, I got it ... as Juval Lowy would say this) to accomplish this. This means that not only SOAP requests are sent for the operation calls but also to have the client and service agree on some context and to inform each other on the success of the calls.

To fully understand when these extra messages are send and what they are carrying, we can have a closer look at the SOAP messages by using a tool like HTTP Analyzer. This great tool allows you to capture the HTTP traffic and dive into the SOAP packets on the wire.

You can download a demo version of HTTP Analyzer at http://www.ieinspector.com/httpanalyzer/index.html

To experiment on these issues I created an application, which has some scenarios to demonstrate the differences on these bindings. You can download this VS2005 solution here.

I created 3 proxy-service scenarios, all of them exposing the same ServiceOperation and using the same really simple implementation.

[ServiceContract]
interface ITestServiceContract
{
    [OperationContract]
    int DoSomethingInTheService(int aNumber, string aString);

    [OperationContract]
    string DoAnotherThingInTheService(int aNumber, string aString);
}

class TheService : ITestServiceContract
{
    public int DoSomethingInTheService(int aNumber, string aString)
    {
        return aNumber * 10;
    }

    public string DoAnotherThingInTheService(int aNumber, string aString)
    {
        return string.Format("I got {0}", aString);
    }
} 

1. Using BasicHttpBinding (the ASMX style)

Code to start the service (I’m not using any config here, the service is running self hosted in a executable and configuration of binding and endpoint is done programmatically).


* The ServiceHost

ServiceHostBasic = new ServiceHost(typeof(TheService));
BasicHttpBinding binding;
binding = new BasicHttpBinding();
ServiceHostBasic.AddServiceEndpoint(typeof(ITestServiceContract), binding, "http://localhost:9000/ServiceHostBasic");

* The client creates a proxy

EndpointAddress endpointAddress;
endpointAddress = new EndpointAddress(new Uri("http://localhost:9000/ServiceHostBasic"));
BasicHttpBinding binding;
binding = new BasicHttpBinding();

ProxyBasic = new TheProxy(binding,endpointAddress);

* The client calls the operations

int a;
a = ProxyBasic.DoSomethingInTheService(100, "test");
string s;
s = ProxyBasic.DoAnotherThingInTheService(100, "test");

* The client closes the proxy.

ProxyBasic.Close();

Lets examine this scenario in detail. Doing all of this results in 2 messages traveling over the wire. One for the first call (DoSomethingInTheService) another for the second one (DoAnotherThingInTheService).

ss1

Both messages transport the call and the needed data to the service.

Content of the request for the second message (as an example, this is comparable to the first message) :

ss2

Content of the response for the second message:

ss3

Hmm, no security, not encrypted. The client cannot know whether the call arrived at the service, as this is a kind of fire and forget situation. No acknowledgement of the arrival of the call back to the client.


2. Using default WSHttpBinding.

* The ServiceHost
ServiceHostWS = new ServiceHost(typeof(TheService));
WSHttpBinding binding;
binding = new WSHttpBinding();
ServiceHostWS.AddServiceEndpoint(typeof(ITestServiceContract), binding, "http://localhost:9000/ServiceHostWS");

ServiceHostWS.Open();

* The client creates a proxy

EndpointAddress endpointAddress;
endpointAddress = new EndpointAddress(new Uri("http://localhost:9000/ServiceHostWS"));
WSHttpBinding binding;
binding = new WSHttpBinding();

ProxyWS = new TheProxy(binding, endpointAddress);

The rest of the code is the same. What has gone over the wire now? This results in 6 messages and their answers.

ss4

Message 1,2 and 3 is a handshake sequence to establish the security context. This handshake is using the Web Service Secure Conversation Languages build on the WS-Security and WS-Trust protocols.

In this part of a message 1 you can see the client asks for a security token.

 ss5b

The answer for this is a RequestSecurityTokenResponse.

ss6

The 2 following SOAP messages (message 2 en 3) complete this handshake.

Message 4 and 5 are the operation calls, but the data is now encrypted in a way the service infrastructure (=WCF) can decrypt this before sending it in the operation.

 cypherdata

Message 6 is again related to the securitycontext. But important to notice that message 6 is sent when closing the proxy. So the service can release the securitycontext.

As said, this behavior comes for free by using WCF, the developer does not have to know how this is done. Compared the ASMX this is a huge step forward. It would be hard to develop this yourself without WCF and if you would succeed in this is, it would be influencing the functional code.

This is the default behavior of the WSHttpBinding. But what about the reliability and ordered delivery?

3. Using default WSHttpBinding with the reliableSessionEnabled flag on.

When instantiating the WSHttpBinding you can set the reliableSessionEnabled flag to true. This instructs the WCF client to have the messages sent in a reliable session. This means that the client gets informed when the message arrives so there is no doubt whether the serviceoperation has done it’s job.

ss8

* The ServiceHost

ServiceHostWSReliable = new ServiceHost(typeof(TheService));
WSHttpBinding binding;
binding = new WSHttpBinding(SecurityMode.Message, true);
ServiceHostWSReliable.AddServiceEndpoint(typeof(ITestServiceContract), binding, "http://localhost:9000/ServiceHostWSReliable");

ServiceHostWSReliable.Open();

* The client creates a proxy

EndpointAddress endpointAddress;
endpointAddress = new EndpointAddress(new Uri("http://localhost:9000/ServiceHostWSReliable"));
WSHttpBinding binding;
binding = new WSHttpBinding(SecurityMode.Message, true);

ProxyWSReliabable = new TheProxy(binding, endpointAddress);

The only difference is this code compared to scenario 2 is in providing the parameters to the constructor of the binding. This at the client side and the service side.

This results in 9 messages and their answers, of which only 2 messages are the actual calls to the operations.

ss9

Message 1 to 3: Again this is the security context handshake like in the previous scenario.

Message 4: This message asks the service to create the sequence, so it knows it can expect multiple messages that are part of the same sequence.

createsequence

And the answer on this:

createsequenceresponse

Message 5 and 6 are again the encrypted calls to the operations. But notice that each message is carrying a sequence number.

The first operation:

ss10

The second operation:

ss11

Message 7 is the client asking to the service to acknowledge the 2 messages it just has send it.

This message (and the subsequent messages) is send when the proxy is closed. So remember its necessary to close your proxy always!

ss12

On which the service reacts by sending its acknowledgement:

ss13

Message 8 is again the client telling to the service it got its confirmation so both part can be sure the messages are delivered. This is what reliability is about.

Message 9 is as in the previous scenario to release the securitycontext at the service.


Summary (considering 2 calls to an ServiceOperation)

1. BasicHttpBinding (2 messages)

sum1

2. Default WSHttpBinding (6 messages)

sum2

3. Default WSHttpBinding with Reliable Session Enabled (9 messages)

sum3

Some remark: Although you can set the securityMode when creating the BasicHttpBinding for the service, you cannot use this without having either SSL on the IIS to implement for transort level security or implement the WS-enhancement stack on the client yourself. So out-of-the box ASMX services have this basic non-secure behavior. With WCF this comes all for free with the WSHttpBinding.

 

cu (happy coding)


Saturday, April 19, 2008 #

A litle late, busy month, been on holiday to Lissabon with wife and kids and attended the Architect's Master Class (by Juval Lowy). 2 great experiences !

The links that hit my eye the last month are :

About ASP.NET MVC, great screencasts by Scott Hanselman
http://www.hanselman.com/blog/ASPNET35ExtensionsPlusMVCHowToScreencast.aspx
http://www.asp.net/learn/3.5-extensions-videos/default.aspx#mvc

About Workflow Services in .NET 3.5 on Channel9
http://channel9.msdn.com/Showpost.aspx?postid=398586
http://channel9.msdn.com/Showpost.aspx?postid=362199
http://channel9.msdn.com/ShowPost.aspx?postid=338720

Or by Mike Taulty (Building WCF Services Using Workflow Foundation)
http://www.microsoft.com/uk/msdn/screencasts/screencast/285/WF-V35-Building-WCF-Services-Using-Workflow-Foundation.aspx

More on Workflow Services : Building Workflow Services (WF+WCF) with Visual Studio 2008 by Marc Schweigert
http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?culture=en-US&EventID=1032366133&CountryCode=US

Free books on WCF
http://codeidol.com/csharp/wcf/
http://books.google.be/books?id=-AUyj6S7etwC

WCF Community Site
http://wcfcommunity.com

Miscellaneous links (from my favorites collected during research and course preparation work), worth to have a look at.
This lists somehow reflects what I have been doing past months.
http://www.infoq.com/presentations/ddd-dsl-evans
http://www.objectmentor.com/resources/articles/ocp.pdf
http://www.soapatterns.org/section53.asp
http://www.langnetsymposium.com/talks/1-01%20-%20CSharp3%20-%20Anders%20Hejlsberg.html
http://www.west-wind.com/weblog/posts/246222.aspx
http://forums.microsoft.com/MSDN/showpost.aspx?postid=1935713&siteid=1
http://msdn2.microsoft.com/en-us/magazine/cc163647.aspx
http://www.designpatternsfor.net

A very good blog to follow up close :
http://www.clemensreijnen.nl

A list of great screencasts at :
http://devkeydet.spaces.live.com/lists/cns!1F72DA7294089597!583/


Wednesday, February 27, 2008 #

26 developers from 'West-Vlaanderen' interested in LINQ and the Entity Framework attended (and liked) my IT Club session yesterday. This session will be repeated for Ordina and some local .NET usergroups. I this session i give an introduction to LINQ and the needed C# languages enhancements, focus on OR-mapping and contains demos on Linq to SQL and the Entity Framework.

Interested in attending, please mail me or reply to this post.

Or you can download the slides here.


Monday, February 25, 2008 #

I'll try to post every month some interesting links (to blogsposts, articles, white books and other content) I noticed on the net in the last month during professional daily work or from personal interests (what's the difference anyway). Not always brand new resources but the ones I found of most value and quality. Most links will be in the area of OO design patterns, software architecture, EAI and agile development and can be seen as needed reading material (if time permits) for a role as solution architect. Some of them are quick reads/views, others are huge and in-depth material.

This month :

Implementing Value Objects (by Sander Hoogendoorn) in .NET Magazine #19 (dutch article)

Scrum - Started without Getting Burned Part 1 (by Giovanni Asproni, webcast on Parleys.com)

Scrum - Started without Getting Burned Part 2 (by Giovanni Asproni, webcast on Parleys.com)

Domain Driven Design MiniBook (InfoQ)

Inversion of Control Containers and the Dependency Injection pattern (Martin Fowler)

The Blog of Bart De Smet.

Continuous Integration: From Theory to Practice 2nd Edition (Carel Lotz)

Interactive Application Architecture Patterns (Derek Greer, Ctrl-Shift-B)

Microsoft BizTalk Server Operations Guide (Microsoft Download Center)

Interview Jezz Santos About Software Factories

Patterns and Practices Guidance Unity Dependency Injection IoC Screencast (David Hayden) 

How Do I: Create and Customize My Domain Specific Language? (MSDN)

How Do I: Use Advanced Customization (DSL)? (MSDN)

Simplifying SOA (Zapthink)

MSDN Belgium Chopsticks

NDepend Metrics poster (pdf, Corillian Corporation)

Project Astoria (Pablo Castro in The Architecture Journal)

Happy reading/viewing ....


Monday, February 18, 2008 #

The Unity Application Block Feb 2008 CTP (from now on called Unity) is released on www.codeplex.com/unity. It's a lightweight dependency injection container with support for constructor, property and method call injection.

To get people started with this, I created a small example. Actually I ported my Dependency Injection with Spring.NET example from some posts ago to this release of Unity.

This sample shows how a class can get an reference to another class through its constructor.

Hit this link to download this example (VS2008!)

Let assume that ClassA needs a reference to ClassB. But ... not always to ClassB. Sometimes, for testing purposes, you would like to have another Class (called ClassB2 in this example) being giving to the constructor. Yeah, once again .... the loose coupling pattern, very usefull from the point-of-view of unittests.

So ClassA Looks like this :

 

public class ClassA { IClassB _refToB; public ClassA(IClassB b) { Console.WriteLine("Class A constructed!"); _refToB = b; } public void Test() { _refToB.DoSomething(); } }

 

Of course ClassB2 would need to implement the same interface as ClassB does otherwise the compiler is not satisfied. Note that the contructor for ClassA gets a reference to a class which implements this interface called IClassB

IClassB (the Interface for ClassB and ClassB2) looks like this :

public interface IClassB { void DoSomething(); }

Concrete implementation of ClassB :

 

class ClassB : IClassB { public ClassB() { Console.WriteLine("Class B constructed!"); } public void DoSomething() { Console.WriteLine("Class B did something"); } }

 

Concrete implementation of ClassB2 :

 

class ClassB2 : IClassB { public ClassB2() { Console.WriteLine("Class B2 constructed!"); } public void DoSomething() { Console.WriteLine("Class B2 did something"); } }

 

Ok, these are normal classes, nothing special. If we want to use them, we instantiate them with the new operator. First instantiate ClassB (or ClassB2) than instantiate ClassA giving it the freshly created ClassB (or ClassB2) in the constructor. Not ! This is too tighly coupled !

With a depency injector container (like Unity) we do not explicitly program the instantiations with the new operator. The container will do this for us. Al we have to do is : ask the container which object we want. If we ask for ClassA, the container will see that the constructor must have an instantiation of a class that implements IClassB and such a class will be instantiated for us and been given to this constructor.

Of course the container must know what concrete class (ClassB or ClassB2) it must instantiate. This is done by first mapping the Interface type to the concrete type, either by code or by configuration.

By Code :

IUnityContainer container = new UnityContainer(); container.Register(typeof(IClassB), typeof(ClassB2));

This code results in the creating of the container. Thereafter the IClassB interface type is mapped to the concrete ClassB2. From now on, if we want the have ClassA instantiated we just ask the container to get a reference by specifying the type in the generic Get method of the container.

ClassA a1; a1 = container.Get<ClassA>(); a1.Test();

So this method will lookup (through reflection) if other instantiations are needed (= dependent) and detects that it needs a class of type IClassB in the constructor. Because we already mapped ClassB2 to this interface the container is able to know that he needs to instantiate ClassB2 and thereafter needs to instantiate ClassA with the reference to ClassB2.

Result :

Class B2 constructed!
Class A constructed!
Class B2 did something

By Configuration :

In the previous way the choice of wich implementation of the interface to use is still hardcoded in the program. To be really loose coupled we need to have this decision written down in the configuration. Unity also supports this.

 

<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <containers> <container> <types> <type type="TestUnity.IClassB,TestUnity" mapTo="TestUnity.ClassB2,TestUnity" /> </types> </container> </containers> </unity> </configuration>

 

In this configuration the mapping between IClassB an ClassB2 (or ClassB) is clearly specified. To read this configuration we need to use the ConfigurationManager like this :

 

IUnityContainer container = new UnityContainer(); UnityConfigurationSection section; section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Containers.Default.GetConfigCommand().Configure(container);

 

The rest of the code remains the same.

Bottom line : The container shields the developer away from that awfull new operater and gives him/her the needed objects based on a simple configuration.

But ... there's more (lots of ...)

For example : You can even configure the container to use singletons when instantiating the classes by setting the lifetime attribute. By default the Unity container will not use singletons unless you specify this. Like this :

 

<type type="TestUnity.ClassA,TestUnity" mapTo="TestUnity.ClassA,TestUnity" lifetime="Singleton" />

 

Result : when calling this code ....

 

ClassA a1; a1 = container.Get<ClassA>(); a1.Test(); ClassA a2; a2 = container.Get<ClassA>(); a2.Test();

 

... the constructor of ClassA and the constructor of ClassB2 (or ClassB) will only be executed once and a1 and a2 will point to the same instantiation without the need to write our own singleton logic.

 

One advice about the CTP : clearly the documantation is not in syc with this release. Please follow the discussions about this on http://www.codeplex.com/unity/Thread/List.aspx


Saturday, February 16, 2008 #

Microsoft has announced the next generation of the Technology Specialist exams. There are 6 MCTS exams to choose from, instead of 3 for the current certification track.  The main difference is that the new exams are more 3.5 technology (WCF,WF,WPF,ADO,ASP) oriented instead of to the type of application (web,win,distributed) as in the 2.0 track.


The exams are ...

70-502 TS: Microsoft .NET Framework 3.5 - Windows Presentation Foundation
Launching on 25 March 2008

70-503 TS: Microsoft .NET Framework 3.5 - Windows Communication Foundation
Launching on 27 March 2008

70-504 TS: Microsoft .NET Framework 3.5 – Windows Workflow Foundation
Launching on 28 March 2008

70-505  TS: Microsoft .NET Framework 3.5 - Windows Forms Applications
No launchdate know yet (No Preparation Guide available yet)

70-561  TS: Microsoft .NET Framework 3.5 - ADO.NET Applications
Launching on 12 May 2008 (No Preparation Guide available yet)

70-562  TS: Microsoft .NET Framework 3.5 - ASP.NET Applications
Launching on 21 May 2008 (No Preparation Guide available yet)


Worth noticing is :

- The 70-536 exam is still valid, but will be renamed to TS: Microsoft .NET Framework, Development Foundation.  They will drop the 2.0 versionnumber in the title.
- There is no upgrade path from the MCAD/MCSD certifications, the MCAD/MCSD credentials will not expire, but the exams will retire in the future.


Want to know how many already have been certified in the existing track ? The numbers of MCP's worlwide have been published (i mean recently updated). Check out : http://www.microsoft.com/learning/mcp/certified.mspx


Besides the 3.5 Technology Specialist exams there are also a number of new exams in various areas.

70-541 TS: Microsoft Windows SharePoint Services 3.0 - Application Development
70-542 TS: Microsoft Office SharePoint Server 2007 – Application Development
70-543 TS: Visual Studio 2005 Tools for the Microsoft Office System
70-544 TS: Microsoft Virtual Earth 6.0, Application Development
70-545 TS: Microsoft Office Visio 2007, Application Development
70-571 TS: Microsoft Windows Embedded CE 6.0 Application Development


BTW : the 'Get a second chance to pass your Microsoft Certification exam' offer has been extended through June 30, 2008!


Release plans for Courseware,E-learning and Microsoft Press books are :
- Starting from March some E-learning will be available
- In April and May courseware for all exams except 70-505 will be available
- Schedule for Self Paced Training Kits : July 2008 : 502, 503, 504, Sep 2008 : 561 and 562


Happy Studying.


Thursday, February 14, 2008 #

As my interest grows to learn more about the J2EE development platform (I strongly believe that knowledge of both platforms is needed to work in an IT architect role) I started looking at Spring.Net. Spring is the most widely used application framework in the Java world. Spring is somehow comparable to what the Microsoft Enterprise Library is offering. (Hmm, not exactly ...)

Spring (and also Spring.net) supports the Inversion of Control (IoC) principle in a really easy and efficient way. Not as complex as ObjectBuilder in Enterprise Library.

I came up with a little tutorial on Loose Coupling and Dependency Injection with Spring.NET. Design patterns like these are hard to understand without a good example. In this post I will guide you in this area by coding a simple scenario.

Let's consider a program which instantiates an object of ClassA (could be a windows form). That object needs a reference to another object that performs some logic (could be a domain object or a proxy to a WCF service). Let's call this ClassB.  ClassA has a property which refers to ClassB. When the progam asks ClassA to do something, ClassA will call a method on ClassB.

Loose Coupling ? Loose Coupling comes in very handy for testing purposes : to test the behavior of ClassA we want to change ClassB to another Class (let's call it ClassB2) which has the same method but doesn't execute the logic to really call to a database backend but returns some hardcoded values. In a unit test we could assert the outcoming of the method in ClassA based on those harcoded values.

 

I will give you three different approaches for this scenario : 

 

1. Not Loose coupled example, no dependency injection, no spring.net

class ClassA { public ClassB refToB { get; set; } public void DoSomething() { string answerFromDatabase; answerFromDatabase = refToB.GetSomehingFromADatabase(); Console.WriteLine(answerFromDatabase); } }

There's is no way to use another version of ClassB (ClassB2) without changing ClassA and recompiling it.  ClassA is really dependent on ClassB.

So this code snippet will not compile.

a = new ClassA(); a.refToB = new ClassB(); a.DoSomething(); a.refToB = new ClassB2(); //<- does not compile of course. a.DoSomething();

A solution for this is working with interfaces.

 

2. Loose Coupled with an Interface, no dependency injection, no spring.net

An Interface called IClassB is added.

public interface IClassB { String GetSomethingFromADatabase(); }

Now both ClassB and ClassB2 implement this interface. This interface holds the definition of the methods that ClassB (and ClassB2) should implement. ClassA now has a property which type is this Interface.

class ClassA { public IClassB refToB { get; set; } public void DoSomething() { string answerFromDatabase; answerFromDatabase = refToB.GetSomethingFromADatabase(); Console.WriteLine(answerFromDatabase); } }

This allows the calling code to decide which version of ClassB is given to ClassA. Both code snippets below are correct.

a = new ClassA(); a.refToB = new ClassB(); a.DoSomething(); a.refToB = new ClassB2(); a.DoSomething();

OK, more or less loose coupled, ... but again we need to recompile the application to switch from the real ClassB to the hardcoded ClassB2.

 

3. With Dependeny Injection using Spring.NET

Instead of using a property we add a constructor to ClassA which takes a reference to the interface IClassB as paramater. This construcor will hold this reference in a private field inside the class.  The type of this private field is also the interface.

class ClassA { private IClassB refToB; public ClassA(IClassB b) { refToB = b; } public