Asp.Net

Friday 22 August 2014

Web Services in Asp.net

In this article ,I will Explain you how to create a simple web service in Asp.Net:

First Create a Employee Table and Insert some records in your database:(Table Name:TB_Employee)
ID Int (Set Identity=true and don't allow null values)
Name varchar(50)
City varchar(50)
Mob varchar(50)

Asp.Net Web Service Application:
Now In the Microsoft Visual Studio

Open visual studio -> Select File -> New -> Web Site -> select ASP.NET Web Service
 
Now open  Service.cs file in App_Code folder to write the code to get the user details from the 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;
 
Now Add below Method in the Service.cs File 

 [WebMethod]
  public XmlElement GetEmployeeDetails(string name)
   {
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dbconnection"].ToString());con.Open();
 string query = "select * from [Tb_Employee] where Name like @name+'%'";
 SqlCommand cmd = new SqlCommand(query, con);
 cmd.Parameters.AddWithValue("@name", name);
 SqlDataAdapter da = new SqlDataAdapter();
 da.SelectCommand = cmd;
 DataSet ds = new DataSet();
 da.Fill(ds);
 con.Close();
 XmlDataDocument xmldata = new XmlDataDocument(ds);
  XmlElement xmlele = xmldata.DocumentElement;
  return xmlele;
   }
 
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=USER\SQLEXPRESS; Integrated Security=True; Initial Catalog=Practice"/>
  </connectionStrings>
 
 
Now our Web Service Application is ready to use and Lets See how to use web service in an web application.
 
Open visual studio -> Select File -> New -> Web Site -> select ASP.NET Web Site
 
 Asp.Net Web Site :
 
After creation of new website right click on solution explorer and choose “Add web reference” 
then give our URL of the web service in the search text box And Click the Add Reference.
 
Now our Default.aspx should be like this: 
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Getting Data from WebService</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<b>Enter UserName:</b>
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvUserDetails" runat="server" EmptyDataText="No Record Found">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
 
Default.aspx.cs 
 
 
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            bindemployee("");
        }

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        bindemployee(txtUserName.Text);
    }

    protected void bindemployee(string username)
    {
        localhost.Service objectemp = new localhost.Service();
        DataSet ds = new DataSet();
        XmlElement xmlele = objectemp.GetEmployeeDetails(username);
        if (xmlele != null)
        {
            XmlNodeReader xmln = new XmlNodeReader(xmlele);
            ds.ReadXml(xmln, XmlReadMode.Auto);
            gvUserDetails.DataSource = ds;
            gvUserDetails.DataBind();

        }
        else
        {
            gvUserDetails.DataSource = null;
            gvUserDetails.DataBind();
        }
       
      
    }
}

 


 
 



 
 
 
 






No comments:

Post a Comment