articles

Home / DeveloperSection / Articles / Web Services in .NET

Web Services in .NET

priyanka kushwaha5175 25-Feb-2015

In this article, I’m explaining about web Services in SQL


A Web Service is an interface that describes a collection of operations that are network-accessible through standardized XML messaging. A Web service is described using a standard, formal XML nation, called its service description. It covers all the details necessary to interact with the service. Include message formats, transport protocols and location. The interface hides the implementation details of the service, allow it to be used independently of the hardware or software platform on which it is implemented and also independently of the programming language in which it is written. This allows and encourages web services-based applications to be loosely coupled, component-oriented, cross-technology implementations. Web services fulfill a specific task or a set of tasks. They can be used alone or with other web services to carry out a complex aggregation or a business transaction.

Web services Development Lifecycle

The web service development lifecycle includes the design, deployment and runtime requirements for each of the roles: service registry, service provider and service requestor. Each role has specific requirements for each element of the development lifecycle.

The development lifecycle can have four phase:

1.       Build

The build phase of the life cycle includes development and testing of the web service implementation, the definition of the service interface description and definition of the service implementation         description. Web service implementations  can be provided by creating new  web services,transforming existing applications into Web Services, and composing new Web Services from other Web Services and applications.

2.       Deploy

The deploy phase includes the publication of the service interface and service implementation definition to a service requestor or service registry and deployment of the executables for the Web service into an execution environment. 

3.       Run

During the run phase, the Web service is available for invocation. At this point, the Web

service is fully deployed, operational and network-accessible from the service provider. Now

the service requestor can perform the find and bind operations. 


4.       Manage

The manage phase covers ongoing management and administration of the Web service

application. Security, availability, performance, quality of service and business processes

must all be addressed. 

SOAP and  WSDL 

SOAP(Simple object Access Protocol): SOAP is an XML that describes the parameters that you  pass to the programs that you call. When calling a web service, there are two soap documents-

an input document that you send to the programs you are calling, and an output document that gets  sent back to you.

The format of a SOAP message can be determined from another XML document called a WSDL document. 

WSDL(Web services Description language):

A WSDL document will describe the different “program you can call”, as well as the parameters that need to be passed to those operations.

Example:

Create a webService WebService.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.IO;
 
