Create A Web Service

Why we need web service

Suppose, you are working as a resident software developer for any plastic product manufacturing company. Company want to share product details on web to other applications also.

Web service is XML and HTTP base protocol kind of service. Mostly it can consume by major other framework.

  1. Create a new empty web site project.

    File, Web Site, then ASP.NET Empty Web Site.

    Asp.Net Empty Web Site

    In the above screenshot we created empty web site project named MyWebService
  2. Add a new Web Service to this project by right clicking,

    WebService

    I added webservice file named ProductWebService.asmx

  3. After creating webservice the following files will get created in our project.

    1. ProductWebService.Cs : The file created with folder App_Code, means app_code folder not created in your project. Visual studio will create App_Code folder and then this file.

    2. ProductWebService.asmx: This file gets created on root of project.

    By default Visual Studio created HELLOWORLD web method. You keep this method or comment or delete from the code.

    I had removed HELLOWORLD method.

  4. Namespace required.

    Namespace Functionalities
    Using System.Xml For returning XmlElement.
    Using System.Data To get ASP.NET data handling classes.
    Using System.Data.SqlClientTo connect to Microsoft SQL server.
    Using Systen.ConfigurationTo fetch configuration and connectionstring from app.config.

    Table Structure inside MemberCDAC database, table named TBLPLASTICS

    1. USE [MemberCDAC]  
    2. GO  
    3. /****** Object:  Table [dbo].[tblProducts]    Script Date: 12/19/2015 11:09:21 ******/  
    4. SET ANSI_NULLS ON  
    5. GO  
    6. SET QUOTED_IDENTIFIER ON  
    7. GO  
    8. SET ANSI_PADDING ON  
    9. GO  
    10. CREATE TABLE [dbo].[tblProducts](  
    11.     [ProductID] [int] IDENTITY(1,1) NOT NULL,  
    12.     [ProductName] [varchar](50) NULL,  
    13.     [ProductRemarks] [varchar](500) NULL  
    14. ON [PRIMARY]  
    15.   
    16. GO  
    17. SET ANSI_PADDING OFF  
  5. Web.Config file
    1. <?xml version="1.0"?>  
    2.     <!--  
    3.     For more information on how to configure your ASP.NET application, please visit  
    4.     http://go.microsoft.com/fwlink/?LinkId=169433  
    5. -->  
    6.     <configuration>  
    7.         <system.web>  
    8.             <compilation debug="true" targetFramework="4.0" /> </system.web>  
    9.         <configuration>  
    10.             <connectionStrings>  
    11.                 <add name="MemberCDACConnectionString" connectionString="Data Source=SAIBABA-PC\SAIBABA;Initial Catalog=MemberCDAC;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>  
    12.         </configuration>  
    13.     </configuration>  
    tblProducts: table data.

    PRODUCT IDPRODUCTNAME
    1Ball Pen
    2Gel Pen
    3Ink Pen
    46B Pencil
    56C Pencil
    6Bar Mobile Dual Sim
    7Bar Mobile Three Sim
    8Jalgoan Chiiki
    9Jaipur Chaadar
    10Jalna Bhel
    11Jamshedpur Steel
    12Jamnuna Prasad

  6. ProductWebService.CS file code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Configuration;  
    4. using System.Data;  
    5. using System.Data.SqlClient;  
    6. using System.Linq;  
    7. using System.Web;  
    8. using System.Web.Services;  
    9. using System.Xml;  
    10. /// <summary>  
    11. /// Summary description for ProductWebService  
    12. /// </summary>  
    13. [WebService(Namespace = "http://tempuri.org/")]  
    14. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
    15. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
    16. // [System.Web.Script.Services.ScriptService]  
    17. public class ProductWebService: System.Web.Services.WebService  
    18. {  
    19.     //To fetch connection string from APP.CONFIG file.  
    20.     string ConStr = ConfigurationManager.ConnectionStrings["MemberCDACConnectionString"].ConnectionString;  
    21.     public ProductWebService()  
    22.     {  
    23.         //Uncomment the following line if using designed components   
    24.         //InitializeComponent();   
    25.     }  
    26.     [WebMethod]  
    27.     public XmlElement GetProductsByProductKeyWord(string ProductSearchKeyword)  
    28.     {  
    29.         //Set connection which feteched from app.config.  
    30.         SqlConnection con = new SqlConnection(ConStr);  
    31.         //SELECT query to fetch data from ProductsTable  
    32.         SqlDataAdapter da = new SqlDataAdapter("Select ProductName From tblProducts Where ProductName Like '%" + ProductSearchKeyword + "%'", ConStr);  
    33.         //DataSet is virutual database or data container.  
    34.         DataSet ds = new DataSet();  
    35.         //Fill data inside ds(DataSet) with TableNamed ProductsTable  
    36.         da.Fill(ds, "ProductTable");  
    37.         //Convert data result set into xmlelement.  
    38.         XmlDataDocument _xmldata = new XmlDataDocument(ds);  
    39.         XmlElement _xmlElement = _xmldata.DocumentElement;  
    40.         return _xmlElement;  
    41.     }  
    42. }  
  7. Press F5 To check Web Service.

    ProductsByProductKey

    Now click on our WebMethod named GetProductsByProductKeyWord

  8. As you click on WebMethod GetProductsByProductKeyWord.

    GetProductsByProductKeyWord

    In this screen you have to enter search product name.

    I am going to search PEN, so type PEN and click on INVOKE button.

    search PEN typed

    I had searched PEN and here's the WebService result.
    1. <?xml version="1.0" encoding="utf-8" ?> -  
    2.     <NewDataSet> -  
    3.         <ProductTable>  
    4.             <ProductName>Ball Pen</ProductName>  
    5.         </ProductTable> -  
    6.         <ProductTable>  
    7.             <ProductName>Gel Pen</ProductName>  
    8.         </ProductTable> -  
    9.         <ProductTable>  
    10.             <ProductName>Ink Pen</ProductName>  
    11.         </ProductTable> -  
    12.         <ProductTable>  
    13.             <ProductName>6B Pencil</ProductName>  
    14.         </ProductTable> -  
    15.         <ProductTable>  
    16.             <ProductName>6C Pencil</ProductName>  
    17.         </ProductTable>  
    18.     </NewDataSet>  
    Now I am going to implement this web service into our aspx page.

  9. Create a new Web Page on same project.

    Right click on project and add new item then select Web Form from list.

    Web form

  10. Namespace required.

    Namespace Functionalities
    Using System.DataTo get ADO.NET data handling classes.
    Using System.Data.SqlClient To connect to Microsoft SQL server.
    Using Systen.ConfigurationTo fetch configuration and connectionstring from app.config.

    Note: Don’t forget to give reference of web service to project.

    Here I had given reference and named MYWebServiceReference.

    In Default.aspx.cs I had uses reference of MYWebServiceReference and create instance of SOAPCLIENT and uses method of webservice named GetProductsByProductKeyWord.

  11. Now switch back to DEFAULT.ASPX page, drag and drop HTML TABLE from toolbox.

    Note: HTML tool box of controls located at bottom of toolbox.

    Add the following controls as per charts.

    CONTROL TYPECONTROL ID DESCRIPTION
    TextBox txtProductSearchKeyword To enter Product to search.
    Button btnSubmit Text = “Search Product”
    Button to submit data.
    GridView ProductsGridView Gridview to display data.
    Set following settings from properties:
    Width="100%"

    Drag and Drop above mentioned controls from toolbox after html table.

  12. After drag and drop grid view, click smart tag of Gridview and select AUTO FORMAT.

    WebForm from list

  13. Default.aspx file code,
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
    2.     <!DOCTYPE html>  
    3.     <html xmlns="http://www.w3.org/1999/xhtml">  
    4.   
    5.     <head runat="server">  
    6.         <title></title>  
    7.         <style type="text/css">  
    8. .auto-style1 {  
    9.     width: 226px;  
    10. }  
    11.         </style>  
    12.     </head>  
    13.   
    14.     <body>  
    15.         <form id="form1" runat="server">  
    16.             <div>  
    17.                 <table style="width: 100%;">  
    18.                     <tr>  
    19.                         <td class="auto-style1"></td>  
    20.                         <td></td>  
    21.                         <td></td>  
    22.                     </tr>  
    23.                     <tr>  
    24.                         <td class="auto-style1" style="text-align: right">Search Product  :    </td>  
    25.                         <td>  
    26.                             <asp:TextBox ID="txtProductSearchKeyword" runat="server" Width="286px"></asp:TextBox>  
    27.                         </td>  
    28.                         <td> </td>  
    29.                     </tr>  
    30.                     <tr>  
    31.                         <td colspan="2">                                          
    32.                             <asp:Button ID="btnSubmit" runat="server" Text="Search Product" sytle="padding-left:120px" Width="194px" onclick="btnSubmit_Click" /> </td>  
    33.                         <td> </td>  
    34.                     </tr>  
    35.                     <tr>  
    36.                         <td colspan="2">  
    37.                             <asp:GridView ID="ProductsGridView" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">  
    38.                                 <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />  
    39.                                 <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />  
    40.                                 <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />  
    41.                                 <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />  
    42.                                 <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> </asp:GridView>  
    43.                         </td>  
    44.                         <td> </td>  
    45.                     </tr>  
    46.                 </table>  
    47.             </div>  
    48.         </form>  
    49.     </body>  
    50.   
    51. </html>  
  14. Default.aspx.cs file code,
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.UI;  
    6. using System.Web.UI.WebControls;  
    7. using System.Data;  
    8. using System.Data.SqlClient;  
    9. using System.Configuration;  
    10. using MYWebServiceReference;  
    11. using System.Xml;  
    12. public partial class _Default: System.Web.UI.Page  
    13. {  
    14.     protected void Page_Load(object sender, EventArgs e)  
    15.     {  
    16.         if (!IsPostBack)  
    17.         {  
    18.             //By default gridview should not default any record that why used NULL   
    19.             SearchProducts("NULL");  
    20.         }  
    21.     }  
    22.     protected void SearchProducts(string SearchProductKeyWords)  
    23.     {  
    24.         //Uses the reference of MYWebServiceReference and create Instace of SoapClient then used web method.  
    25.         MYWebServiceReference.ProductWebServiceSoapClient serviceRef = new MYWebServiceReference.ProductWebServiceSoapClient();  
    26.         DataSet ds = new DataSet();  
    27.         XmlElement exelement = serviceRef.GetProductsByProductKeyWord(SearchProductKeyWords);  
    28.         if (exelement != null)  
    29.         {  
    30.             XmlNodeReader nodereader = new XmlNodeReader(exelement);  
    31.             ds.ReadXml(nodereader, XmlReadMode.Auto);  
    32.             ProductsGridView.DataSource = ds;  
    33.             ProductsGridView.DataBind();  
    34.         }  
    35.         else  
    36.         {  
    37.             ProductsGridView.DataSource = null;  
    38.             ProductsGridView.DataBind();  
    39.         }  
    40.     }  
    41.     protected void btnSubmit_Click(object sender, EventArgs e)  
    42.     {  
    43.         SearchProducts(txtProductSearchKeyword.Text);  
    44.     }  
    45. }  
  15. After pressing F5 on default.aspx, the screen will look like the following,

    AUTO FORMAT

  16. Type PEN in textbox and click on Search Product button.

    SEARCH PRODUCT button

  17. Result

    RESULT

Thank You, Task completed.

Up Next
    Ebook Download
    View all
    Learn
    View all