Home > DeveloperSection > Beginner > Web Services in .NET

Web Services in .NET


.NET C#  ASP.Net  Web Services 
Ratings:
0 Comment(s)
 1395  View(s)
Rate this:

Web Services in .NET

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]

    public class WebService : System.Web.Services.WebService

    {

        SqlConnection constr = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);

        SqlCommand cmd;

        DataTable dt;

//Method for update record

        [WebMethod]

        public string UpdateRecord(string studentID, string FirstName, string LastName, string DOB, string Age, int Qualification, string Date, string EmailID)

        {

            cmd = new SqlCommand();

            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]

        public string DeleteRecord(int studentID)

        {

            cmd = new SqlCommand();

            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]

        public Info GetStudentDetail(int studentID)

        {

            cmd = new SqlCommand();

            dt = new DataTable();

            List<Info> list = new List<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 = new Info(dr);

                list.Add(info);

            }

 

            constr.Close();

            return list.FirstOrDefault();

        }

//method for insertion

        [WebMethod]

        public string Insert(string FirstName, string LastName, string DOB, string Age, int Qualification, string Date, string EmailID)

        {

            cmd = new SqlCommand();

            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]

        public List<Info> GetData(string RecordsLimit)

        {

            cmd = new SqlCommand(); ;

            dt = new DataTable();

            List<Info> list = new List<Info>();

            try

            {

                cmd.Connection = constr;

                constr.Open();

                cmd.CommandText = "ProcGetData";

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(new SqlParameter("@PageLimit", Convert.ToInt32(RecordsLimit)));

                var data = cmd.ExecuteReader();

                dt.Load(data);

                Info info;

                foreach (DataRow dr in dt.Rows)

                {

                    info = new Info(dr);

                    list.Add(info);

                }

 

            }

            catch (Exception ex)

            {

            }

            finally

            {

                constr.Close();

            }

            return list.ToList();

        }

//generate qualification

 

        [WebMethod]

        public List<Tuple<int, string>> GetQualification()

        {

            List<Tuple<int, string>> list = new List<Tuple<int, string>>();

            dt = new DataTable();

            cmd = new SqlCommand();

            cmd.Connection = constr;

            constr.Open();

            cmd.CommandText = "procQualification";

            cmd.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(dt);

            constr.Close();

            foreach (DataRow dr in dt.Rows)

            {

                list.Add(new Tuple<int, string>(Convert.ToInt32(dr["QualificationID"]), dr["QualificationName"].ToString()));

            }

            return list;

 

        }

    }

 

//properties

 

    public class Info

    {

        public int StudentID { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string DOB { get; set; }

        public string Age { get; set; }

        public string Qualification { get; set; }

        public string Date { get; set; }

        public string 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>

      <compilation debug="true" targetFramework="4.5" />

      <httpRuntime targetFramework="4.5" />

    </system.web>

  <appSettings>

    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/>

  </appSettings>

  <connectionStrings>

    <add name="conString"   connectionString="data source=servername;initial catalog=databaseName; UID=username; Password=password" providerName="System.Data.SqlClient"/>

  </connectionStrings>

 

</configuration>

 

2. Create a studentInformation.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="StudentInformation.aspx.cs" Inherits="StudentManagementSystem.StudentInformation" %>

 

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

    <script src="js/jquery-2.1.3.js"></script>

    <script src="js/bootstrap.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.1/js/bootstrap-datepicker.min.js"></script>

    <link href="css/bootstrap.min.css" rel="stylesheet" />

    <script src="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();

                    return false;

                }

            }

            if (Firstname.value == "") {

                Firstname.focus();

                return false;

            }

            if (LastName.value == "") {

                LastName.focus();

                return false;

            }

            if (DOB.value == "") {

                DOB.focus();

                return false;

            }

 

 

            if (Age.value == "") {

                Age.focus();

                return false;

            }

 

            if (Email.value == "") {

                //alert("Enter Email");

                Email.focus();

                return false;

            }

            if (Date.value == "") {

                //alert("Enter Email");

                Date.focus();

                return false;

            }

 

            var em = Email.value;

            var EmailmatchArray = em.match(emailPat);

            if (EmailmatchArray == null) {

                Email.focus();

                alert("Your email address seems incorrect. Please try again.");

                return false;

            }

 

            return true;

        }

