Click here to Skip to main content
Click here to Skip to main content

WCF by Example - Introduction

By , 12 Feb 2013
 
Next
Chapter I

Latest modifications 

The last article added to the series is WCF by Example - Chapter XVI - EF 5 & SQL CE - AzureWebSites Deployment, this article was added in Feb 2013 and discusses how to implement a Unit of Work and Repository using Entity Framework Code First within the eDirectory solution. This article also discusses how to deploy the solution on Azure WebSites.

The source code for the articles is located at its own project in Codeplex, latest changes can be found at the trunk branch.

In Dec 2012, RavenDB support was added to the solution.

In Oct 2012, the solution was amended so NHiberante is also configured to work with SQL-CE 4.0; previously it was only working for SQL Server or the Express versions; you may want to check it out to see what it takes to get your application running using SQL-CE and NHibernate. 

In Dec 2010, the server side of the application was deployed to Azure, a ready-to-run client is available on codeplex. The WPF client can invoke methods to a WebRole deployed in Azure. This source code can be found at CodePlex at eDirectory.WPFClient.Azure.zip 

You may want to follow series/code updates at: @enriquealbert/wcfbyexample

Introduction

This article is the first of a series that discusses how to design and develop a WPF client using WCF for communication and NHibernate for persistence purposes. Actually, the solution can be configured to use one of the following persistence implementations: NHibernate, EF, InMemory and RavenDB.

Designing enterprise applications requires a comprehensive set of skills. In small and medium projects allocation of time and resources could be not feasible to the extent that is in larger projects, it is at this time where a source for best practices and patterns can become very beneficial. There are plenty articles, books and other materials covering specific aspects but it is almost impossible to find a single place where all the technologies and patterns are used in conjunction providing a comprehensive discussion of the why and how.

The intention of these articles is to provide an example of how a full enterprise application is developed from the early stages to a full functional stage. The articles build on top of each other where new aspects are covered or/and existing functionality is enhanced as a result of aligning the architect to the business non-functional requirements.

It is assumed in the series that Agile practices are followed so the solution's architect focuses in providing flexible mechanisms for RAD, DDD and TDD methodologies. One key aspect of the architect is the requirement to be able to deploy a full-functional client for business exploration purposes that requires a minimum infrastructure footprint; avoiding databases, deployment to IIS and so on. 

Background 

The architect requirements are as follow: 

  • Rich client using WPF  
  • Client connects to server using WCF services  
  • NHibernate, EF, RabenDB are used for persistence purposes  
  • Client application can be run against in-memory repositories (Exploration Client)
  • Deployment of the exploration client must be kept simple  
  • The application must be easily testable, tests can be run against any of the implemented repositories

Other assumptions:

  • We have full control over the client and server components
  • We are creating the database from scratch, we are not using some legacy database
  • We are deploying the server components using IIS7 and WAS; we will use TCP/IP
  • We have full design control over the PK in the database tables, we will using unique long fields for all our entities in this project

The eDirectory solution

We are going to start using a very simple business scenario in our series, the focus on the series is the architecture not the business domain. We may extend our domain in the future if we find that we want to explore some more complex architect concepts. 

The business domain is based in a simple list of contacts, it is currently so simple that one single entity is only required: Customer. The solution name is eDirectory. 

The source code can be found at codeplex: WCF by Example  

The latest version can be found at the trunk branch, each chapter is located at its own tag branch. You may want to use the browse function within Codeplex to navigate among the branches. 

Architect Overview 

The eDirectory application defines three well differentiated application components: the database, server and client. 

wcfbyexample_introduction/architecture_highlevel.gif

Within the client and server the application is structured into layers, in most cases the layers are stacked one beside each other, continuous layers are provided with decoupled mechanisms so different implementations can be used. Some services are available across multiple layers.

As we earlier mentioned, we have full control of the clients and server. So we will not relay on late service discovery, instead the service contracts are available at both sides of the application. This is also true for the DTOs and some common business validation. As a result, a Common assembly is defined that contains components shared by the server and client applications.  

