Showing posts with label WebService. Show all posts
Showing posts with label WebService. Show all posts

Sunday, 12 January 2014

Create a One-Way asp.net web service

In this article we are going to see the how to create a one way web service in the asp.net. so for long running process we can invoke the service and do the next process instead of waiting for the response from the service. set [SoapDocumentMethod(OneWay=true)]

web service:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Runtime.Remoting.Messaging;
using System.Web.Services.Protocols;
using System.IO;
using System.Threading;

namespace MathService
{
    /// <summary>
    /// Summary description for Service1
    /// </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 MathService : System.Web.Services.WebService
    {

        [WebMethod]
        public int Add(params int[] values)
        {
            return values.Sum();
        }

        
        [SoapDocumentMethod(OneWay=true)]
        [WebMethod]
        public void WriteLog(string message)
        {
            Thread.Sleep(10000);
            File.AppendAllText(Server.MapPath("log.txt"),message);
        }
    }

}

Client:
namespace InvokeWebService
{
    class Program
    {
        static void Main(string[] args)
        {
            Maths.MathService websrv = new Maths.MathService();
            Console.WriteLine("Connecting service . . . ");           
            int addvalue = websrv.Add(new int[] { 3,2,6,7});
            Console.WriteLine(" Add Operation result : " + addvalue);

            int subvalue = websrv.Sub(4, 2);
            Console.WriteLine(" Sub Operation result :" + subvalue);

            websrv.WriteLog("This is called as async, by Rajesh. G");
            Console.WriteLine("Done");
            Console.Read();

        }
    }
}




Output:
This is called as async, by Rajesh. G

A log file is created in the server side with the information send by the user.

Create a asp.net webservice and invoke using client.

In this article we are going to see the how to create a web service and invoke a web service from the client.
Create a new project with web service as template. in these we are creating a two methods which will have to do the maths operation.

Web Service :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Runtime.Remoting.Messaging;
using System.Web.Services.Protocols;
using System.IO;
using System.Threading;

namespace MathService
{
    /// <summary>
    /// Summary description for Service1
    /// </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 MathService : System.Web.Services.WebService
    {

        [WebMethod]
        public int Add(params int[] values)
        {
            return values.Sum();
        }

        [WebMethod]
        public int Sub(int a,int b)
        {
            return a - b;
        }

    }
}



Host the application in the IIS and launch the in the web browser.



Client:
Create a new project with the console application.Add the web reference and name it as Maths.

namespace InvokeWebService
{
    class Program
    {
        static void Main(string[] args)
        {
            Maths.MathService websrv = new Maths.MathService();
            Console.WriteLine("Connecting service . . . ");           
            int addvalue = websrv.Add(new int[] { 3,2,6,7});
            Console.WriteLine(" Add Operation result : " + addvalue);

            int subvalue = websrv.Sub(4, 2);
            Console.WriteLine(" Sub Operation result :" + subvalue);

            Console.WriteLine("Done");
            Console.Read();

        }
    }
}


Output:
Connecting service . . .
 Add Operation result : 18
 Sub Operation result :2
Done


From this article you can learn how to create the service and invoke it from the client.

Saturday, 27 July 2013

Call a WebService in ASP.NET using JSON




What is JSON?
  JSON is JavaScript Object Notation – It is used for Data Interchange, Describes about format of data interchange. It is Light-Weight.

Example:
{“menu”: {
“id”: “m01”,
“value”: “F23”,
“contextmenu”:{
“menuitem”:[
{“value”: ”Edit”,”name”: “_edit”},
{“value”: ”View”,”name”: “_view”}
   ]
           }
}
}

In Xml :

<menu id="m01" value=F23>
  <contextmenu>
    <menuitem value=Edit name=_edit />
    <menuitem value=View name=_view />
  </contextmenu>

</menu>

Now we see the program how we are going to call a web service using JSON. Create ASP.NET WebService, with few WebMethods.

Step 1. Create  a  ASP.NET Application and add a webservice1.asmx as new item from visual studio and the following code to create a web service.


public class WebService : System.Web.Services.WebService
{

