JSON and JSONP Support

New functionality has been introduced within the Personify Data Services to communicate with service using JSON or JSONP. Default communication format is XML. PDS is intelligent enough to serialize/deserialize XML or JSON based communication messages based on the “content-type” specification as part of request http header.

 

If used with non .NET clients (like jQuery etc.) specify “content-type” as “application/json” to communicate in JSON format.  Any other (or with no content-type) defaults to “application/xml”.

 

By default, without any configuration/content-type specification, the following would return JSON (based on the built-in OData feature):

http://servername/PersonifyDataServices/PersonifyData.svc/Countries?$format=json

Enabling JSON Communication to Work with SvcClient.cs (.NET Client)

Add new key/value pair in AppSettings at client side (Web.Config/App.Config) and SvcClient would automatically communicate using JSON (and that too only for Service Operations).

<appSettings>

<!-- CommunicationFormat=JSON/XML - used to provide the communication format for the data service call. It should have either JSON or XML. XML is the default value -->

<add key="CommunicationFormat" value="JSON"/>

SvcClient.cs supports JSON based communication only for Service Operations (including Create, Save etc.). Microsoft’s OData Client does not support JSON materialization for entity querying. For example following code will not return correct object (if SvcClient with JSON is enforced):

private CusBiography GetCusBiography(string masterCustomerId, int? subCustomerId)
{
              var biographies = SvcClient.Client.Context.CusBiographies
                     .Where(b => b.MasterCustomerId == masterCustomerId &&
                            b.SubCustomerId == subCustomerId)
                     .Select(b => b)
                     .ToList();
                     returnbiographies.FirstOrDefault();
              }
}

Communicating using JSONP

JSONP requires the communication to be of type “application/json” along with the specification of “callback”.

Use the following to communicate using JSONP:

1.    Set the ‘Content-Type’ header as “application/json” in ajax call (or give “$format=json” option in the URL)

2.    Provide “callback”

JSONP Code Samples (in jQuery):

Example 1 (for OData URI): Get all Countries in Json using $format=json URL

function doProcessJsonGet() {

        $.ajax({

            url: "http://localhost/PersonifyDataServices/PersonifyData.svc/Countries?

$format=json&$callback=callbackGet",

            beforeSend: function (xhr) {

                xhr.setRequestHeader("Authorization", getAuthCookie());

            },

            error: function (xhr, ajaxOptions, thrownError) {

                alert(xhr.status);

                alert(thrownError);

            }

        });

    }

 

Example 2 (for OData URI): Get all Countries in Json using Content-Type header

function doProcessJsonGet() {

        $.ajax({

            url: "http://localhost/PersonifyDataServices/PersonifyData.svc/Countries?

$callback=callbackGet",

            beforeSend: function (xhr) {

                xhr.setRequestHeader("Authorization", getAuthCookie());

                xhr.setRequestHeader("Content-Type", "application/json");

            },

            error: function (xhr, ajaxOptions, thrownError) {

                alert(xhr.status);

                alert(thrownError);

            }

        });

    }

 

Example 3 (for Service Operations): Create and save an customer activity entity

Following is an example how you can use JSONP in your HTML page to create and save an entity.

<!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>

    <title>JSONP for create and save an entity (Customer Activity)</title>

    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>

</head>

<body>

    <input id="btnCreate" name="bntCreate" type="button" value="Create Customer Activity" 

onclick="doProcessJsonCreate();"/><br />

    <input id="btnSave" name="bntSave" type="button" value="Save Created Customer

Activity"  onclick="setDataForSave();"/><br />

    Status:&nbsp; <input id="Text1" style="color: red; column-count:auto; width:

653px;" name="txtStatus"  type="text" /><br />

    Result: <textarea name="txtData" rows="10" cols="80"></textarea>

    <script type="text/javascript">

        var header = "Basic " + "YWRtaW46YWRtaW4=";

        document.cookie = "Authorization=" + header;

        var entity;

 

        function getAuthCookie() {

            var cn = "Authorization=";

            var idx = document.cookie.indexOf(cn)

 

            if (idx != -1) {

                var end = document.cookie.indexOf(";", idx + 1);

                if (end == -1) end = document.cookie.length;

                returnunescape(document.cookie.substring(idx + cn.length, end));

            } else {

                return "";

            }

        }

 

        //create an entity

        functiondoProcessJsonCreate() {

            $.ajax({

                url: "http://localhost/PersonifyDataServicesBase/PersonifyData.svc/Create?EntityName='CusActivity'&$callback=callbackCreate",

                beforeSend: function (xhr) {

                    xhr.setRequestHeader("Authorization", getAuthCookie());

                    xhr.setRequestHeader("Content-Type", "application/json");

                },

                error: function (xhr, ajaxOptions, thrownError) {

                    alert(xhr.status);

                    alert(thrownError);

                }

            });

        }

 

        function setDataForSave() {

            if (entity == null) {

                txtStatus.value = "Entity is not created, click 'Create Customer

Activity' button to create the entity first.";

                return;

            }

 

            //modify properties of newly created entity

            entity.MasterCustomerId = "JEFFERSON";

            entity.Subsystem = "MRM";

            entity.ActivityText = "This is sample text - " + entity.CustomerActivityId;

            entity.Subsystem = "MRM";

            entity.CallTypeCode = "EMAIL-INBOUND";

            entity.CallTopicCode = "ADDRESS";

            entity.ActivityCode = "COMMUNICATION";

 

            //save entity

            $.ajax({

                url: "http://localhost/PersonifyDataServicesBase/PersonifyData.svc/Save?EntityName='CusActivity'&$callback=callbackSave",

                beforeSend: function (xhr) {

                    xhr.setRequestHeader("Authorization", getAuthCookie());

                    xhr.setRequestHeader("Content-Type", "application/json");

                },

                type: 'post',

                data: (JSON.stringify(entity)),

                error: function (xhr, ajaxOptions, thrownError) {

                    alert(xhr.status);

                    alert(thrownError);

                }

            });

        }

 

        functioncallbackCreate(result) {

            if (result == null) {

                txtStatus.value = "No value returned in Create...";

                txtData.value = "";

                return;

            }

            txtStatus.value = "Successfully created...";

            entity = result;

            txtData.value = JSON.stringify(result);

        }

 

        functioncallbackSave(result) {

            if (result == null) {

                txtStatus.value = "No value returned in Save...";

                txtData.value = "";

                return;

            }

            txtStatus.value = "Successfully saved...";

            txtData.value = JSON.stringify(result);

        }

 

    </script>

</body>

</html>