namespace StudentManagementSystem
{
    ///<summary>
    /// Summary description for WebService
    ///</summary>
    ///
 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    publicclassWebService : System.Web.Services.WebService
    {
        SqlConnection constr = newSqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
        SqlCommand cmd;
        DataTable dt;
//Method for update record
        [WebMethod]
        publicstring UpdateRecord(string studentID, string FirstName, string LastName, string DOB, string Age, int Qualification, string Date, string EmailID)
        {
            cmd = newSqlCommand();
            int res = 0;
            try
            {
                cmd.Connection = constr;
                constr.Open();
                cmd.CommandText = "procUpdateDetail";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@studentId", Convert.ToInt32(studentID));
                cmd.Parameters.AddWithValue("@FirstName", FirstName);
                cmd.Parameters.AddWithValue("@LastName", LastName);
                cmd.Parameters.AddWithValue("@DOB", DOB);
                cmd.Parameters.AddWithValue("@Age", Age);
                cmd.Parameters.AddWithValue("@Qualification", Qualification);
                cmd.Parameters.AddWithValue("@Date", Date);
                cmd.Parameters.AddWithValue("@EmailID", EmailID);
 
                res = cmd.ExecuteNonQuery();
 
            }
            catch (Exception ex)
            {
            }
            finally
            {
                constr.Close();
            }
            if (res > 0)
                return"true";
            else
                return"false";
        }
//Method for Delete student record
 
        [WebMethod]
        publicstring DeleteRecord(int studentID)
        {
            cmd = newSqlCommand();
            int res = 0;
            try
            {
                cmd.Connection = constr;
                constr.Open();
                cmd.CommandText = "procDeleteDetail";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@studentId", Convert.ToInt32(studentID));
                res = cmd.ExecuteNonQuery();
 
            }
            catch (Exception ex)
            {
            }
            finally
            {
                constr.Close();
            }
            if (res > 0)
                return"true";
            else
                return"false";
        }
//generate a student records
 
        [WebMethod]
        publicInfo GetStudentDetail(int studentID)
        {
            cmd = newSqlCommand();
            dt = newDataTable();
            List<Info> list = newList<Info>();
            cmd.Connection = constr;
            constr.Open();
            cmd.CommandText = "GetStudentDetail";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@StudentID", studentID);
            var reader = cmd.ExecuteReader();
            dt.Load(reader);
            Info info;
            foreach (DataRow dr in dt.Rows)
            {
                info = newInfo(dr);
                list.Add(info);
            }
 
            constr.Close();
            return list.FirstOrDefault();
        }
//method for insertion
        [WebMethod]
        publicstring Insert(string FirstName, string LastName, string DOB, string Age, int Qualification, string Date, string EmailID)
        {
            cmd = newSqlCommand();
            int res = 0;
            try
            {
                cmd.Connection = constr;
                constr.Open();
                cmd.CommandText = "ProcInsertStudent";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@FirstName", FirstName);
                cmd.Parameters.AddWithValue("@LastName", LastName);
                cmd.Parameters.AddWithValue("@DOB", DOB);
                cmd.Parameters.AddWithValue("@Age", Age);
                cmd.Parameters.AddWithValue("@Qualification", Qualification);
                cmd.Parameters.AddWithValue("@Date", Date);
                cmd.Parameters.AddWithValue("@EmailID", EmailID);
                res = cmd.ExecuteNonQuery();
 
            }
            catch (Exception ex)
            {
            }
            finally
            {
                constr.Close();
            }
            if (res > 0)
                return"True";
            else
                return"false";
 
        }
//generate student records within limit
 
        [WebMethod]
        publicList<Info> GetData(string RecordsLimit)
        {
            cmd = newSqlCommand(); ;
            dt = newDataTable();
            List<Info> list = newList<Info>();
            try
            {
                cmd.Connection = constr;
                constr.Open();
                cmd.CommandText = "ProcGetData";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(newSqlParameter("@PageLimit", Convert.ToInt32(RecordsLimit)));
                var data = cmd.ExecuteReader();
                dt.Load(data);
                Info info;
                foreach (DataRow dr in dt.Rows)
                {
                    info = newInfo(dr);
                    list.Add(info);
                }
 
            }
            catch (Exception ex)
            {
            }
            finally
            {
                constr.Close();
            }
            return list.ToList();
        }
//generate qualification
 
        [WebMethod]
        publicList<Tuple<int, string>> GetQualification()
        {
            List<Tuple<int, string>> list = newList<Tuple<int, string>>();
            dt = newDataTable();
            cmd = newSqlCommand();
            cmd.Connection = constr;
            constr.Open();
            cmd.CommandText = "procQualification";
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = newSqlDataAdapter(cmd);
            da.Fill(dt);
            constr.Close();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(newTuple<int, string>(Convert.ToInt32(dr["QualificationID"]), dr["QualificationName"].ToString()));
            }
            return list;
 
        }
    }
 
//properties
 
    publicclassInfo
    {
        publicint StudentID { get; set; }
        publicstring FirstName { get; set; }
        publicstring LastName { get; set; }
        publicstring DOB { get; set; }
        publicstring Age { get; set; }
        publicstring Qualification { get; set; }
        publicstring Date { get; set; }
        publicstring EmailID { get; set; }
        public Info(DataRow dr)
        {
            this.StudentID = (int)dr["StudentID"];
            this.FirstName = (string)dr["FirstName"];
            this.LastName = (string)dr["LastName"];
            this.DOB = (string)dr["DOB"];
            this.Age = (string)dr["Age"];
            this.Qualification = (string)dr["QualificationName"];
            this.Date = (string)dr["Date"];
            this.EmailID = (string)dr["EmailID"];
          }
 
    }
 
}

