Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Friday, December 16, 2011

Performing CRUD Operations synchronously in CRM 2011 through JSON

Synchronous methods to create, update and delete the records for the Account entity through JSON. These methods works synchronously.

Create Records: To create the record into the CRM, you need to create an object for that record. After that you need to create the object of the XMLHttpRequest and open this request through “POST” method and need to call the send method with this jsonEntity (create from the target record).

function createRecord( ) {
var account = new Object( );
account.Name = "Create Sample";
account.Telephone1 = "555-0123";
account.AccountNumber = "ABCDEFGHIJ";
account.EMailAddress1 = "someone1@example.com";

var jsonEntity = window.JSON.stringify(account);
var createRecordReq = new XMLHttpRequest( );
var ODataPath = Xrm.Page.context.getServerUrl( ) + "/XRMServices/2011/OrganizationData.svc";
createRecordReq.open('POST', ODataPath + "/" + "AccountSet", false);
createRecordReq.setRequestHeader("Accept", "application/json");
createRecordReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
createRecordReq.send(jsonEntity);

var newRecord = JSON.parse(createRecordReq.responseText).d;
//Alert the Id of the created record
alert("Id is: " + newRecord.AccountId);
}

Update Record: Update record request is same as the create but for the Update we need to set the Additional request header for the Method in the XMLHttpRequest. Here we have added the “MERGE” method. As shown below.
updateRecordReq.setRequestHeader("X-HTTP-Method", "MERGE");

And when we open the request, we need to pass the guid of the record. As given in the below script.

function updateRecord( ) {
var account = Object( );
account.Name = "Update Name of this Account";
var jsonEntity = window.JSON.stringify(account);
var updateRecordReq = new XMLHttpRequest( );
var ODataPath = Xrm.Page.context.getServerUrl( ) + "/XRMServices/2011/OrganizationData.svc";
updateRecordReq.open('POST', ODataPath + "/" + "AccountSet" + "(guid'" + "E72B45B9-58E0-E011-B700-00155D005515" + "')", false);
updateRecordReq.setRequestHeader("Accept", "application/json");
updateRecordReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
updateRecordReq.setRequestHeader("X-HTTP-Method", "MERGE");
updateRecordReq.send(jsonEntity);

}

Delete Record: This is same as update request but here we need to call the Method delete and call send method with the null parameter.

function deleteRecord( ) {
var deleteRecordReq = new XMLHttpRequest( );
var ODataPath = Xrm.Page.context.getServerUrl( ) + "/XRMServices/2011/OrganizationData.svc";
deleteRecordReq.open('POST', ODataPath + "/" + "AccountSet" + "(guid'" + "E72B45B9-58E0-E011-B700-00155D005515" + "')", false);

deleteRecordReq.setRequestHeader("Accept", "application/json");
deleteRecordReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
deleteRecordReq.setRequestHeader("X-HTTP-Method", "DELETE");
deleteRecordReq.send(null);

}


-------------------------------------------------------
Posted by: Inogic
For more information/discussions (documents, sample code snippets, detailed work flow or diagrams),
Please be free to visit the following links or email us:
Web: http://www.inogic.com
Blog: http://inogic.blogspot.com
Email: news@inogic.com
-----------------------------------------------------

Tuesday, December 13, 2011

Read records synchronously using JSON in CRM 2011

Common knowledge is that we can make JSON requests through scripts in CRM 2011 to retrieve data from CRM entities. However, the JSON request works asynchronously i.e it does not return the results immediately and the control moves to the next line of code to be executed.

It so happened during one of our development sessions is that we had to write a script to populate the values of some attributes on a form based on the value entered in another form, similar to the usual copy the phone and email once the contact is selected. We had written the JSON code for this but because it executed asynchronously the control would return to the user even before the code execution completed and the phone and email was populated on the form. The user would click on Save and Close and reported an issue that it did not bring over the phone and email…