wcfbyexample_introduction/common_components.gif

In the server side we find the core components, the business domain declares the business entities and their behavior (action methods). Then services are declared that exposes our domain action methods. The services for persistence and serialisation constraints only expose DTOs between the client and server. As a result, the transformation of entities to DTOs needs to be addressed in a comprehensive manner.  

In order to decouple our business domain from the database, the repository components are responsible for the persistence of our entities. We will define a generic interface between these two layers. Four concrete implementations of the repositories are available: in-memory, NHibernate, Entity Framework and RavenDB.

The transaction manager is our "unit of work" implementation. It is responsible for our business transactions and the handling of business messages (warnings and exceptions).

wcfbyexample_introduction/server_components.gif

Finally, but not the least, we have the client components. The client is a WPF application designed using the MVVM pattern. This pattern provides a neat view XAML component with none or very little code behind, the binding capabilities of XAML in conjunction with the ViewModel class leverages how the client renders the DTOs provided by the services layers.

The client decouples the service layers into two main components. The adapter is responsible for the managing of business messages retrieved during the execution of services. The WCF Proxy layer is responsible for the management of WCF services, the design is neat and is a nice way of decoupling the client from the WCF service.

wcfbyexample_introduction/client_components.gif

Available articles in Codeproject

Date Article
28-June-2010 WCF by Example - Chapter I - Baseline
05-July-2010 WCF by Example - Chapter II - Repository Locator
10-July-2010 WCF by Example - Chapter III - Response
16-July-2010 WCF by Example - Chapter IV - Transaction Manager
23-July-2010 WCF by Example - Chapter V - Contexts
31-August-2010 WCF by Example - Chapter VI - Baseline MVVM
04-September-2010 WCF by Example - Chapter VII - Contract Locator
15-September-2010 WCF by Example - Chapter VIII - Relay Command
19-September-2010 WCF by Example - Chapter IX - Notify Property Change
16-October-2010 WCF by Example - Chapter X - DI with Spring.Net
04-November-2010 WCF by Example - Chapter XI - NHibernate Implementation
24-November-2010 WCF by Example - Chapter XII - WCF Implementation
19-December-2010 WCF by Example - Chapter XIII - Business Domain Extension
07-January-2011 WCF by Example - Chapter XIV - Validation & Exception Management
16-December-2012 WCF by Example - Chapter XV - RavenDB Implementation
12-February-2013 WCF by Example - Chapter XVI - EF 5 & SQL CE - AzureWebSites Deployment

Available chapters (source code) in Codeplex

Date Chapter
14-June-2010 Chapter I - Baseline
14-June-2010 Chapter II - Response
14-June-2010 Chapter III - Response
14-June-2010 Chapter IV - Transaction Manager
14-June-2010 Chapter V - Service Locator
14-June-2010 Chapter VI - Baseline MVVM
14-June-2010 Chapter VII - Contract Locator
29-July-2010 Chapter VIII - RelayCommand
29-July-2010 Chapter IX - Notify Property Changed Pattern
29-July-2010 Chapter X - Dependency Injection
12-September-2010 Chapter XI - NHibernate Implementation
07-October-2010 Chapter XII - WCF Implementation
14-November-2010 Chapter XIII - Business Domain Extension
12-December-2010 Azure Solution - In-memory mode WebRole
07-January-2011 Chapter XIV - Validation & Exception Management
07-October-2011 Client re-factor: ServiceAdapter & CommandDispatcher pattern 
16-December-2012 RavenDB Implementation
12-February-2013 Entity Framework Implementation

Future chapters 

Chapter State
Azure Deployment - In-memory WebRole Source code is available

History

