Quickly Mastering: Create And Use Asp .Net Web Service From Basic, Database Access To Ajax-Enabled

Description

Web services are components on a Web server that a client application can call by making HTTP requests across the Web. ASP.NET enables you to create custom Web services or to use built-in application services, and to call these services from any client application
Source: http://msdn.microsoft.com/en-us/library/t745kdsh.aspx

Web Services are an integral part of the .NET framework that provide a cross-platform solution for exchanging data between distributed systems. Although Web Services are normally used to allow different operating systems, object models and programming languages to send and receive data, they can also be used to dynamically inject data into an ASP.NET AJAX page or send data from a page to a back-end system. All of this can be done without resorting to postback operations.
Source: http://www.asp.net/web-forms/tutorials/aspnet-ajax/understanding-asp-net-ajax-web-services

Web Service In Code

Web Service in Asp .Net is an object that can be accessed in the same way as a class.
Website project must add Web reference to a WebService’s Url address so that the website can access it.
In code point of view, writing access to WebService is same as accessing a regular class in Asp .Net. This regular class usually located in App_Code folder.
WebService located at a web server and reference it through http protocol.

Inside WebService code file is a class and its member. We can put class member, properties and methods in WebService. We can build WebService to operate with files, database etc

Examples

WebService Basic

  1. Create an Empty Website
  2. Add new WebForm (Basic.aspx) and write below code:
    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Basic.aspx.vb" Inherits="Basic" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        Write your name: <asp:TextBox ID="myname" runat="server"></asp:TextBox> &nbsp;
        <asp:Button ID="btn" runat="server" Text="Say Hello!" /><br />
    
        <asp:Label ID="lblmsg" runat="server"></asp:Label>
        </div>
        </form>
    </body>
    </html>
    

    We have one textbox and button to say ‘Hello’ on lblmsg label depends on textbox user input. We will make webService to create the hello message.

  3. Add New Item to Solution and choose WebService. Name it as Hello.asmx 

    VS will create two files which are Hello.asmx and Hello.vb under ‘App_Code’ folder

  4. Open Hello.vb and write below code:
    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    
    ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    ' <System.Web.Script.Services.ScriptService()> _
    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
    Public Class Hello
         Inherits System.Web.Services.WebService
    
        <WebMethod()> _
        Public Function SayHello(ByVal myname As String) As String
            Return "Hello " & myname
        End Function
    End Class
    

    We have Hello Class and I write SayHello function to return Hello message.

  5. Right Click Solution, Add Web Reference, and click WebService in this Solution
  6. Choose Hello (WebService that I previously created) and change the Web Reference name to HelloWS  
    Hello WebService already added to Web Project Solution.
  7. Edit Basic.aspx code file (Basic.aspx.vb):
    Partial Class Basic
        Inherits System.Web.UI.Page
    
        Protected Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn.Click
            Dim hlo As New HelloWS.Hello()
            lblmsg.Text = hlo.SayHello(myname.Text)
    
        End Sub
    End Class
    

    If user click the button then btn_Click executed. We can access Hello Class in WebService using ‘New HelloWS.Hello()’. Remember that HelloWS is a reference name we set earlier and Hello is a class inside WebService file.

  8. View Basic.aspx in browser.

Loading Database

