Updated with links to WCF-Part 2, WPF, WWF, WCF Tracing FAQ, 8 steps to enable Windows authentication on WCF BasicHttpBinding, difference between BasicHttpBinding and WsHttpBinding, WCF FAQ Part 3 – 10 security related FAQ, SilverLight FAQ Part 1 and Part 2, One-Many and One-One relationship using LINQ to SQL.
In this section we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF.
Watch my 500 videos on various topics like design patterns, WCF, WWF, WPF, LINQ, Silverlight, UML, SharePoint, Azure, VSTS, and a lot more @ here, you can also catch me on my trainings @ here>.
- Click here to see Windows Communication Framework (WCF) - Part 2
- Click here to see Windows Presentation Foundation (WPF)
- Click here to see Windows Workflow Foundation (WWF)
- Click here to see Windows Communication Framework (WCF) Tracing FAQ
- Click here to see 8 steps to enable Windows authentication on WCF BasicHttpBinding
- Click here to see Difference between BasicHttpBinding and WsHttpBinding
- Click here to see WCF FAQ Part 3 – 10 security related FAQ
- Click here to see 21 Important FAQ SilverLight - Part 1
- Click here to see (Animations and Transformations) FAQ SilverLight - Part 2
- Click here to see One-Many and One-One relationship using LINQ to SQL
What is .NET 3.0?
In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows Presentation Foundation + Windows Workflow Foundation + Windows Card Space.
What is Windows Card Space?
It was previously known by its codename Info Card. It is a framework by Microsoft which securely stores digital identities of a user and provides a unified interface to choose the identity for a particular transaction, such as logging in to a website. Windows Card Space is a central part of Microsoft’s effort to create an identity met system, or a unified, secure, and interoperable identity layer for the internet.
What is WCF?
First let us give a short answer to this: "WCF (Indigo was the code name for WCF) is a unification of .NET Framework communication technologies". WCF is a unification technology which unites the following technologies:
- NET remoting
- Web services
The below figure depicts the WCF fundamentals pictorially.
Figure: 1 - WCF Components
What are the important principles of SOA (Service Oriented Architecture)?
WCF is based on SOA. All big companies are playing big bets on SOA. So how can Microsoft remain behind? In order to implement SOA architecture easily you need to use WCF. SOA is based on four important concepts:
Boundaries are well defined
In SOA, everything is formalized. The client who is consuming the service does not need to know how the implementation of the service is done. If you look at some old methodologies of communication like DCOM, for any change at the server level the client also has to change. The server and client implementations were so bound that changes needed to be done at all places. In SOA, the rule is if you do enhancements you do not need to change anything at the client. SOA based applications only understand that there is an end point, contract, and bindings.
Note: Just to clarify shortly about end point and contract. Any SOA service is exposed through an end point. End point defines three important aspects: What, Where, and How. We will understand more details of the same in the following sections.
Change is the law of nature and services will evolve. In SOA, services can be versioned and you can host those services in new ends. For instance, you have a service called as “Search Tickets (Ticket Number) “which gives details based on Ticket Number and it is exposed on end point “ep1”. Tomorrow you want to make your Search Tickets service more useful by also providing an extra option of allowing it to search by passenger name. Therefore, you just declare a new end “ep2” with service “Search Tickets (Ticket Number, Passenger Name)”. The client who is consuming the service at end ep1 continues and at the other end, we have evolved our service by adding new ends ep2.
Services share only schemas and contracts
Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is no heavy coupling between environments.
Service compatibility is policy based
Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance your service needs to be hosted for two types of clients, one which uses Remoting as the communication methodology and another client uses DCOM. An ideal SOA service can cater to both of them according to there communication policies.
Note: Many people assume Web Services are the base for SOA. The answer is 50 % right. What web services lack is policy based service compatibility. If you host a web service it can only serve with an HTTP communication channel and SOAP message. Any other type of client trying to communicate will not degrade itself. This is what is provided by WCF. You can host the service in one or more modes. For instance you can host a WCF service using remoting and ASMX.
What are ends, contract, address, and bindings?
The above terminologies are the core on which SOA stands. Every service must expose one or more ends by which the service can be available to the client. An end consists of three important things: where, what, and how:
Contract is an agreement between two or more parties. It defines the protocol of how a client should communicate with your service. Technically, it describes parameters and return values for a method.
An Address indicates where we can find this service. Address is a URL which points to the location of the service.
Bindings determine how this end can be accessed. It determines how communication is done. For instance, you expose your service, which can be accessed using SOAP over HTTP or BINARY over TCP. So for each of these communication mediums, two bindings will be created. The below figure shows the three main components of an end. You can see the stock ticker is the service class, which has an end hosted on www.soa.com with HTTP and TCP binding support and using the Stock Ticker interface type.
Figure 2: Endpoint Architecture
Note: You can also remember the end point by ABC where A stands for Address, B for bindings, and C for Contract.
Which specifications does WCF follow?
WCF supports specifications defined by WS-* specifications. WS-* specifications are defined together by Microsoft, IBM, SUN, and many other big companies so that they can expose there services through a common protocol. WCF supports all specifications defined and now we will learn them one by one.
- Messaging (WS-Addressing): SOAP is the fundamental protocol for web services. WS Addressing defines some extra additions to SOAP headers, which makes SOAP free from the underlying transport protocol. One of the good things about message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize the transmission format for SOAP messages in XML-Binary format using XML optimized packaging (XOP). Because data will sent in binary and optimized format, it will give us a huge performance gain.
- Security (WS-Security, WS-Trust, and WS-Secure Conversation): All the three WS- define authentication, security, data integrity, and privacy features for a service.
- Reliability (WS-Reliable Messaging): This specification ensures end-to-end communication when we want SOAP messages to be traversed back and forth many times.
- Transactions (WS-Coordination and WS-Atomic Transaction): These two specifications enable transaction with SOAP messages.
- Metadata (WS-Policy and WS-Metadata exchange): WSDL is an implementation of the WS-Metadata Exchange protocol. WS-Policy defines more dynamic features of a service, which cannot be expressed by WSDL. We have stressed on the WS-* specification as it is a specification which a service has to follow to be compatible with other languages. Because WCF follows WS-* specifications, other languages like Java, C++ can also exploit features like Messaging, Security, Reliability, and transactions written in C# or VB.NET. This is the biggest achievement of WCF to integrate the above features with other languages.
Note: During an interview the interviewer expects that you know what WS-* specifications are supported by WCF and its advantages with respect to interacting with other languages.
What are the main components of WCF?
We need to define three main components in WCF:
- Service class
- Hosting environment
- End point
What is a service contract, operation contract, and data contract?
In this example, we will make a simple service which displays the total cost of a complete product group. In simple words, this service will take three parameters per product cost, number of products, and the product name. In return the service will return the total cost of all the products by multiplying the number of products with the cost per product. As we go ahead with this explanation, we will try to understand all the terminologies which are asked in the above question. First, you need to create a WinFx service project. You can see in the below figure we have selected the WinFx project.
Figure 3: Create new WinFX Service class
In this project, we add a new class and name it serviceGetCost.cs. This class will have our core implementation and this is the class which has all the action. The service class has to be exposed to the external client. We need to use the Service Contract attribute to mark it as a service class. The Service Contract attribute defines saying which application interface will be exposed as a service. You can see in the below code snippet that we have made an interface and marked it as a Service Contract. It is not essential that you need to use an interface, you can also use a simple class and mark it as a Service but an interface represents a contract and does not have implementation. In short, they stand at a very higher level of abstraction. So as a good design practice using interface to represent a service contract makes more sense.
The next thing to note is the Operation Contract attribute. The Operation Contract dictates which methods should be exposed to the external client using this service. It defines individual exchange or request and replies. In the current sample, we have defined the
GetTotalCost method which will be used by the end client to get the total cost results. The next thing to note in the code snippet is the Data Contract attribute. In the previous two steps, we have exposed a class as a service by using Service Contract and methods by using Operation Contract. Every operation will definitely do some kind of data transfer. The Data Contract attributes defines which type of complex data will be exchanged between the client and the service. They determine which parameters to be serialized. When you are using simple data types like int, bool, etc., it is not necessary that you need to mark the data contract attribute. Because you will always find matching types on the client. However, for complex structures like the one shown in the below code snippet, you will need to define a data contract. Remember, the data contract defines how this data will be passed during transmission. In short, the data contract attribute defines how data will be serialized in transmission. In the below sample we have marked the structure product data to be serialized.
Figure 4: The Service class
As the data contract is all about serialization you need to import the
System.Runtime.Serialization namespace. In the next step, we implement the
GetTotalCost function. It just returns a simple string with the product name and the total cost of all products. Once our service class is done it is time to host this service. There are various ways of hosting a WCF service, we will look into that in the next question. For the current example, we will host in its own process.
Figure 5: Hosting the service
Hosting the WCF service needs two things: one is the config file and the second is the hosting code on startup. Because we are hosting this service in its own application process this needs to be a Windows application. So first let us have a look at what entries we need to make in the App.config file.
In the above figure, everything is clear but let us understand all the sections defined in the App.config file. In the configuration section, we need to add a new section
<system.serviceModel>. The most important part of
<system.serviceModel> is the endpoint tag. As said in the previous answer End gives three important answers: Where, What, and How. In short where is the service, what the contract of the service is, and how we communicate with the service. In the above code snippet, we have only defined the contract, i.e., what and how, that is bindings. The where is defined in the application entry point
static void main (). Therefore, the contract attribute defines the interface and binding says that the end clients can communicate using the HTTP protocol. In the
static void Main method, we create an object of the Service Host class and use the
Open method to host the service. We have used the URI object to define the address where the service will be hosted.
Figure 6: Service Started
If you compile the project, you will see something as shown in the above figure. This says that the service is up and running and ready to serve any WCF client. Now it is time to develop the consumer which will consume this WCF service. Microsoft has provided a decent automation to generate the client. The below figure depicts the various steps:
Figure 7: svcutil in action
Go to the command prompt of the Windows SDK and run the following command:
Svcutil <Service hosted URI>
In the above command <Service Hosted URI> is the URI on which the service is hosted. One you run the command against the URI, it will generate two files: the config file and the proxy. You can see in the above figure that two files are generated: serviceGetCost.cs and output.config. With the help of these two files, we will make our client.
Figure 8: Client code walkthrough
You can see in the above figure that we have made the WFCClientGetCost project. In that, we have added output.config and serviceGetCost.cs to the client project. We have renamed output.config to app.config. Once we have done everything, it is time to write the client code which calls the proxy which in turn will call the service hosted. In the above figure, you can see we have the client code also. It is a simple code: we first create the object of the data structure and set the values. Then we create the object of the service and call the
GetTotalCost function. If everything is compiled and you run the server and client, you should get your output as shown below.
Figure 9: Output of WCF service
What are the various ways of hosting a WCF service?
There are three major ways to host a WCF service:
- Self-hosting the service in its own application domain. This we have already covered in the first section. The service comes into existence when you create the object of the Service Host class and the service closes when you call the
Close method of the Service Host class.
- Host in application domain or process provided by IIS Server.
- Host in the Application domain and process provided by WAS (Windows Activation Service) Server.
How do we host a WCF service in IIS?
Note: The best way to know how to host a WCF in IIS is by doing a small sample. So what we will do is host the same GetCost sample which was self hosted in the previous section.
The first thing you will need is to create the SVC file which exposes the service class. The SVC file contains the pointer to the class. You can see from the figure below that the class attribute points to the class whose interface is exposed by the service.svc.cs file. Also, note the actual interface is in the service.svc.cs file. The below figure has both the files service.svc, which has the class attribute which points to the service class, and the interface, which resides in the service.svc.cs file. We have taken the same sample which was self-hosted in the previous question.
Figure 10: The SVC file and the behind code
We also need to provide an implementation for the interface. So we have made a class
ServiceGetCost which has the actual implementation. The below figure shows the same in detail. In the below figure you can also see the solution files.
Figure 11: Implementation of Service.svc.cs
We also need to specify the service type and the endpoint in the web.config file. Also note that we have specified the HTTP binding because we will be hosting the service on IIS.
Figure 12: Web.config file for hosting service on IIS
Now that we are done with the coding part, we need to create the virtual directory in IIS. In the below figure in Step 1 and Step 2 we can see how to create the virtual directory in IIS. One important thing to note while creating a virtual directory is to set the access permission to execute.
Figure 13: IIS Configuration
In the third step, we will publish the website to our virtual directory. Note the fourth step in which we have copied the svc file so that the service can be requested. Note: ASP.NET compilation has changed in ASP.NET 2.0. In 2.0, there is no concept of solution files. So if you want to have a fully compiled DLL you need to publish the project to a virtual directory. Once you have hosted the SVC file you can test the same by requesting the service.svc file. If everything works fine you will get something as shown in the below figure:
Figure 14: IIS WCF client
Using Svcutil.exe, you will need to generate the proxy class and the config file. The proxy and config will be the same, as we had done for self-hosting. The one important change is the address. The config file URL now points to service.svc, which is hosted on IIS. You can run the same client which we had created for self-hosting. The only change you will need to do is change the endpoint address.
Figure 15: Output of WCF client at IIS
You should get the same output which we had received for self-hosting.
What are the advantages of hosting WCF Services in IIS as compared to self-hosting?
There are two main advantages of using IIS over self-hosting:
IIS provides automatic activation which means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in the case of self hosting the service should always be running.
If IIS finds that a service is not healthy that means if it has memory leaks etc., IIS recycles the process. Let us try to understand what recycling is in the IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, the process stops and you lose all information. IIS also restarts the worker process. By default, the worker process is recycled in around 120 minutes. So why does IIS recycle? By restarting the worker process it ensures any bad code or memory leak does not cause issues to the whole system. In the case of self-hosting both the above features you will need to code yourself. Lots of work, right? That is why IIS is the best option for hosting services until you are really doing something custom. The below figure shows where the recycle option is located in IIS. You need to click on the DefaultAppool and then Properties.
Figure 16: IIS recycle option
What is the difference between WCF and Web services?
Web services can only be invoked by HTTP. A Service or a WCF component can be invoked by any protocol and any transport type. Second, web services are not flexible. However, Services are flexible. If you make a new version of the service you just need to expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
What are the different bindings supported by WCF?
WCF includes predefined bindings. They cover most of the bindings widely needed in day-to-day applications. However, just in case you find that you need to define something custom WCF does not stop you. So let us try to understand what each binding provides:
- BasicHttpBinding: This binding is used when we need to use SOAP over HTTP. This binding can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized forms like MTOM.
Note: MTOM is discussed in one of the pervious questions in this chapter.
- WsHttpBinding: It is same as BasicHttpBinding. In short, it uses SOAP over HTTP. But it also supports reliable message transfer, security, and transaction. WS-Reliable Messaging, security with WS-Security, and transactions with WS-Atomic Transaction support reliable messages.
- NetTcpBinding: This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. The biggest disadvantage of NetTcpBinding is that both server and client should be made in a .NET language.
- NetNamedPipesBinding: Ths binding sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.
Note: An interprocess control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication within processes. But when it comes to communicating across a network TCP holds the best choice. So if you are using WCF to communicate with a process it’s the best choice to use in terms of performance. Named pipes do not perform when the traffic is heavy as compared to TCP/IP.
- NetMsmqBinding: This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.
What is an one-way operation?
IsOneWay equal to true ensures that the client does not have to wait for the response. So methods marked by
true should always return
void. In this, the caller does not get anything in return so it is called as a one-way communication. In order to understand one-way implementation in WCF let's make a code walkthrough of a sample. Note: You can find code for the same in the “WCFIsOneWay” folder.
Figure 17: One-Way in action
Above is the code snippet which describes practically how one way works in WCF. The above given code snippet is numbered. Below is the explanation according to the numbers marked in the figure:
- This is the code snippet of the server service. We have created a method called
DoHugeTask makes the method sleep for 5000 ms and then displays the time when the task is completed.
- This code snippet is for the client. It creates a proxy object of
serviceIsOneWay and calls the
doHugeTask method. After calling
doHugeTask, the client execution continues. So as a proof, we display the time when the method calling was completed.
- This screenshot shows the output given by both the server and the client. The top window displays the server output and the bottom window displays the client output.
Note: You can find the code in the WCFIsOneWay folder. For generating the proxies you have to follow the same steps which are shown in the previous section.
Run the server program first, i.e., ServiceIsOneWay, and run the client later. You will see that the client runs
doHugeTask and moves ahead. Therefore the client completion time is less than that of the server. One more thing to understand is that one way does not give any notification back for completion. Therefore it is like fire and forget.