14 June 2010 - Introduction article was created.
28 June 2010 - Chapter I is done and series are published.
05 July 2010 - Chapter II was added to the series
10 July 2010 - Chapter III was added to the series
16 July 2010 - Chapter IV was added to the series
23 July 2010 - Chapter V was added to the series
31 August 2010 - Chapter VI was added to the series
04 September 2010 - Chapter VII was added to the series
15 September 2010 - Chapter VIII was added to the series
19 September 2010 - Chapter IX was added to the series
07 October 2010 - Source code for Chapter XII is available at CodePlex
16 October 2010 - Chapter X was added to the series
04 November 2010 - Chapter XI was added to the series
24 November 2010 - Chapter XII was added to the series
12 December 2010 - In-memory WebRole is deployed to MS Azure
19 December 2010 - Chapter XIII was added to the series
07 January 2011 - Chapter XIV was added to the series
09 February 2011 - Chapter XIV section 2 was added to the series
07 October 2011 - Client re-factor was made available on Codeplex
20 October 2012 - SQL-CE 4.0 support was added to the solution
16 December 2012 - RavenDB implementation
12 February 2013 - Entity Framework implementation

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Enrique Albert
Software Developer (Senior)
Ireland Ireland
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerRe: Client and Server on the same machine?memberEnrique Albert23 Mar '12 - 14:47 
Denis Kozlov wrote:
Please let me know if you would consider client-server approach if they both installed on the same machine

Your configuration is the simplest in terms of components and deployment; and for a limited number of users is probably adequate in terms of memory/processor/database connections. Now, you should use a conservative approach when it comes to caching in NHibernate; with the configuration you describe, you should only use cache for read-only entities.
As you say, it all depends on the number of users and server resources.
 

Denis Kozlov wrote:
In case if it will be just application (not client-server). Do you think that your solution can be easily adopted for non client-server case?

Yes, the series is just about this aspect. The point is to realise how to use DI and the interface contracts so we can easily provide different infrastructures but without changing our user interface and business logic. In the series, we only bring WCF in chapter XII, before that we execute both the user interface, business logic/domain and nhibernate in one single process.
I hope the series is making clear the point that WCF is a pluggable component, as the database component is.
 
I am going to start a new project where we only require an standalone in-process application like yours, I dont like to over-engineering but I hope I can apply the series infrastructure model ensuring the application can be deployed client-server if required.
AnswerRe: Client and Server on the same machine?memberEnrique Albert23 Mar '12 - 14:51 
btw, if you have a chance, have a try with WPF; XAML is a comprehensive library/"language" but it is worthy the time and effort. It is one of the best things MS has done in recent years.
QuestionNice series - i have one WCF trouble that keeps apearing in different projectsmemberHaBiX13 Mar '12 - 0:31 
Hey all,

I'm running into some wierd wcf errors that happen randomly:

- I got asp.net 4.0 web site, with one "FooService.svc" that inherits some service class (compiled in different project).
- I'm using windows forms as a client to talk to my FooService.svc
- All works well until the client starts getting "Cant activate service" exception
- If i browse my FooService.svc with IE i get something like:
[FileNotFoundException: Could not load file or assembly 'App_Web_ynlv0b1k, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +39
 
- if i browse other aspx pages, everything works fine.

What i think is happening (no clue):
- asp.net/app pool for some reason inits recompile/recycle of .svc?!
- the compiler for some reason fails to make "App_Web_yn1v0b1k.dll" (in the case i posted up)
- asp.net tries to use/reference the non-existing dll - then responses exception

To fix the problem i either have to restart iis, or make change in web.config to init re-compile again.

I googled a lot and found other users with same trouble, but no solutions that worked.

 

Thanks for any suggestions! Smile | :)
AnswerRe: Nice series - i have one WCF trouble that keeps apearing in different projectsmemberEnrique Albert13 Mar '12 - 13:11 
I saw this sort of issues years ago with IIS 6 and W2003 when a new version was deployed to the servers for a classic SOAP Web Services application. They issue was always related to the temporally files that IIS generates, we had to ensure that the old temp assemblies were removed from that location when this issue was taking place. The major difference to your issue is that we had the problem straight after the application was deployed and not at later stage, I am not sure, are you saying that you are deploying the solution and the FooService service runs for a while before it throws the mentioned exception?
 