1. Write in web.config 

<configuration>
    <configSections>
    </configSections>
    <system.web>
      <compilationdebug="true"targetFramework="4.5" />
      <httpRuntimetargetFramework="4.5" />
    </system.web>
  <appSettings>
    <addkey="ValidationSettings:UnobtrusiveValidationMode"value="None"/>
  </appSettings>
  <connectionStrings>
    <addname="conString"   connectionString="data source=servername;initial catalog=databaseName; UID=username; Password=password"providerName="System.Data.SqlClient"/>
  </connectionStrings>
 
</configuration> 

2. Create a studentInformation.aspx


<%@PageTitle=""Language="C#"MasterPageFile="~/MasterPage.Master"AutoEventWireup="true"CodeBehind="StudentInformation.aspx.cs"Inherits="StudentManagementSystem.StudentInformation"%>
 
<asp:ContentID="Content1"ContentPlaceHolderID="head"runat="server">
    <scriptsrc="js/jquery-2.1.3.js"></script>
    <scriptsrc="js/bootstrap.min.js"></script>
    <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.1/js/bootstrap-datepicker.min.js"></script>
    <linkhref="css/bootstrap.min.css"rel="stylesheet"/>
    <scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.1/css/datepicker.css"></script>
 
<script>
//validation
 
        function validate() {
            var Firstname = document.getElementById('<%=txtFirstName.ClientID %>');
            var LastName = document.getElementById('<%=txtLastName.ClientID %>');
            var Email = document.getElementById('<%=txtEmailID.ClientID %>');
            var Age = document.getElementById('<%=txtAge.ClientID %>');
 
            var DOB = document.getElementById('<%=txtDOB.ClientID %>');
            var Date = document.getElementById('<%=txtDate.ClientID %>');
            var emailPat = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
            var digits = "0123456789";
            var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; /^\d{2}-\d{2}-\d{4}$/;
            var temp;
 
            for (var i = 0; i < Age.value.length; i++) {
                temp = Age.value.substring(i, i + 1);
                if (digits.indexOf(temp) == -1) {
                    alert("Please enter correct age code");
                    Age.focus();
                    returnfalse;
                }
            }
            if (Firstname.value == "") {
                Firstname.focus();
                returnfalse;
            }
            if (LastName.value == "") {
                LastName.focus();
                returnfalse;
            }
            if (DOB.value == "") {
                DOB.focus();
                returnfalse;
            }
 
 
            if (Age.value == "") {
                Age.focus();
                returnfalse;
            }
 
            if (Email.value == "") {
                //alert("Enter Email");
                Email.focus();
                returnfalse;
            }
            if (Date.value == "") {
                //alert("Enter Email");
                Date.focus();
                returnfalse;
            }
 
            var em = Email.value;
            var EmailmatchArray = em.match(emailPat);
            if (EmailmatchArray == null) {
                Email.focus();
                alert("Your email address seems incorrect. Please try again.");
                returnfalse;
            }
 
            returntrue;
        }
//Clear function
        function clear() {
            $('#txtStId').val('');
            $('#txtFirstName').val('');
            $('#txtLastName').val('');
            $('#txtDOB').val('');
            $('#txtAge').val('');
            $('#txtQualification').val('');
            $('#txtDate').val('');
            $('#txtEmailID').val('');
            $('#btnAddOp').val('Add');
 
        }
//bind data in fropdownlist
 
        function bindDropdlist() {
 
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebService.asmx/GetQualification",
                dataType: "json",
                success: function (Result) {
                    Result = Result.d;
                    $.each(Result, function (key, value) {
                        $("#drplist").append($("<option></option>").val(value.Item1).html(value.Item2));
                    });
 
                }
            });
 
        }