We can replace JSON with SOAP and get this done. But we thought of getting this done by executing JSON request synchronously now that we already has the code in there to execute the call through JSON.
function retrieveRecordsSynchronously() {

var retrieveRecordsReq = new XMLHttpRequest();
var ODataPath = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/AccountSet";
retrieveRecordsReq.open('GET', ODataPath, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.send(null);
var records = JSON.parse(retrieveRecordsReq.responseText).d;
//Read the first account name
alert('First Account Name is: ' + records.results[0].Name);
}
As given in the above code we need to create the object of the XMLHttpRequest and need to open this request through ‘GET’ method. And after setting the header of this request we need to just call the send Method to send the request, after that we need to parse the response text of the request and from that we can read the results.

We are reading from AccountSet and it returns an array of accounts. Note it would only return 50 results at a time.

Wednesday, July 27, 2011

Json and Silverlight with ODataService in CRM 2011

Dynamics CRM 2011 now provides the ability to perform data operations on CRM entities using JSON and ODATA service.

Here we have tried to explain the various clauses of JSON that is supported by CRM ODATA and how this service can be used in Silverlight as well as in Scripts. Note not all standard ODATA clauses are supported by CRM.

To use these clauses in silverlight you need to add a reference to the ODataService of the CRM i.e. OrganizationData.svc.

$select: This clause is the Select part of any SQL statement where you can specify the list of attributes to be returned by the query. Note you can also provide the collection property of a 1:N or N:1 relationship.

Using JSON

If you write the following URL to read the opportunity.

http://://xrmservices/2011/organizationdata.svc/OpportunitySet

it will return all columns of the opportunity in XML but if you want to read only the name you can add the select as follows.

http://ad12:5555/crmorg1//xrmservices/2011/organizationdata.svc/OpportunitySet?$select=Name

It will return the folliwng XML



Using Silverlight:

To use the $select in the Silverlight app you need to write the query as follows.

DataServiceQuery query = (DataServiceQuery_context.OpportunitySet.AddQueryOption("$select", "Name");


$expand: Directs that related records should be retrieved in the record or collection being retrieved.

Using JSON:
If you want to read the customer information with the opportunity while we are reading the opportunity by JSON then we can use the expand, and then we can read the customer details with the opportunity. Below we have given the JSON url.

http://://xrmservices/2011/organizationdata.svc/OpportunitySet?$expand=opportunity_customer_accounts,opportunity_customer_contacts&$select=*,opportunity_customer_accounts,opportunity_customer_contacts

Using Silverlight:

To use this with the silverlight you need to write the following query in the silverlight.

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$select", "*,opportunity_customer_accounts,opportunity_customer_contacts")
.AddQueryOption("$expand", "opportunity_customer_accounts")
.AddQueryOption("$expand", "opportunity_customer_contacts");

$filter:

Using JSON:
To set the condition in the JSON query we can use the $filter clause in the url.
Suppose if you want read all accounts of an user the JSON url will be as follows.

http:// ://xrmservices/2011/organizationdata.svc/AccountSet?$filter=OwnerId/Id eq (guid'34fca7f5-d556-e011-b9a8-00155d005515')

Using Silverlight:
In silverlight we can use the AddQueryOption to add the $filter as we use for $expand or we can use the Where Condition as shown in the below.

DataServiceQuery query = (DataServiceQuery)_context.AccountSet.Where(a => a.OwnerId.Id == new Guid("34FCA7F5-D556-E011-B9A8-00155D005515"));

To do it through AddQueryOption you can generate the filter in a string and then pass that string a parameter to the filter option. This provides us to create dynamic filters as shown below


filter += "new_testId eq (guid'" + _userid + "') ";

DataServiceQuery query = (DataServiceQuery)

query = query.AddQueryOption("$filter", filter);

$orderby: We can use it to set the sort order. Use it same as $filter.

Using JSON:

http:// ://xrmservices/2011/organizationdata.svc/AccountSet?$orderby=Name, Address1_Country.

Using Silverlight:

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$orderby", "Name, Address1_Country")


$top: To define the range that how many record want to read. Max limit is 50.

Using JSON:

http:// ://xrmservices/2011/organizationdata.svc/AccountSet?$top=10

Using Silverlight:

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$top", 10)


$skip: To define the that how many record want to skip.
Using JSON:

http:// ://xrmservices/2011/organizationdata.svc/AccountSet?$skip=10

Using Silverlight:

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$skip", 10)


NOTE: By default any query executed using ODATA service will only return 50 records at a time. If we want to display All records that exist even if it is more than 50 records, then you can use a combination use of the $skip and $top clauses to read all records.

For this you can recursively call this Query where _top will be const with value 50. And at each recursion we can increase the value of the _skip by 50.

DataServiceQuery query = (DataServiceQuery)_context.OpportunitySet.AddQueryOption("$skip", _skip).AddQueryOption("$top", _top)