I wonder how you are deploying the application to the server and also if the problem re-occurs once you re-start IIS or force an application re-start touching the web config.
GeneralRe: Nice series - i have one WCF trouble that keeps apearing in different projectsmemberHaBiX13 Mar '12 - 21:12 
Thanks for reply Enrique.
 
And yes, it never fails after deployment. It only happens after some time Confused | :confused: and re-deployment actually fixes the service if it was down.
 
On one site, we had to implement a timer that calls "echo" method on service in intervals, and if it doesn't reply, it appends a space on end of web.config to init re-compile and fix the service. (i know its nasty, but we're cant find any other quick fix / or the source of problem)
 
The websites are not precompiled (altho they have some functionality in external dlls) / they are classic web sites (with app_code). Deployment is still all manual (copy/paste over mstsc).
 
We also tryed to move the service code from app_code into its own dll; .svc just inheriting that class (thinking if its compiled, iis wont recompile it) but we get same error after some time.
 
The biggest problem is, we cant simulate the error and sometimes it works for days before the exception starts raising.
 

 
Right now, we're thinking of changing the services to self-hosting services (to get IIS out of the compile process) with MS port sharing service. I only started reading about this, but i'm guessing the problem will be gone this way.
QuestionNHibernate concurrencymemberMember 83564422 Feb '12 - 22:00 
Hello and thank you for the great article! I read it thoroughly and i find one aspect unclear. How does the server manage NHibernate concurrency issues?
 
Thanks in advance
AnswerRe: NHibernate concurrencymemberEnrique Albert3 Feb '12 - 5:45 
I normally use the "version" feature in NHibernate. Have a look at the following link: http://ayende.com/blog/3946/nhibernate-mapping-concurrency[^]
GeneralMy vote of 4memberivix4u2 Feb '12 - 19:30 
Very Good Article
GeneralWCF IntroductiongroupAnkitaaguggi11 Nov '11 - 20:36 
Thumbs Up | :thumbsup: This is awesome post. Its really helpful for me. Here I have got another useful link related to this post over the internet, You may check out it by clicking on the link...
 
http://mindstick.com/Blog/230/WCF%20Introduction
 
Here I would like to thank everyone.
 
Smile | :) Thanks Everyone!
QuestionWhat about sequrity?memberWebGrave9 Nov '11 - 4:19 
Hello, Enrique.
 
At this moment i'm try to apply your great patterns from this article. Also i need to add some authorization functionality to client application. Let's we have a user name and passward and let's server API needs this data at every request (over https). I see some ways to modify your patterns for this purposes. For example, is it suitable to add a new methods getCustomerService(username, password) to IContractLocator interface (or set auth data to it's concrete implementations through properties)? Another way is to set authorization data to global context of client application (only one user can use application).
Enrique, what you can advice me about this problem?
AnswerRe: What about sequrity?memberEnrique Albert10 Nov '11 - 2:51 
From my experience, application security is based on setting visibility on menus, buttons and so for.
I normally map AD principals to application roles that contain application permissions. In a recent WPF project, we enabled a server method that returned a list of application permissions available for the user. (ServiceSecurityContext is used on WCF to gather the current WindowsIdentity details). Then, in the client side, we developed extended controls from standard controls with DependencyProperties that can be used in the XAML to indicate which application permission is required to enable/display the control.
 
You may also want to add an additional security/authorisation checking in the server methods. I can think of couple solutions, probably something similar to the implementation (InstanceCreationAttribute) of IContractBehavior but instead an implementation of IOperationBehavior may do the trick.
GeneralMy vote of 5memberDasiths24 Oct '11 - 15:16 
very well detailed and to the point.
QuestionLook forwarding for silverlightmembercaosnight21 Oct '11 - 1:19 
Thank you very much.
 