//show a student record in mode popup
 
        function edit(stuid) {
 
            $.ajax(
                          {
                              type: "POST",
                              contentType: "application/json; charset=utf-8",
                              url: "WebService.asmx/GetStudentDetail",
                              data: "{studentID:'" + stuid + "'}",
                              dataType: "json",
                              success: function (response) {
 
                                  $("#txtStId").val(response.d.StudentID);
                                  $("#txtFirstName").val(response.d.FirstName);
                                  $("#txtLastName").val(response.d.LastName);
                                  $("#txtDOB").val(response.d.DOB);
                                  $("#txtAge").val(response.d.Age);
                                  $("#txtQualification").val(response.d.Qualification);
                                  $("#txtDate").val(response.d.Date);
                                  $("#txtEmailID").val(response.d.EmailID);
                                  $("#btnAddOp").val('Update');
                                  $('#dia').modal('show');
                              }
                          }
                          )
        }
 
//call deleted function
 
        function deletefun(stuid) {
            if (confirm("You want to delete your record")) {
                $.ajax(
                     {
                         type: "POST",
                         contentType: "application/json; charset=utf-8",
                         url: "WebService.asmx/DeleteRecord",
                         data: "{studentID:'" + stuid + "'}",
                         dataType: "json",
                         success: function (response) {
                             if (response.d == "true") {
                                 alert("Successfully deleted");
                                 bindgrid();
                             }
                             else
                                 alert("fail");
                         }
                     }
                     )
            }
        }