In this example, I use AdventureWorks Database. The web page will load HumanResources.Department records.

  1. Add New Webform and name it LoadDB.aspx
    <%@ Page Language="VB" Debug="true" AutoEventWireup="false" CodeFile="LoadDB.aspx.vb" Inherits="LoadDB" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <asp:Button ID="btnloaddb" runat="server" Text="Load Departments" /><br />
        <asp:GridView ID="gvdept" runat="server" HeaderStyle-Font-Bold="true">    
        </asp:GridView>
        </div>
        </form>
    
    </body>
    </html>
    

    The file has button ‘Load Departments’ and GridView control as a data container.

  2. Add New Item -> Webservice and name it Departments.asmx. VS will create two files which are Departments.asmx and Departments.vb. Departments.vb located under ‘App_Code’ folder
  3. Edit Webservice behind code (Departments.vb):
    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    Imports System.Data
    Imports System.Data.SqlClient
    
    ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    '<System.Web.Script.Services.ScriptService()> _
    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
    Public Class Departments
        Inherits System.Web.Services.WebService
    
        <WebMethod()> _
        Public Function ShowDepartments() As DataTable
            Dim conn As New SqlConnection("Data Source=.\SQLExpress;Initial Catalog=AdventureWorks;Integrated Security=true")
            conn.Open()
    
            Dim da As New SqlDataAdapter("select * from HumanResources.Department", conn)
            Dim dt As New DataTable("Department")
            da.Fill(dt)
            conn.Close()
            Return dt
        End Function
    End Class
    

    I imports System.Data and SqlClient to operate with SQL Server Database. Records in HumanResources.Department filled inside DataTable and ShowDepartments() method return that DataTable.

  4. Click Add Web Reference and Browse To: Webservice in this solution. Change to Reference Name to DepartmentWS
  5. Edit code behind file (LoadDB.aspx.vb):
    Imports System.Data
    Partial Class LoadDB
        Inherits System.Web.UI.Page
    
        Protected Sub btnloaddb_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnloaddb.Click
            Dim dept As New DepartmentWS.Departments()
            gvdept.DataSource = dept.ShowDepartments()
    
            gvdept.DataBind()
        End Sub
    End Class
    

    Above code shows us on how to access WebService’s class and the GridView’s DataSource is DataTable returned from WebService.

  6. View LoadDB.aspx in browser 

Ajax Enabled

Ajax request calls WebService asynchronously under client script. This client script (.js) file access WebService class on server.
The web page it self do not reload but only part of it.

In basic example, we just show message from Ajax Request. This ajax calls WebService’s class

  1. Add New WebForm and name it AjaxEnabled.aspx
  2. Write code below on AjaxEnabled.aspx:
    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="AjaxEnabled.aspx.vb" Inherits="AjaxEnabled" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>       
            </Services>
            <Scripts>         
            </Scripts>
            </asp:ScriptManager>
            <input type="button" id="btnshow" value="Show Message" onclick="OnClickShowAjaxMsg()" /> &nbsp;
            <span id="result"></span><br />
           
        </div>
        </form>
    </body>
    </html>
    

    We have design form only. ScriptManager is an ajax server component. Inside ScriptManager there are Services and Scripts Tag. Now both are empty but later on Services include path of WebService and Scripts refer to path of client script .Js file to access WebService’s class.
    Button Show Message will get the Ajax message from client script. The message will print on span ‘id=result’ element

  3. Add New WebService file and name it AjaxHello.asmx. Two files are generated from VS AjaxHello.asmx and AjaxHello.asmx.vb under ‘App_code’ folder
  4. Edit AjaxHello.asmx.vb file:
    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    
    ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    <System.Web.Script.Services.ScriptService()> _
    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
    Public Class AjaxHello
        Inherits System.Web.Services.WebService
    
        Public Sub New()
    
        End Sub
        <WebMethod()> _
        Public Function SayHelloFromAjax() As String
            Return "Hello from Ajax"
        End Function
    End Class
    

    We have one function only just to say “Hello from Ajax”. Dont forget to uncomment to allow client script calls a WebService.

  5. Add Web Reference, browse this solution and click AjaxHello Web Service. Rename the Reference Name to AjaxHelloWS
  6. Add new .js file (AjaxReqs.js)
    var ajaxProxy;
    
    function pageLoad() {
        ajaxProxy = new AjaxHello();
        ajaxProxy.set_defaultSucceededCallback(SucceededCallback);
        ajaxProxy.set_defaultFailedCallback(FailedCallback);
    }
    
    // Processes the button click and calls
    // the service Greetings method.
    function OnClickShowAjaxMsg() {
        var sclock = ajaxProxy.SayHelloFromAjax();
    }
    
    // Callback function that
    // processes the service return value.
    function SucceededCallback(result) {
        var RsltElem = document.getElementById("result");
        RsltElem.innerHTML = result;
    }
    
    // Callback function invoked when a call to
    // the  service methods fails.
    function FailedCallback(error, userContext, methodName) {
        if (error !== null) {
            alert("An error occured: \n" + error.get_message());
        }
    
    }
    if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    

    pageLoad() function will load when web is loaded. We have declaration to WebService ajaxProxy = new AjaxHello();.
    ajaxProxy set its Succeeded and Failed Callback function to SucceededCallback() and FailedCallback() respectively.
    OnClickShowAjaxMsg() function executed when button ‘Show Message’ clicked. Remember we have on AjaxEnabled.aspx.
    ajaxProxy run SayHelloFromAjax(). SayHelloFromAjax() is a WebService class function on AjaxHello.asmx.vb file

  7. Complete AjaxEnabled.aspx:
    </pre>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>        
                <asp:ServiceReference Path="~/AjaxHello.asmx" /> 
            </Services>
            <Scripts>
                <asp:ScriptReference Path="~/AjaxReqs.js" />
            </Scripts>
            </asp:ScriptManager>
            <input type="button" id="btnshow" value="Show Message" onclick="OnClickShowAjaxMsg()"  /> &nbsp;
            <span id="result"></span><br />
        </div>
        </form>
    

    Now we have path of .asmx inside Services and path of .js inside Scripts.

  8. Run this aspx file 