This article is my underlying of my first WCF and NHibernate project.
I'm keep looking for new update and silverlight implementation
Questionwhy in your viewmodels you have a reference from its view?membermtaboy7 Oct '11 - 9:34 
Hi...In your wpf Layer...you use mvvm pattern...but i hav a question.in your viewmodels you have a reference from its view ...is it correct in mvvm?
AnswerRe: why in your viewmodels you have a reference from its view?memberEnrique Albert7 Oct '11 - 16:35 
Hi, I see what you mean, for example, in the eDirectory solution the following code is contained in the CustomerDetailViewModel class:
 
 
01      private readonly CustomerDetailView View;
 
        public CustomerDetailViewModel(CustomerDto operation)
        {
            CustomerServiceAdapter = new ServiceAdapter<ICustomerService>();
            Model = new CustomerDetailModel {Customer = new CustomerDto()};
            if(operation != null) Model.Customer = operation;
02          View = new CustomerDetailView {DataContext = this};
        }
 
As you indicated the ViewModel knows about the View, line 01. And the ViewModel is responsible for the creation and initialisation of the View, line 02. The reason I keep a reference to the View is to be able to trigger some actions on the View in my commands. Simple things like closing the window and so for:
 
 
        private void Save()
        {
            if (Model.Customer.Id == 0)
            {
                ...
            }
 
            View.DialogResult = true;
            View.Close();
        }
 
I could have a more generic reference, instead of declaring a reference to CustomerDetailView, instead it could be a reference to Window or even better to some interface that encapsulates the required functionality. I should also add some additonal code/logic to ease the testing of the ViewModel without creating a instance of a Window.
 
Could you suggest a better way to fulfil the above requirements?
 
Thanks
GeneralRe: why in your viewmodels you have a reference from its view?membermtaboy7 Oct '11 - 21:46 
In some mvvm fremeworks such as mvvmlight toolkit using from mediator service(Messenger class in mvvmlight)
GeneralRe: why in your viewmodels you have a reference from its view?memberEnrique Albert8 Oct '11 - 3:00 
Very interesting, it makes sense. Worth to have a look it.
 
Thanks
GeneralMy vote of 5memberWooters7 Oct '11 - 5:36 
Great work, thanks for sharing.
QuestionBroken Link!memberRoland Ebner23 Aug '11 - 23:22 
Link to Chapter I is broken http://www.codeproject.com/KB/architecture/wcfbyexample_baseline.aspx
AnswerRe: Broken Link!memberEnrique Albert24 Aug '11 - 2:04 
Fixed ... thanks
GeneralMy vote of 5memberSathishkumar_P14 Feb '11 - 0:56 
Nice one mate!
GeneralMy vote of 5memberVivek Johari9 Jan '11 - 4:02 
nice one.....
Generalnice one - have 5memberPranay Rana7 Jan '11 - 10:28 
nice and thanks for sharing

GeneralOne Suggestionmemberprasad0222 Dec '10 - 3:46 
Now you have many related posts so you need to have first and last button always Smile | :)
Thanks and Regards,
prasad

GeneralMy vote of 5memberprasad0222 Dec '10 - 3:45 
Great 5/5
GeneralRe: My vote of 5memberEnrique Albert22 Dec '10 - 16:14 
Thanks for the support
Questionwcf datacontractsmemberWebGrave21 Dec '10 - 0:52 
Hi, Enrique.
It's really cool blockbuster).
 
But I have one question.
 
Why u didn't set the [DataMember] attribute to properties of DTO classes (like CustomerDto e.t.c). How WCF will understand this data fields to be serialized?
AnswerRe: wcf datacontractsmemberEnrique Albert21 Dec '10 - 3:09 
WebGrave wrote:
How WCF will understand this data fields to be serialized?

 
With .Net 3.5 SP1 WCF is able to serialize POCO classes without the markup. You may want to check the following article[^]. I only use the attributes if it is really necessary, WCF serialization could be very tricky so I tend to keep it simple.
 