//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:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

 

    <div class="container">

        <div class="row well well-sm">

            <div class="col-md-4">

 

                <asp:DropDownList ID="selectOption" runat="server" CssClass="form-control" ClientIDMode="Static">

                    <asp:ListItem Text="5" Value="5"></asp:ListItem>

                    <asp:ListItem Text="10" Value="10"></asp:ListItem>

                    <asp:ListItem Text="20" Value="20"></asp:ListItem>

                </asp:DropDownList>

            </div>

            <div class="col-md-6">

                <asp:TextBox ID="txtSearch" Text="Enter Student Id" ClientIDMode="Static" runat="server" CssClass="form-control"></asp:TextBox>

 

            </div>

            <div class="col-md-2">

                <input type="button" class="form-control" id="btnAdd" value="+" />

            </div>

        </div>

    </div>

 

 

    <div class="modal fade" id="dia" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

        <div class="modal-dialog">

            <div class="modal-content">

                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

                    <h4 class=" -title" id="exampleModalLabel">New Student</h4>

                </div>

                <div class="modal-body">

                    <form method="post" id="frmStudent">

                        <div class="form-group">

                            <label for="recipient-name" class="control-label">Student ID</label>

                            <asp:TextBox ID="txtStId" ClientIDMode="Static" runat="server" CssClass="form-control" Enabled="false"></asp:TextBox>

                        </div>

                        <div class="form-group">

                            <label for="recipient-name" class="control-label">First Name</label>

                            <asp:TextBox ID="txtFirstName" ClientIDMode="Static" runat="server" required="required" CssClass="form-control"></asp:TextBox>

 

                        </div>

                        <div class="form-group">

                            <label for="recipient-name" class="control-label">Last Name</label>

                            <asp:TextBox ID="txtLastName" runat="server" ClientIDMode="Static" required="required" CssClass="form-control"></asp:TextBox>

 

                        </div>

                        <div class="form-group">

                            <label for="recipient-name" class="control-label ">Date of Birth</label>

 

                            <asp:TextBox ID="txtDOB" runat="server" ClientIDMode="Static" CssClass="form-control datepicker" required="required"></asp:TextBox>

 

                        </div>

                        <div class="form-group">

                            <label for="recipient-name" class="control-label">Age</label>

 

                            <asp:TextBox ID="txtAge" runat="server" ClientIDMode="Static" CssClass="form-control" required="required"></asp:TextBox>

 

                        </div>

                        <div class="form-group">

                            <label for="recipient-name" class="control-label">Qualification</label>

 

                            <select id="drplist" class="form-control">

                            </select>

 

                            <div class="form-group">

                                <label for="recipient-name" class="control-label">Date</label>

                                <asp:TextBox ID="txtDate" runat="server" CssClass="form-control datepicker" ClientIDMode="Static" required="required"></asp:TextBox>

 

                            </div>

                            <div class="form-group">

                                <label for="recipient-name" class="control-label">EmailID</label>

                                <asp:TextBox ID="txtEmailID" runat="server" CssClass="form-control" ClientIDMode="Static" required="required"></asp:TextBox>

 

                            </div>

                        </div>

                    </form>

                </div>

                <div class="modal-footer">

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

 

                    <input type="button" id="btnAddOp" value="Add" class="btn btn-primary" />

                </div>

            </div>

        </div>

    </div>

    <div class="container">

 

        <table id="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:

Click on Add button

 

 

Click on Edit Button for Updation


Don't want to miss updates? Please click the below button!

Follow MindStick