//call GetData() and show all student record in
 
        function bindgrid() {
            $("#tbDetails").find("tr:gt(0)").remove();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebService.asmx/GetData",
                data: "{RecordsLimit:'" + $('#selectOption').val() + "'}",
                dataType: "json",
                success: function (response) {
                    for (var j = 0; j < response.d.length ; j++) {
                        $("#tbDetails").append("<tr><td>" + response.d[j].StudentID + "</td><td>" + response.d[j].FirstName + "</td><td>" + response.d[j].LastName
                            + "</td><td>" + response.d[j].DOB + "</td><td>" + response.d[j].Age + "</td><td>" + response.d[j].Qualification + "</td><td>" + response.d[j].Date + "</td><td>" + response.d[j].EmailID + "</td><td>" + "<input type='button' class='btn btn-primary edit' value='Edit' id='" + response.d[j].StudentID + "'></td><td><input type='button' class='btn btn-primary delete' value='Delete' id='" + response.d[j].StudentID + "'></td></tr>");
                    }
                    $('.edit').click(function () {
                        stuid = $(this).attr("id");
                        edit(stuid);
 
                    });
                    $('.delete').click(function () {
                        stuid = $(this).attr("id");
                        deletefun(stuid);
                    });
                },
                failure: function (response) {
                }
            });
        }
 
        $(function () {
 
            bindgrid();
            bindDropdlist();
            $('.datepicker').datepicker();
 
            $('#selectOption').change(function () {
                bindgrid();
            });
 
            $('#btnAddOp').click(function () {
 
                if (!validate())
                    return;
 
                if ($(this).attr("value") == "Add") {
 
                    $.ajax(
                          {
                              type: "POST",
                              contentType: "application/json; charset=utf-8",
                              url: "WebService.asmx/Insert",
                              data: "{FirstName:'" + $('#txtFirstName').val() + "',LastName:'" + $('#txtLastName').val() + "',DOB:'" + $('#txtDOB').val() + "',Age:'" + $('#txtAge').val() + "',Qualification:'" + $('#drplist').val() + "',Date:'" + $('#txtDate').val() + "',EmailID:'" + $('#txtEmailID').val() + "'}",
                              dataType: "json",
                              success: function (response) {
                                  if (response.d == "True") {
                                      alert("Sucessfully saved!");
                                      $('#txtFirstName').val('');
                                      $('#txtLastName').val('');
                                      $('#txtDOB').val('');
                                      $('#txtAge').val('');
                                      // $('#drplist').val('');
                                      $('#txtDate').val('');
                                      $('#txtEmailID').val('');
                                      bindgrid();
                                      $('#dia').modal('hide');
                                  }
                                  else {
                                      alert("failure");
                                  }
                              }
                          });
                }
 
                if ($(this).attr("value") == "Update") {
                    $.ajax(
                          {
                              type: "POST",
                              contentType: "application/json; charset=utf-8",
                              url: "WebService.asmx/UpdateRecord",
                              data: "{studentID:'" + $('#txtStId').val() + "',FirstName:'" + $('#txtFirstName').val() + "',LastName:'" + $('#txtLastName').val() + "',DOB:'" + $('#txtDOB').val() + "',Age:'" + $('#txtAge').val() + "',Qualification:'" + $('#drplist').val() + "',Date:'" + $('#txtDate').val() + "',EmailID:'" + $('#txtEmailID').val() + "'}",
                              dataType: "json",
                              success: function (response) {
                                  if (response.d == "   ") {
                                      alert("Sucessfully Update!");
                                      bindgrid();
                                      $('#dia').modal('hide');
                                  }
                                  else {
                                      alert("failure");
                                  }
                              }
                          });
                }
            });
 
            $('#btnAdd').click(function () {
                $('#txtFirstName').val('');
                $('#txtLastName').val('');
                $('#txtDOB').val('');
                $('#txtAge').val('');
                $('#drplist').val('');
                $('#txtDate').val('');
                $('#txtEmailID').val('');
                $('#btnAddOp').val('Add');
                $('#dia').modal('show');
            });
            $('#btnSearch').click(function () {
                $('#SearchModel').modal('show');
            }
         );
            $('#txtSearch').change(function () {
                var stuid = $('#txtSearch').val();
                $('#tbDetails').find("tr:gt(0)").remove();
                if (stuid != "") {
                    $.ajax(
                           {
                               type: "POST",
                               contentType: "application/json; charset=utf-8",
                               url: "WebService.asmx/GetStudentDetail",
                               data: "{studentID:'" + stuid + "'}",
                               dataType: "json",
                               success: function (response) {
                                   $("#tbDetails").append("<tr><td>" + response.d.StudentID + "</td><td>" + response.d.FirstName + "</td><td>" + response.d.LastName
                                   + "</td><td>" + response.d.DOB + "</td><td>" + response.d.Age + "</td><td>" + response.d.Qualification + "</td><td>" + response.d.Date + "</td><td>" + response.d.EmailID + "</td><td>" + "<input type='button' class='btn btn-primary edit' value='Edit' id='" + response.d.StudentID + "'></td><td><input type='button' class='btn btn-primary delete' value='Delete' id='" + response.d.StudentID + "'></td></tr>");
 
                                   $('.edit').click(function () {
                                      stuid = $(this).attr("id");
                                       edit(stuid);
 
                                   });
                                   $('.delete').click(function () {
                                    stuid = $(this).attr("id");
                                       deletefun(stuid);
                                   });
                               }
                           }
                           );
 
                }
                else {
                    bindgrid();
                }
 
 
            }
           );
 
        });
 
    </script>
