Designing WCF services

Hi all,

I have been working for a while with WCF and still want to learn more about how to design better WCF services. I found a great post i would like to share with you: patterns for flexible wcf services. I hope you like the post as much as i do.

Regards,

Dennis

WCF and IsWrapped MessageContracts

The IsWrapped property on a messagecontract is keeping me busy. When working with WSSF it’s forcing you to set the IsWrapped property to true when you have more than one element in your message contract. This is because this required by the WS-I Basic profile1.1 standard. So you set the property to true and don’t have any idea what this will do to the proxy which is generated for you. In this post i will describe four possible scenarios and there effect on the proxy which is influenced by the choice you make. The possible scenarios are summarized in the table below:

  Request IsWrapped  Response IsWrapped 
Scenario 1 True  False 
Scenario 2  False True 
Scenario 3 False False
Scenario 4 True True

 

Well I desgined a simple service called CaseService. This service implements the ICaseService interface. This interface contains one operation RetrieveCase which accepts a casenumber (string) as input paramter and returns a Case object.

The messagecontract I used are: RetrieveCaseRequest and RetrieveCaseResponse.

Scenario 1

In this scenario I set the property IsWrapped of the RetrieveCaseRequest to true and the IsWrapped property of the RetrieveCaseResponse to false. When I build this service and generate a proxy for this service this will give me the following code (I stripped code which is irrelevant for this post):

public WCFService.Client.Proxy.Case RetrieveCase(WCFService.Client.Proxy.RetrieveCaseRequest RetrieveCaseRequest)
        {
            WCFService.Client.Proxy.RetrieveCaseRequest1 inValue = new WCFService.Client.Proxy.RetrieveCaseRequest1();
            inValue.RetrieveCaseRequest = RetrieveCaseRequest;
            WCFService.Client.Proxy.RetrieveCaseResponse retVal = ((WCFService.Client.Proxy.CaseService)(this)).RetrieveCase(inValue);
            return retVal.Case;
        }

The extra generated messagcontract