    public WebService ()
    {
       
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public string HelloMe(string Name)
    {
        return "Hello " + Name + " !";
    }

    [WebMethod]
    public bool CheckName(string Name)
    {
        // Checking for records can be done here.
        return (Name == "Validator");
    }

    [WebMethod]
    public string CallError()
    {
        int i = 0;
        int j = 5 / i;    //Divide by Zero Error
        return "Error";
    }
}


Above service have four methods one method with no parameter, another method with parameter, another one is used to check validate the control and finally for exception.

Step 2. Create a JavaScript function to call the Web Service.

function SynchronousJSONResponse(url, postData)
    {
        var xmlhttp = null;
        if (window.XMLHttpRequest)
            xmlhttp = new XMLHttpRequest();
        else if (window.ActiveXObject) {
            if (new ActiveXObject("Microsoft.XMLHTTP"))
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            else
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        url = url + "?rnd=" + Math.random(); // to be ensure non-cached version 
        xmlhttp.open("POST", url, false);
        xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xmlhttp.send(postData);
        var responseText = xmlhttp.responseText;
        return responseText;
    }

   Above method is used to post the data to the web service and get the response from the web service.Check for the xmlhttp to initialize for which object.

Above service have four methods one method with no parameter, another method with parameter, another one is used to check validate the control and finally for exception.
The First Parameter consists of Url of Web Service including the Web Method.
The Second Parameter consists of Data that send as parameter using JSON.

Step 3: Create an event and bind it with JavaScript function.
     3.1 Simple Web Service call
        <dt>Simple Call</dt>
           <dt><a href="javascript:HelloWorld()">Hello World</a></dt>      
          function HelloWorld()
     {
var result = SynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/HelloWorld") %>'null);
           result = eval('(' + result + ')');
       alert(result.d);
    }

     3.2 Web Service Call with passing a parameter.
         In this a Link is binded to the Javascript function on click, In Which the function          takes the Value from the TextBox and pass as parameter to web method.

         <dt>Call With Paramter</dt>
            <dt><input id="txtName" value="Your Name" />
               <a href="javascript:HelloMe()">Hello Me</a>
            </dt>      
function HelloMe()
{
  var result = GetSynchronousJSONResponse('<%=                  
            Page.ResolveUrl("~/WebService.asmx/HelloMe") %>',
            '{"Name":"' + document.getElementById('txtName').value + '"}');        result = eval('(' + result + ')');
    alert(result.d);
}

     3.3 Binding the Web Method with Control Validate.
          In this We are validating a control using the Custom Validator by using the             client Script.Which invokes the webservice and validate the Value present in             TextBox.

        <dt>Call With Custom Validator</dt>
        <dt>
            <asp:TextBox ID="txtCheckName" runat="server" Text="Validator"></asp:TextBox>
            <asp:CustomValidator ID="cvName" ControlToValidate="txtCheckName"      
                EnableClientScript="true"              
                ClientValidationFunction="CheckForDuplicateInDB" runat="server"
                Display="Static" ToolTip="Name is Duplicate."           
                Text="*"></asp:CustomValidator>
            <asp:Button ID="btnClickMe" runat="server" Text="ClickMe!" />
            <a href="#" onclick="a()">a</a>
        </dt>

           function CheckForDuplicateInDB(sender, arg) {
var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/CheckName") %>''{"Name":"' + arg.Value + '"}');
                 result = eval('(' + result + ')');
                 arg.IsValid = !result.d;
                }

        function a() {
var result = GetSynchronousJSONResponse('<%=
Page.ResolveUrl("~/WebService.asmx/HelloMe") %>''{"Name":"' + document.getElementById('txtName').value + '"}');
       result = eval('(' + result + ')');
       alert(result.d);
                }
   

     3.4 Handle Server Error
         Handling the error on client side when it is raise on server side.

<dt><a href="javascript:CallError()">Call Error</a></dt>             

function CallError() {
var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/CallError") %>'null);
        result = eval('(' + result + ')');
        if (typeof (result.d) == 'undefined')
          alert(result.Message);
        else
          alert(result.d);
    }

The parameter is passed in JSON format, The Response from the Web Service is get and alerted in page.

Full ASP.Net Code.
Javascript 


<script type="text/javascript">

      function SynchronousJSONResponse(url, postData)
            {
                  var xmlhttp = null;
                 if (window.XMLHttpRequest)
                        xmlhttp = new XMLHttpRequest();
                 else if (window.ActiveXObject) {
                           if (new ActiveXObject("Microsoft.XMLHTTP"))
                                 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                          else
                                 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                              }   
                         url = url + "?rnd=" + Math.random(); // to be ensure non-cached version 
                        xmlhttp.open("POST", url, false);
                        xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                        xmlhttp.send(postData);
                       var responseText = xmlhttp.responseText;
                       return responseText;
                 }

         function HelloWorld()
     {
var result = SynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/HelloWorld") %>'null);
           result = eval('(' + result + ')');
       alert(result.d);
    }
         function HelloMe()
{
  var result = GetSynchronousJSONResponse('<%=                  
            Page.ResolveUrl("~/WebService.asmx/HelloMe") %>',
            '{"Name":"' + document.getElementById('txtName').value + '"}');        result = eval('(' + result + ')');
    alert(result.d);
}
         function CheckForDuplicateInDB(sender, arg) {
var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/CheckName") %>''{"Name":"' + arg.Value + '"}');
                 result = eval('(' + result + ')');
                 arg.IsValid = !result.d;
                }

        function a() {
var result = GetSynchronousJSONResponse('<%=
Page.ResolveUrl("~/WebService.asmx/HelloMe") %>''{"Name":"' + document.getElementById('txtName').value + '"}');
       result = eval('(' + result + ')');
       alert(result.d);
                }
       function CallError() {
var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/CallError") %>'null);
        result = eval('(' + result + ')');
        if (typeof (result.d) == 'undefined')
          alert(result.Message);
        else
          alert(result.d);
    }

</script>


 ASP.NET Code :

<body>
    <form runat="server"> 
    <dl>
        <dt>Simple Call</dt>
        <dt><a href="javascript:HelloWorld()">Hello World</a></dt>
        <dt><hr /></dt>
        <dt>Call With Parameter</dt>
        <dt><input id="txtName" value="Your Name" />
            <a href="javascript:HelloMe()">Hello Me</a>
        </dt>
        <dt><hr /></dt>
        <dt>Call With Custom validator</dt>
        <dt>
            <asp:TextBox ID="txtCheckName" runat="server" Text="Validator"></asp:TextBox>
            <asp:CustomValidator ID="cvName" ControlToValidate="txtCheckName" EnableClientScript="true" ClientValidationFunction="CheckForDuplicateInDB" runat="server" Display="Static" ToolTip="Name is Duplicate." Text="*"></asp:CustomValidator>
            <asp:Button ID="btnClickMe" runat="server" Text="ClickMe!" />
            <a href="#" onclick="a()">a</a>  
        </dt>
     <dt><hr /></dt>
        <dt>Call Error</dt>
        <dt><a href="javascript:CallError()">Call Error</a></dt>
        <dt><hr /></dt>
    </dl>
    </form>
</body>


 I hope from this article you can learn basic information of how to call a web service from ASP.NET Website using JSON in ASP.NET