Webservice using Generic Collections
Below code is a Example for Webservice using Generic Collections. Advantage of using Generic Collections is it lets client applications bind directly to the output.Generic list is the one of the way to return more than one value from webservices.
This is a ASP.NET Webservice using C#, List and SQL Server 2008.
This code returns the country, capital and country code against a given Country Name from database. So you should create a SQL connection in the webservice and then open the connection to work on database. Store the data in a reader. Create a object of type CountryDetails List. Then add the values to the List object. Then we get Generic List of a class CountryDetails type that returns three variables as output of the webservice.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Data.SqlClient;
namespace Webservice
{
[WebService(Namespace = "http://Your_URL.in/",Description="Country capital and their codes",Name="Country Details")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
SqlConnection con = new SqlConnection("Connection String");
public class CountryDetails
{
public string country;
public string capital;
public int Code;
}
[WebMethod]
public List
{
string sqlQuery = "select * from country where Country_Name='"+Country+"' ";
con.Open();
SqlCommand com = new SqlCommand(sqlQuery, con);
SqlDataReader read = com.ExecuteReader();
var stri = new List
read.Read();
while (read.HasRows)
{
var s = new CountryDetails();
s.Code = Convert.ToInt32(read["Country_Code"].ToString());
s.capital = read["Capital"].ToString();
s.country = read["Country_Name"].ToString();
stri.Add(s);
while (read.Read())
{
var s1 = new CountryDetails();
s1.Code = Convert.ToInt32(read["Country_Code"].ToString());
s1.capital = read["Capital"].ToString();
s1.country = read["Country_Name"].ToString();
stri.Add(s1);
}
read.NextResult();
}
return stri.ToList();
}
}
}