[System.ServiceModel.MessageContractAttribute(IsWrapped = false)]
    public partial class RetrieveCaseRequest1
    {

There are two Request MessageContracts generated: RetrieveCaseRequest and RetrieveCaseRequest1. The RetrieveCaseRequest1 is a wrapper for the RetrieveCaseRequest. It looks like that the proxy will balance the request and response to the same IsWrapped setting. They are both send over the line with IsWrapped set to false.

The proxy will send the RetrieveCaseRequest1 (IsWrapped=false) and will receive RetrieveCaseResponse (IsWrapped=false). The RetrieveCaseRequest method in the proxy will accept a request messagecontract as input.

Scenario 2

In this scenario we will switch the IsWrapped settings. For the Request it will be set to false and for the response it will be set to true. Scenario 2 will give us the situation which is vica versa of scenario 1. There is one Request MessageContract and there are two Response MessageContracts: RetrieveCaseResponse and RetrieveCaseResponse1. The RetrieveCaseResponse1 is used as a wrapper contract for the RetrieveCaseResponse. Also notice the input parameter of the method RetrieveCase in the proxy. It’s a CaseNumber (string) and not a messagecontract like in scenario 1. It will wrap it into a messagecontract before sending it to the service.

public WCFService.Client.Proxy5.RetrieveCaseResponse RetrieveCase(string CaseNumber)
        {
            WCFService.Client.Proxy5.RetrieveCaseRequest inValue = new WCFService.Client.Proxy5.RetrieveCaseRequest();
            inValue.CaseNumber = CaseNumber;
            WCFService.Client.Proxy5.RetrieveCaseResponse1 retVal = ((WCFService.Client.Proxy5.CaseService)(this)).RetrieveCase(inValue);
            return retVal.RetrieveCaseResponse;
 }

Scenario 3

In the third scenario i have set both message contracts (request and response) to false. This results in the following proxy method:

public WCFService.Client.Proxy3.Case RetrieveCase(string CaseNumber)
        {
            WCFService.Client.Proxy3.RetrieveCaseRequest inValue = new WCFService.Client.Proxy3.RetrieveCaseRequest();
            inValue.CaseNumber = CaseNumber;
            WCFService.Client.Proxy3.RetrieveCaseResponse retVal = ((WCFService.Client.Proxy3.CaseService)(this)).RetrieveCase(inValue);
            return retVal.Case;
        }
As you can see, it will  accept a casenumber as input and a case object as return parameter. The proxy will wrap a messagecontract around the type before sending it to the service and strips the messagecontract before returning the response to the consumer of the proxy. Remember that you don’t always have the option to set the iswrapped property to false. When your messagecontract has multiple elements it will need the iswrapped property set to true.

Scenario 4

In this scenario I will set for both the Request and Response messages the IsWrapped property to true.

public WCFService.Client.Proxy2.Case RetrieveCase(string CaseNumber)
{
            WCFService.Client.Proxy2.RetrieveCaseRequest inValue = new WCFService.Client.Proxy2.RetrieveCaseRequest();
            inValue.CaseNumber = CaseNumber;
            WCFService.Client.Proxy2.RetrieveCaseResponse retVal = ((WCFService.Client.Proxy2.CaseService)(this)).RetrieveCase(inValue);
            return retVal.Case;
        }

As you can see this scenario contains the same proxy method as scenario 3.

I have experienced three of the four scenarios on projects and i was wondering how is it possible that my proxy is looking different when i am switching the iswrapped properties. I hope that this post will give you some information about the iswrapped property and will give you some ideas when you are running in the same kind of proxies with different faces.

Regards,

Dennis

Programming WCF services

The last few days i’ve been reading the book “Programming WCF Services” by Juval Lowy. I was looking for a book which isn’t a representation of msdn, like training kits. Just a book which describes how to write good quality WCF services. I think that Juval Lowy did a great job with his book. He is sharing his knowledge and experiences through out the whole book. Even though i think this book isn’t for starters of WCF. Juval starts with an introduction about the framework and tells more about the basics like Datacontracts, Messagecontracts, Faults and Operations. Chapters I really liked were Instance management, Transactions and Concurrency Management. These three chapters have a lot do with each other. When you already have experience with WCF and you want to read a book which still can learn you more about programming WCF services, this book is highly recommended.

Regards,

Dennis

Building transactional services with WSSF

When you are familiair with the WebService Software Factory (WSSF) you probably know that this tool uses three kind of models to make developing services much easier:

  • DataContractModel
  • ServiceContractModel
  • HostModel

In this post I would like to focus on the ServiceContractModel. This model generates messagecontracts and a servicecontracts. The servicecontract looks like a normal  interface where signatures of methods are defined. The only difference is that a servicecontract also contains two kind of attributes:

The properties of both attributes can be modified with the designer of WSSF. One drawback of WSSF is that it’s not possbile to add more attributes to the servicecontract. When you want to build a transactional WCF service with WSSF you have to do some coding by yourself. This isn’t a problem, but the combination of writing your own code and generate code with WSSF could become a problem if you not doing it right.

There are a couple of steps you need to take before your service is supporting transactions. For a guide step by step take a look here. In this post I will only talk about how you should decorate your interface and how to do this with WSSF. In your interface you are able to determine which operation could join or start a transaction. Foreach operation who should be available for a transaction you should decorate the operation with a TransactionFlowAttribute.  

Adding this attribute should be done by hand. When you have decorated your interface correctly and followed the steps in the blogpost above, then your ready to go. But what happens when you have checked in your code and your colleague is working on the servicemodel and clicks on the generate button. You don’t get any errors, but you don’t see any transaction enlisted anymore in your Distributed Transaction Coordinator (DTC). One of the steps you need for a transactional service is removed from your code. The servicecontract is regenerated, this means that the old servicecontract with the TransactionFlowAttribute is replace with the new one generated by WSSF.

I could only think of one solution to avoid such an situation. The solution would be adding the TransactionFlowAttribute to the class (the service) who is also implemeting the interface. This isn’t a perfect situation, but it could avoid strange behavior in your transactional service.

Regards,

Dennis

WCF proxy with duplicate classes

Hi,

A year ago I wrote a post about WSSF and shared datacontracts. Well I am still using those lines of code to generate my own proxies for WCF services. A couple of months this was working very well on my new project. Somehow after an unknown change the generation of my datacontracts and proxy wasn’t working anymore. The datacontracts are still generated into a separated file but my proxy also contains my datacontracts which results in ambiguous compilation errors in my client application. After searching and troubleshooting for a couple of hours i found the solution. I made a simple change to my service contract in WSSF. I changed a response MessageContract from IsWrapped=false to IsWrapped=true. Well this is something i do very often so i couldn’t imagine this was the problem. I am used to change the IsWrapped property of my Request MessageContracts. You can set this property to true on the request without setting it to true on the response. This doesn’t have any consequences for the generation of your proxy. When you set the IsWrapped property of your response to true and on the request it’s still false, this will give you duplicate classes in your proxy.

Solution: “If you change the IsWrapped property of the response MessageContract make sure you do the same for the request MessageContract, otherwise you get duplicate classes into your proxy”

See the workitem on codeplex

Regards

Invoking crmservice: CPU and memory peaking

The last few days i’ve been working on a WCF service which is using a few other services as sources. One of the source is the crmservice. Somehow when i was programming against the crmservice everything went smooth when i was testing it in the development server of Visual studio (Cassini). When i deployed the WCF service on a webserver in IIS the service was performing very poor. The CPU and the memory was rising sky high. It took me a while to figure it out, but a colleague of my pointed me to a very good post which was a start for solving my problem. I am not a CRM guru, so this post is maybe for some of you old news but you have to check this post of the CRM team. Down in the comments someone has a step by step description. You can find it here. Hopefuly you don’t have to spent to much time solving this issue.

Regards

No more broken build with gated check-ins

In VSTS 2010 Microsoft has a pretty cool feature called “gated check-in”. This will prevent a check-in if it will break the build. Brian Harry mentioned this on his blog.

Regards

Relations in CRM 4.0

Hi all,

I am working on a project where i am implementing CRM 4.0. One of the demands of our customer is that they want to create relationships between Account entities and they want to store some additional information about this relationship. They want to add a startdate and an enddate attribute to the relationship entity. Well the relationship entity which is delivered out-of-the-box doesn’t give us any options the extend the entity with extra attributes. This means that we have to create our own relationship entity. Well in our situation we want to create N:N relation between the Account entities, which means we have to make the following relations:

Primary entity Relation Secondary entity
Account 1:N CustomRelation
Account 1:N CustomRelation

We have to add this type of relation twice otherwise we can’t make a N:N relation between Accounts. So far so good, what does this mean for our CRM interface. In the left menu you will see a link to Customrelationship Entity twice. This is something you don’t want.

CRM relation

The first link will show us the relationships where the selected Account is the primary entity in the relation and the second link will show us the relationships where the selected account is the secundary entity in the relation. So if we implement it in this way we don’t have an single view of all the relationships from one Account.

My Colleague Ronald Lemmen told me that this should be fixed with building a plugin. The plugin will be responsible for created a relationship the other way around. For example:

Organization A –> Organization B: this relationship is made in CRM.
Organization B –> Organization A: this relationship is made by the plugin.

This solution will result in 2 relationships between the same entities. CRM itself is using the same solution. See below. In the first screenshot we see that Avanade is the selected Account. Avanade is also Party1 in the relationship with Microsoft.

CRM relation

In the screenshot below we see the same relationship but the parties are reversed. Micorsoft is the selected account and Party1 in the relationship.

CRM relation

Now that we create a reversed relationship with our plugin we are able to remove one link in the menu (see first screenshot). This can be done in the screen where you add your relations between entities. I hope that this post will help other developers who are running into the same problem.

Kind Regards!

Test driven development (TDD) in VSTS 2010

The last 2 days I have been testing a little piece of VSTS 2010. Something I liked is the way VSTS 2010 supports TDD. A lot of developers are familiar with TDD, some hate it and some love it. I don’t have a lot of experience with TDD, but I am very interested and tried this way of programming on my last project. Test-First development is something which makes you look different to your own code. I realized that I was focused even more on the signature of the method that I was writing. What are good input parameters and what are my return values.

When you start writing your first Unit test you will run into the annoying thing that every class you instantiate isn’t available yet. Well in VSTS 2010 the class is still not available, but there is a very simple way to make them available without losing the focus on your Unit test. See the screenshot below.

Generate class 

In this screenshot you see that the class which is giving an error because it doesn’t exist has a new option to create the class for me. You have 2 options:

  • Create the class directly in the project where the Unit test resides
  • Create the class in another project of your own choice

I think the second option is the best option, because you don’t want all your classes in the same project with all your test files. When you click on the section option (Generate other…) you will get the following panel.

Enter class information

As you can see in this panel you are able to select the following things:

  • Access modifier (Default, Public, Private, Internal)
  • Type (Class, Struct, Interface, Enum)
  • Project location (The project where you want the class to be created)
  • File name: (The name of the file)

Something what is missing is the opportunity to enter a namespace where the class should belong to. Default the class will belong to the same namespace where the unit test belongs to. Hopefully Microsoft will fix this before the release VSTS 2010. I changed the project location to another project because I don’t want my classes inside my test project. When you create the class in another project VSTS will automatically add a reference to the project where the class will be created.

Solution Explorer

Well the unit test isn’t finished yet. In my Unit test I want to test a method which multiplies the incoming parameter. So I need a method with the following signature:

  • Name: Multiply
  • Input parameter: int
  • Return parameter: int

I write this method down in my Unit test in a way it should be invoked if it exists.

New method

You can stub this method without leaving you Unit test. When VSTS creates a stub for me, it will implement the method with throwing a NotImplementedException. This is fine for me, because it doesn’t matter if the first run of my Unit test will fail. At the end the unit test will look like this.

Unit Test

The class which is generated for me will look like this.

Generated class

As you can see in the screenshot, the Multipy method is created with the right signature and it will throw an exception. The namespace isn’t correct like I already mentioned. The next thing to do is write functional code which will make the unit test pass. So test first development is something which is simple to do in VSTS 2010. When VSTS 2010 is released we are able to write our code in combination with unit tests in two ways:

  • Write our functional code first and generate a Unit test based on the class
  • Write a unit test and generate a class which supports those functionalities you are looking for

When this version of VSTS is released i am happy to do some TDD.

Branching and Merging visual tools in VSTS2010

Microsoft is developing some pretty cool visualization features for branches. Sometimes it’s hard to explain to developers how you want to work with branches. You have a branch for the code base which is running right now on the production server. In case you get some bugs in production which should be fixed quickly, just switch to your production branch and fix the bug. Well when i got a bug in my production branch it’s also in my development branches. I should merge the bugs fix back to my developement branches. You can imaging that knowing which code runs where is pretty hard on a project with multiple branches.

There are whitepapers for branching strategies. When should i make a branch? when must I merge my development branch to the production branch. Which features are available in which branch. With the new visual tools coming in VSTS2010 this is very well organized. You have to check the following screencast on Channel9. Enjoy!

Follow

Get every new post delivered to your Inbox.