Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Service
Now our new web service ready our webservice website like this
Now open your Service.cs file in web service website to write the code to get the user details from database
Before writing the WebMethod in Service.cs first add following namespaces
using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After adding namespaces write the following method GetUserDetails in Service.cs page
[WebMethod]
public XmlElement GetUserDetails(string userName)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like @userName+'%'", con);
cmd.Parameters.AddWithValue("@userName", userName);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
// Return the DataSet as an XmlElement.
XmlDataDocument xmldata = new XmlDataDocument(ds);
XmlElement xmlElement = xmldata.DocumentElement;
return xmlElement;
}
Here we need to remember one point that is adding [WebMethod]
before method definition because we need to access web method pulically
otherwise it’s not possible to access method publically. If you observe
above code I converted dataset to XmlElement t because sometimes we will get error like return type dataset invalid type it must be either an IListSource, IEnumerable, or IDataSource to avoid this error I converted dataset to XmlElement.
Here we need to set the database connection in web.config because here I am getting database connection from web.config
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
Now run your web service it would be like this
Our web service is working fine now we need to know how we can use webservice in our application?
Before to know about using web service in application first Deploy your
webservice application in your local system .
No comments:
Post a Comment