1. Basics of WCF
2. Download – Source Code
3. Download WCF Tutorial – PDF document
Basics of WCF
Definition of WCF
Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF we can build secure, reliable, transacted solutions that integrate across platforms.
WCF is a unified framework which provides :
1. NET Remoting 2.Distributed Transactions 3.Message Queues and 4.Web Services into a single service-oriented programming model for distributed computing.
WCF interoperate between WCF-based applications and any other processes that communicate via SOAP (Simple Object Access Protocol) messages.
Features of WCF
- Service Orientation
- Interoperability
- Multiple Message Patterns
- Service Metadata
- Data Contracts
- Security
- Multiple Transports and Encodings
- Reliable and Queued Messages
- Durable Messages
- Transactions
- AJAX and REST Support
- Extensibility
http://msdn.microsoft.com/en-us/library/ms733103.aspx
2. Service: A construct that exposes one or more endpoints, with each endpoint exposing one or more service operations.
3. Contracts: A contract is a agreement between two or more parties for common understanding and it is a is a platform-neutral and standard way of describing what the service does. In WCF, all services expose contracts.
Types of Contracts:
1) Operation Contract: An operation contract defines the parameters and return type of an operation.
[OperationContract] double Add(double i, double j);
2) Service Contract: Ties together multiple related operations contracts into a single functional unit.
[ServiceContract] //System.ServiceModel
public interface IMath
{
[OperationContract]
double Add(double i, double j);
[OperationContract]
double Sub(double i, double j);
[OperationContract]
Complex AddComplexNo(Complex i, Complex j);
[OperationContract]
Complex SubComplexNo(Complex i, Complex j);
}
3) Data Contract: The descriptions in metadata of the data types that a service uses.
// Use a data contract
[DataContract] //using System.Runtime.Serialization
public class Complex
{
private int real;
private int imaginary;
[DataMember]
public int Real { get; set; }
[DataMember]
public int Imaginary { get; set; }
}
WCF Step by Step Tutorial
This is the Basic WCF Tutorial ‘wcfMathSerLib’ will be created in a step by step approach. This ‘wcfMathSerLib’ will be tested by ‘ConsoleMathClient’ and with ‘WCF Test Client’
Steps for creating wcfMathSerLib
1. Open Visual Studio 2010 and File->NewProject
2.select WCF in ‘Recent Templates’
3.select ‘WCF Service Library’
4.Give Name as wcfMathServiceLibrary
5.Click OK
2. Delete IService1.cs and Service1.cs
3. Add IMath.cs and MathService.cs and add the code listed below
IMath.cs
using System.Runtime.Serialization;
using System.ServiceModel;
namespace WcfMathServLib
{
[ServiceContract] //System.ServiceModel
public interface IMath
{
[OperationContract]
double Add(double i, double j);
[OperationContract]
double Sub(double i, double j);
[OperationContract]
Complex AddComplexNo(Complex i, Complex j);
[OperationContract]
Complex SubComplexNo(Complex i, Complex j);
}
// Use a data contract
[DataContract] //using System.Runtime.Serialization
public class Complex
{
private int real;
private int imaginary;
[DataMember]
public int Real { get; set; }
[DataMember]
public int Imaginary { get; set; }
}
}
MathService.cs
namespace WcfMathServLib
{
public class MathService : IMath
{
public double Add(double i, double j)
{
return (i + j);
}
public double Sub(double i, double j)
{
return (i - j);
}
public Complex AddComplexNo(Complex i, Complex j)
{
Complex result = new Complex();
result.Real = i.Real + j.Real;
result.Imaginary = i.Imaginary + j.Imaginary;
return result;
}
public Complex SubComplexNo(Complex i, Complex j)
{
Complex result = new Complex();
result.Real = i.Real - j.Real;
result.Imaginary = i.Imaginary - j.Imaginary;
return result;
}
}
}
4.Modify the App.config file as shown
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service name="WcfMathServLib.MathService">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8732/Design_Time_Addresses/WcfMathServLib/MathService/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<endpoint address ="" binding="wsHttpBinding" contract="WcfMathServLib.IMath">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Result Using WCF Test Client
1. Run the WcfMathServLib project you will get the ‘WCF Test Client’
2. Select each method say ‘AddComplexNo’ Give the values in ‘Request’
3. Click on Invoke button
4. See the results in “Response”
Steps for creating ConsoleMathClient
1. Open Visual Studio 2010 and File->NewProject
2. select Visual C#->Windows in ‘Installed Templates’
3. select ‘Console Application’
4. Give Name as ConsoleMathClient
5. Click OK
2. Go to ‘Solution Explorer’ Right click on ConsoleMathClient -> Select ‘Add Service
Reference’ the below dialog will be displayed
1. Click on Discover button
2. Give namespace as ‘MathServiceReference’ and click OK
The service reference will be added now modify the program.cs as shown below.
Program.cs
using System;
using ConsoleMathClient.MathServiceReference;
namespace ConsoleMathClient
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press <Enter> to run the client....");
Console.ReadLine();
MathClient math = new MathClient();
Console.WriteLine("Add of 3 and 2 = {0}", math.Add(3, 2));
Console.WriteLine("Sub of 3 and 2 = {0}", math.Sub(3, 2));
Complex no1 = new Complex();
no1.Real = 3;
no1.Imaginary = 3;
Complex no2 = new Complex();
no2.Real = 2;
no2.Imaginary = 2;
Complex result = new Complex();
result = math.AddComplexNo(no1, no2);
Console.WriteLine("Add of 3+3i and 2+2i = {0}+{1}i", result.Real, result.Imaginary);
result = math.SubComplexNo(no1, no2);
Console.WriteLine("Sub of 3+3i and 2+2i = {0}+{1}i", result.Real, result.Imaginary);
Console.ReadLine();
}
}
}
Result
Compile and Run the project to see the Result
Pingback: WCF Step by Step Tutorial « TNV Balaji …
Pingback: Basics of WCF «
Thanks a lot Balaji !
Really helpful article. Keep more of these coming :)
I had to enter the url when adding the service reference. Just clicking on the “Discover” button without the url found nothing even though the service was running.
I also don’t understand where the definition for MathClient comes from. How does the system know to create a name like MathClient?
anyone please reply to it …even i have same query..
Just a little note. You don’t need the private members real and imaginary in Complex class when you define the members with C# 3 style shorthand property syntax.
MathClient is from
using ConsoleMathClient.MathServiceReference;
Yes you are correct …
You are a legend !
I have never seen it this simple , and everything works as expected . oh and thank you Daniel for “MathClient is from
using ConsoleMathClient.MathServiceReference;”
Thanks Shola :)
I still don’t understand where ‘MathClient’ comes from. If I want to change this name ( to ‘MonkeyClient’ or something like that) then what do I have to do ?
Thanks
The “Add Service Reference” adds a proxy class. The name is determined by taking the service contract name, getting rid of the ‘I’ prefix and adding the “Client” suffix. The proxy class allows you to talk to the service without having to create a channel factory, which requires more code. To see the code, click “View all files” in Solution Explorer.
Mikew, Exactly what you said is correct.
Can expain this please “mathclient”
Hi,
one doubt please
In cofig file the endpoint address =”" so what will be the address or it will take from baseAddress
Thanks a lot,really its helpful
Welcome @ Pushpalatha
Really nice.. thanks ya..
welcome Rajkumar !
Hi, Thanks for this awesome tutorial.
Am just starting with wcf for a project, and being an intern, it’s doubly hard for me. You have simplified my task tremendously, and this tutorial explains the concepts with much clarity.
Just one problem that I had: I had to add the Console Project to the same solution, otherwise it would not work!
Maybe it’s unique to my case, nevertheless, Absolutely Awesome Work! :)
Thanks Ayush !!!
Ayush,
No need to add the console application in same solution.
You can create new console application & add reference the dll of “WCFMathserviceLib” to console application. Then it will work.
Very good tutorial…….
thanks
Very Helpful
THANKS Rashmi
Thank you for the explanation. But I had a problem when I test with ConsoleMathClient: when I entered the address and I click “Discover”, the following message:
——————————————-
“There was an error downloading ‘http://localhost:8732/Design_Time_Addresses/wcfMathServiceLibrary/MathService/’.
Unable to connect to the remote server
No connection could be made because the target machine actively refused it 127.0.0.1:8732
Metadata contains a reference that cannot be resolved: ‘http://localhost:8732/Design_Time_Addresses/wcfMathServiceLibrary/MathService/’.
There was no endpoint listening at http://localhost:8732/Design_Time_Addresses/wcfMathServiceLibrary/MathService/ that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Unable to connect to the remote server
No connection could be made because the target machine actively refused it 127.0.0.1:8732
Si le service est défini dans la solution actuelle, essayez de générer la solution et d’ajouter de nouveau la référence du service.”
——————————————————
Can you help me please? and tell me if I must integrate the service in the solution of test
I got the same error message while adding service reference to the console application.
Anyone knows how to resolve it?
I resolved it. The issue was that while adding a service reference, you need to run the service first so that your console application can find it and then you may add it.
How can I run the service? If I start it in VS 2010, I can’t switch projects while the WCF Test Client runs?
Your Logo is nice and article too
Thanks Pavan !
Really a good article for starter with sample code. From the trace comments above I could able to recognize that MathClient object created is from the proxy class. But I would like to know if for every reference, the proxy class name is determined by taking the service contract name, getting rid of the ‘I’ prefix and adding the “Client” suffix.
Thanks once again
I got the following error:
The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MathService. Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost directly to enable support for this contract.
Any ideas?
Thanks..really helpful for me
Thanks for your comments.
Thanks its really helpfull
Great Swapnil :)
Thanks its really helpfull
Thanks Ajay !
Hi Thanku so much for this wonderful tutorial… it helped me in the rite time…..
Shortcut way to prepare for WCF –
http://rahulsfunda.blogspot.in/2011/09/windows-communication-foundation.html
Really a good article for beginners with simple understanding code…it helped me a lot…Thanks
Balaji,
This is a great example. I am not clear on MathClient. Could you please explain?
Thanks,
Ravi
Hey cool Man..
Balaji,
Excellent tutorial. I was just curious… say if the client using the WCF service is using UNIX (or some non-windows) platform, how would it access the proxy class ? From your example, the proxy class seems to be generated in a dot net language. I am sure I am missing something here. Can you please fill in my gap ?
Thanks in advance,
Asif
Hello There. I discovered your blog the usage of msn. This is an extremely smartly written article. I’ll make sure to bookmark it and return to learn more of your useful info. Thanks for the post. I’ll certainly return.
looking forward to another great article.
Really helpfull… Awesome.. Thanks..
Thanks Manthan !
this us very useful to me . thanks a lot and can you provide more examples
Really good artical
Thank you :)
Nice and simple artilce. Good for beginners
In this example when i click at discover button i not get any service in Address . So i copy baseAddress from web.config section and its works.
Please provide some more examples which clear different bindings concept.
This is a great example,
but perhaps I’m missing some basics, because to add the ServiceReference, I had to open two VS windows, one loaded with wcfMathServiceLibrary project, another with ConsoleMathClient, and run wcfMathServiceLibrary project.
Now, did I miss any step that was not mention here? Did I need to add something to IIS?
I tried to do similar example from MSDN, and same problem was there – I had to open two projects and run my host in one, in order to find the service.
Am I missing anything?
I appreciate any light on this,
vadim
It’s a very good and simple to understand.
It is nice article for the beginners.
Best,
Sekar
Nice and clean tutorial..
Thanks Bharath
hi this is goog for me
System.InvalidOperationException: The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MathService. Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost directly to enable support for this contract.
Where am I wrong actually
Great tutorial, It was really helpful to me…
Thanks de_laz
Great tutorial, it really helped me a lot
Thanks ecdance
my Math Client program unable to connect to service available in local machine! it nothing being available after clicking on Discover. Can you plz help.
It’s started working, i have opened another instance of visual studio, and kept service program running in another window of VS 2012.Thanks Balaji, It is a Nice Tutorial.
Welcome Piyush
Thank you Balaji… Helped a lot in understanding WCF….. I encountered some problem in meta data exchange…. Changed the binding type of service endpoint from wshttpbinding to httpBinding… That worked….. Also gave the service behavior name and specified that behavior in service name tag. This helped in overcoming the ImetadataExchange interface related error while running the service.. Thank you…
Hello,
I have got the following message when i am trying to run this above code that you have mention.
Target Assembly Contains no assembly types. You may need to adjust the Code Access Security policy of the assembly.
Very nice tutorial, Its really helpful for WCF beginners. Thanks
i didnt understood any thing from it anyhow thanks for posting this in serial.
I tried this tutorial on VS2008 and got this error message:
The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MathService.
Any idea why?
Nice article
good and nice article.its soo help full for my project
Without Running state for WCF Service, Is there any possible way we can call and run that service in our project?? Also knows about how to link wcf service to IIS so that whenever system start, WCF Service will start also and we can used it in our project without running webservice with another instance??
The contract name ‘IMetadataExchange’ could not be found in the list of contracts implemented by the service MathService.