I give you one more example to show a clock / current date time dynamically. The web page will have a simple clock that refresh every second.

  1. Add new WebService (Clock.asmx)
  2. Edit file Clock.asmx.vb under App_code folder:
    Imports System.Web
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    
    ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    <System.Web.Script.Services.ScriptService()> _
    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
    Public Class Clock
        Inherits System.Web.Services.WebService
    
        <WebMethod()> _
        Public Function ClockDateTime() As String
            Return Date.Now.ToString()
        End Function
    End Class
    

    Only one function and that returns current server’s date time.

  3. Edit AjaxReqs.js
    var ajaxProxy;
    var dynclockProxy;
    
    function pageLoad() {
        ajaxProxy = new AjaxHello();
        ajaxProxy.set_defaultSucceededCallback(SucceededCallback);
        ajaxProxy.set_defaultFailedCallback(FailedCallback);
    
        dynclockProxy = new Clock();
        dynclockProxy.set_defaultSucceededCallback(DynSucceededCallback);
        dynclockProxy.set_defaultFailedCallback(FailedCallback);
        DynClock();
    }
    
    // Processes the button click and calls
    // the service Greetings method.
    function OnClickShowAjaxMsg() {
        var sclock = ajaxProxy.SayHelloFromAjax();
    }
    
    // Callback function that
    // processes the service return value.
    function SucceededCallback(result) {
        var RsltElem = document.getElementById("result");
        RsltElem.innerHTML = result;
    }
    
    // Callback function invoked when a call to
    // the  service methods fails.
    function FailedCallback(error, userContext, methodName) {
        if (error !== null) {
            alert("An error occured: \n" + error.get_message());
        }
    
    }
    
    function ShowDynClock() {
        var sclock = dynclockProxy.ClockDateTime();
    }
    function DynClock() {
        setInterval("ShowDynClock()", 1000);
    }
    
    // Callback function that
    // processes the service return value.
    function DynSucceededCallback(result) {
        var RsltElem = document.getElementById("result_dyn");
        RsltElem.innerHTML = result;
    }
    
    if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    

    We have dynclockProxy = new Clock(); to access WebService’s class. ShowDynClock() function to show current date time via class function ClockDateTime().
    Also we have DynClock() function that execute ShowDynClock() every second with setInterval("ShowDynClock()", 1000);.
    This DynClock() function executed on pageLoad() so that it is running if web page load or refresh.

  4. Edit AjaxEnabled.aspx
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>        
                <asp:ServiceReference Path="~/AjaxHello.asmx" />
                <asp:ServiceReference Path="~/Clock.asmx" />  
            </Services>
            <Scripts>
                <asp:ScriptReference Path="~/AjaxReqs.js" />
            </Scripts>
            </asp:ScriptManager>
            <input type="button" id="btnshow" value="Show Message" onclick="OnClickShowAjaxMsg()"  /> &nbsp;
            <span id="result"></span><br /><br />      
            <fieldset>
            <legend>Dynamic Clock</legend>
             <div id="result_dyn"></div>
            </fieldset>       
        </div>
        </form>
    

    We add reference path of Clock.asmx inside Services Tag. Also we have div ‘id=result_dyn’ element as place of Ajax response text.

  5. View in browser AjaxEnabled.aspx

Regards,
Agung Gugiaji

Advertisements

2 responses to “Quickly Mastering: Create And Use Asp .Net Web Service From Basic, Database Access To Ajax-Enabled

  1. Pingback: [Resolved]Cannot Consume/Access/Use Asp .Net Classes in App_Code / Bin folder and WebService | Enlighten Application Developer Journals

  2. Pingback: Introduction To Asp .Net Ajax 3 (ScriptManagerProxy) | Enlighten Application Developer Journals

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s