menu

Sunday, July 4, 2010

How to Create WCF Application?

Step 1:

Open Visual Studio 2008 and click File -> New -> Project (a new (New Project) window will open, select Project Type: WCF(WCF Service Library)). Look at image given below.



Step 2:

Write the code inside interface IService1 given below

public interface IService1
{
[OperationContract]
int Sum(int value1, int value2);
[OperationContract]
int Mult(int value1, int value2);
}

Step 3:

Write this code in side class Service1.cs

public class Service1 : IService1
{
#region IService1 Members

int IService1.Sum(int value1, int value2)
{
return value1 + value2;
}

int IService1.Mult(int value1, int value2)
{
return value1 * value2;
}

#endregion
}

Run the service (press F5). Now a new window named WCF Test Client will open(Don't close it because this will give service to client). Double click on Config file and a XML Code will be shown right side, copy highlighted code(end point address)(Ex. http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary2/Service1/).



Now your service is started.

Step 4:

Now create a website site to call WCF.

Right click on Solution Explorer -> Add Service Reference (A new window will open).
Paste link copied from Config File of started WCF (Ex. http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary2/Service1/)
Click GO then OK.(Your service is added now).



Add two TextBox and a Button. On button click create the object of class which is in WCF, and call method of that class.

ServiceReference1.Service1Client ms = new ServiceReference1.Service1Client();
Label1.Text = ms.Mult(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text)).ToString();
Label2.Text = ms.Sum(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text)).ToString();

No comments:

Post a Comment