Wednesday, May 22, 2013

WCF-RESTfull service using JSONP





JSONP (JavaScript Object Notation with padding):

The difference between JSONP and JSON is that, JSONP will wrap the JSON data as a function call, while the function name is passed in from the request URL.

In JavaScript all ajax requests  due to cross domain policy  or security model which prevents the XMLHttpRequest object requesting resources on a different domain or port to the current page (there are sollutions to get around this but they such as the Access-Control-Allow-Origin header but not all browsers support them).
There are few solutions
Local proxy: Can't run a serverless client
Flash:Remote host needs to deploy a crossdomain.xml file
Script tag: Difficult to know when the content is available, no standard methodology, security risk".
 

JSONP is JSON with an additional JavaScript callback function wrapping the JSON content.
JSON with padding" - was created to allow you to request JSON resources from a different domain. 


  •  No XMLHTTPRequest object is used (no ajax)
  • No Same-origin policies limitations
  • No need for cross-domain policy files on servers


Interface :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.IO;
using System.ServiceModel.Activation;

    [DataContract]
    public class Funds
    {
        [DataMember(Name = "MainCategory", Order = 1)]
        public string CategoryMain;

        [DataMember(Name = "FundID", Order = 2)]
        public int ID;

        [DataMember(Name = "FundCode", Order = 3)]
        public string Code;

        [DataMember(Name = "FundName", Order = 4)]
        public string WebFundName;

    }

    [ServiceContract]   
    public interface ITestJsonp
    {
        [OperationContract]
        [WebGet(UriTemplate = "Fund/{fid}", ResponseFormat = WebMessageFormat.Json)]
        List<Funds> getFundInfo(string fid);
    }


Service :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.IO;
using System.ServiceModel.Activation;

  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class TestJsonp : ITestJsonp
    {
        List<Funds> _objfundList = new List<Funds>();
        List<Funds> _objfundListReturn = new List<Funds>();
        Funds _objfunds;

        public List<Funds> getFundInfo(string fid)
        {
             FillData();           
            _objfunds = _objfundList.Find(delegate(Funds f) { return f.ID == Convert.ToInt32(fid); });
           _objfundListReturn.Add(_objfunds);
            return _objfundListReturn;     
        }

        public void FillData()
        {
            for (int i = 1; i <= 5; i++)
            {
                _objfunds = new Funds();
                _objfunds.ID = i;
                _objfunds.Code = "FuncCode -" + i;
                _objfunds.WebFundName = "FundName -" + i;
                _objfunds.CategoryMain = "Category - " + i;
                _objfundList.Add(_objfunds);
            }           
        }
    }


Service Test:




Client Page :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JSONP.aspx.cs" Inherits="WcfService1.JSONP" %>

<!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>
    <script src="Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
     <script type="text/javascript">

         $(document).ready(function () {
       
             var fid = getUrlVars()["fid"];
             var URL = '';
            
             if (fid == undefined) {             
                 URL = "TestJsonp.svc/Fund/1?callback=?";
             }
             else {
                 URL = "TestJsonp.svc/Fund/" + fid + "?callback=?";
             }
        
             //**************Call 1**********************//
             // JSONP CALL TO WCF SERVICE
             $.ajax({
                 cache: false,
                 url: URL,
                 data: "{}",
                 type: "GET",
                 jsonpCallback: "parseresonse",
                 contentType: "application/javascript",
                 dataType: "jsonp",
                 error: function () {
                     alert("list failed!");
                 },
                 success: function (list) {
                     successCallback(list);
                 }
             });
             function successCallback(data) {
                 $.each(data.getFundInfoResult, function (index, output) {
                     alert("Call-1 : " + output.FundCode);
                 });
             }
             //************************************************//


             //**************Call 2**********************//
             $.getJSON(URL, displayImages);

             function displayImages(data) {
                 $.each(data.getFundInfoResult, function (index, output) {
                     alert("Call-2 : " + output.FundName);
                 });
             }

             //**************Working**********************//       


         });
          function getUrlVars() {
                 var vars = [], hash;
                 var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                 for (var i = 0; i < hashes.length; i++) {
                     hash = hashes[i].split('=');
                     vars.push(hash[0]);
                     vars[hash[0]] = hash[1];
                 }
                 return vars;
             }
  </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      
    </div>
    </form>
</body>
</html>


OutPut


2 comments :

  1. can u say

    cross domain policy or security model which prevents or Cross domain calls..security policy

    ReplyDelete