Building a Web Service means creating a class and expose this class's some methods
to web so that a client can consume this web service.To do so create an ASP.NET
Web Service in VS2008 by selecting File > New > Web Site and select ASP.NET
Web Service. (We will get a data set from a remote machine)
Now in solution
explorer you have a service.asmx file. Delete it and add a new file to your project.Select
Web Service, name it as "Customer.asmx".
Write this code to your Customer.cs in your App_Code directory.
[WebMethod] //expose our method to the web
public DataSet GetCustomers() //method to get dataset from a database
{
SqlConnection conn;
SqlDataAdapter adapter;
DataSet result = new DataSet();
string cmdString = "SELECT * FROM [SELECT * FROM SalesLT.Customer]"; //command string
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString);
adapter = new SqlDataAdapter(cmdString, conn);
adapter.Fill(result); //our sqladapter fills the data set
return result; //return resulting dataset
}
Now view in the browser our Customer.asmx You will see ASP.NET's specific
page for Web Services.
Click GetCustomer() method.There is SOAP messages and also
an invoke button to invoke the WebService.You can check whether the webservice is
working or not.
At this point we can consume this webservice.Create another ASP.NET website and right click
on the project name.Select "Add Web Reference"
In URL part copy your asmx file's URL.
In web reference name part, write Customer Service.Click "Add Reference" Now VS2008 has created
necessary classes in the second website to work with web reference.In Default.aspx page add
a button a GridView.In click event of button write:
protected void Button1_Click(object sender, EventArgs e)
{
CustomerReference.Customer ws = new CustomerReference.Customer();
//CustomerReference is the name we defined when adding Web Reference
GridView1.DataSource = ws.GetCustomers();
GridView1.DataBind();
}
If there is no exception, when we click the button we should see the results.:)