</asp:Content>
<asp:ContentID="Content2"ContentPlaceHolderID="ContentPlaceHolder1"runat="server">
 
    <divclass="container">
        <divclass="row well well-sm">
            <divclass="col-md-4">
 
                <asp:DropDownListID="selectOption"runat="server"CssClass="form-control"ClientIDMode="Static">
                    <asp:ListItemText="5"Value="5"></asp:ListItem>
                    <asp:ListItemText="10"Value="10"></asp:ListItem>
                    <asp:ListItemText="20"Value="20"></asp:ListItem>
                </asp:DropDownList>
            </div>
            <divclass="col-md-6">
                <asp:TextBoxID="txtSearch"Text="Enter Student Id"ClientIDMode="Static"runat="server"CssClass="form-control"></asp:TextBox>
 
            </div>
            <divclass="col-md-2">
                <inputtype="button"class="form-control"id="btnAdd"value="+"/>
            </div>
        </div>
    </div>
 
 
    <divclass="modal fade"id="dia"tabindex="-1"role="dialog"aria-labelledby="exampleModalLabel"aria-hidden="true">
        <divclass="modal-dialog">
            <divclass="modal-content">
                <divclass="modal-header">
                    <buttontype="button"class="close"data-dismiss="modal"aria-label="Close"><spanaria-hidden="true">&times;</span></button>
                    <h4class=" -title"id="exampleModalLabel">New Student</h4>
                </div>
                <divclass="modal-body">
                    <formmethod="post"id="frmStudent">
                        <divclass="form-group">
                            <labelfor="recipient-name"class="control-label">Student ID</label>
                            <asp:TextBoxID="txtStId"ClientIDMode="Static"runat="server"CssClass="form-control"Enabled="false"></asp:TextBox>
                        </div>
                        <divclass="form-group">
                            <labelfor="recipient-name"class="control-label">First Name</label>
                            <asp:TextBoxID="txtFirstName"ClientIDMode="Static"runat="server"required="required"CssClass="form-control"></asp:TextBox>
 
                        </div>
                        <divclass="form-group">
                            <labelfor="recipient-name"class="control-label">Last Name</label>
                            <asp:TextBoxID="txtLastName"runat="server"ClientIDMode="Static"required="required"CssClass="form-control"></asp:TextBox>
 
                        </div>
                        <divclass="form-group">
                            <labelfor="recipient-name"class="control-label ">Date of Birth</label>
 
                            <asp:TextBoxID="txtDOB"runat="server"ClientIDMode="Static"CssClass="form-control datepicker"required="required"></asp:TextBox>
 
                        </div>
                        <divclass="form-group">
                            <labelfor="recipient-name"class="control-label">Age</label>
 
                            <asp:TextBoxID="txtAge"runat="server"ClientIDMode="Static"CssClass="form-control"required="required"></asp:TextBox>
 
                        </div>
                        <divclass="form-group">
                            <labelfor="recipient-name"class="control-label">Qualification</label>
 
                            <selectid="drplist"class="form-control">
                            </select>
 
                            <divclass="form-group">
                                <labelfor="recipient-name"class="control-label">Date</label>
                                <asp:TextBoxID="txtDate"runat="server"CssClass="form-control datepicker"ClientIDMode="Static"required="required"></asp:TextBox>
 
                            </div>
                            <divclass="form-group">
                                <labelfor="recipient-name"class="control-label">EmailID</label>
                                <asp:TextBoxID="txtEmailID"runat="server"CssClass="form-control"ClientIDMode="Static"required="required"></asp:TextBox>
 
                            </div>
                        </div>
                    </form>
                </div>
                <divclass="modal-footer">
                    <buttontype="button"class="btn btn-default"data-dismiss="modal">Close</button>
 
                    <inputtype="button"id="btnAddOp"value="Add"class="btn btn-primary"/>
                </div>
            </div>
        </div>
    </div>
    <divclass="container">
 
        <tableid="tbDetails"class="table table-responsive">
            <tbody>
                <tr>
                    <th>Student Id</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>DOB</th>
                    <th>Age</th>
                    <th>Qualification</th>
                    <th>Date</th>
                    <th>Email Id</th>
                    <th>Edit</th>
                    <th>Delete</th>
                </tr>
            </tbody>
        </table>
 
    </div>
</asp:Content>

 

 

Output:

Web Services in .NET

Click on Add button


Web Services in .NET

 

 

Click on Edit Button for Updation


Web Services in .NET


Updated 15-Nov-2019

Leave Comment

Comments

Liked By