Saturday, May 17, 2008

Simple Webservice for C#.Net

Webservices

Definition:

A web service allows a site to expose programmatic functionality via the Internet. Web services can accept messages and optionally return replies to those messages.

How to work with Web services in c#?

Create a New website with ASP.NET Web Service type. And there in the solution explorer window the service.asmx file will be created automatically. Add a web reference to the project like as following steps

Step1: go to solution explorer and right click on the project there you will find add web reference link, and click on that and you will get window like


And click on the web services in this solution then you will get

And click on service hyperlink and then you will get like And click on add reference button then the reference will be added to your project.And then you will get the references like as follows in the solution explorer. At very first after creation of website you will get a form named App_code/Services.cs in that by default it will give the code for displaying of Hello world. In that code I will write another web method for adding of two numbers.

[WebMethod]

public int add(int n1,int n2)
{ return n1 + n2; }

After that we have to add another new item for our project named webservices.aspx.

In the design window I will take two text boxes , one label and one button . In the button click event i.e., in .cs file we need to write code as like this

protected void btnSum_Click(object sender, EventArgs e)
{
Service ser = new Service();
lblTotal.Text = ser.add(Convert.ToInt32(TextBox1.Text),Convert.ToInt32(TextBox2.Text)).ToString(
);
}

And then build the application and run it.
In the output window you will get like this