Thanks for the feedback.
AnswerRe: wcf datacontractsmemberWebGrave21 Dec '10 - 3:31 
thanx
QuestionWhat are the requirements to run this project ? Can I run this on VS2008 ? What other add-ons are required ?memberrajesh_chan12 Nov '10 - 1:06 
Can I run this all in VS 2008 ?
 
Thanks and regards,
Rajesh Chandras
AnswerRe: What are the requirements to run this project ? Can I run this on VS2008 ? What other add-ons are required ?memberEnrique Albert12 Nov '10 - 2:46 
The eDirectory source code is a VS2010 solution, I recall having some problem at the start when I tried to use the Express version of VS2010 so instead I am using a licensed version of VS2010.
The only "add-on" we are using is MS UnitTests, the rest of the third party libs are included within the source code.
You could try to manually "down-grade" the projects to VS2008 as we are not using any of the new features of .Net 4.0 yet.
GeneralDeploymentmemberfgoldenstein8 Oct '10 - 3:04 
Very nice article!! I think that it would be very interesting if you talk about deployment. Deployment problems can be very hard to solve and they're very time consuming.
Thanks! Greetings from Argentina!
GeneralRe: DeploymentmemberEnrique Albert8 Oct '10 - 22:55 
Sure, but could you be a little more specific?
 
Are you concerns in relation to the deployment of the server or client components? If it is the server side, are you thinking in terms of deployment the application on IIS6, IIS7 with WAS, Windows Service or your own application? or maybe you are interested in which WCF transport binding to use? I am just not sure what you are looking for.
 
Thanks
GeneralRe: Deploymentmemberfgoldenstein9 Oct '10 - 10:11 
Thanks for your quick answer. I'm thinking about deploying Silverlight project with WCF Service to IIS in a shared hosting (no access to IIS). For example, you have add baseprefix pointing to domain URL, etc. I think that it would be very usefull to have a step by step guide with common errors. It's just a suggestion because I wasted a lot of time deploying a project and I didn't get much information Googling.
Thanks
GeneralRe: DeploymentmemberEnrique Albert9 Oct '10 - 15:27 
I see now where you are coming from. I have to be honest but normally we have full control of our production environments or we can indicate the infrastructure vendor what changes to make. Our problems are normally around clustering, security (AD authentication or/and authorization) and transport configuration in the WCF side. I think that your problems were of a different nature.
 
I am thinking of deploying eDirectory in Azure and explore the Silverlight client side. That could be another 5 or 6 articles for the series. Poor me Smile | :)
 
It sounds to me that you might be a more appropriate person to produce the article, it may be a good material for a first article on CodeProject, it could help others that could be found in the same situation that you mentioned. If you do so, please, could you add a link in this thread to it?
 
Saludos y disculpas por no poder ayudar mas.
GeneralRe: Deploymentmemberfgoldenstein12 Oct '10 - 7:32 
As soon as I work around a deployment problem I'll write an article here. I invite you to my training blog www.ittraining.com.ar . I post every problem/solution I found in my daily work.
Thanks again!
GeneralRe: Deploymentmemberlinhjob19 Oct '10 - 1:47 
fgoldenstein,
the site is not in English.
GeneralRe: Deploymentmemberfgoldenstein20 Oct '10 - 2:00 
Yes, I know that it's not in English. But, the important thing is Universal (XML configuration). If you want to read the text you can use a translator. I'm sure you'll understand the important thing about the post. If not, feel free to write a comment.
GeneralMy vote of 5memberJRiggs15 Sep '10 - 8:39 
I found these articles to be very well written and useful. Thanks!
GeneralRe: My vote of 5memberEnrique Albert22 Dec '10 - 16:17 
Thanks for the feedback
GeneralMy vote of 4memberAmit Kumar Tiwari4 Jul '10 - 22:43 
Nice article.
GeneralRe: My vote of 4memberEnrique Albert17 Jul '10 - 21:55 
Thanks
GeneralRe: My vote of 4membershakil03040037 Oct '10 - 4:38 
Nice article.
Md. Shakil Ahmed.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 12 Feb 2013
Article Copyright 2010 by Enrique Albert
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid