serving the solutions day and night

Pages

Saturday, December 8, 2012

CRM Dynamics 2011 OData Query Designer

OData Queries
Select All fields from all board entities
http://<Server_Name>/<Org_Name>/XRMServices/2011/OrganizationData.svc/g_boardSet()

Select specific fields from a specific board entity - g_boardSet(guid'{11b8a0d5-5328-e211-913d-0050568c5ad}')?$select=g_lastname,g_state

Select all board entities ordered by first name - select=g_lastname,g_state&orderby=g_firstname

Filter
All board entities with 'k' in their last name - orderby=gab_firstname&$filter=substringof('k',g_lastname)

number - CreditLimit/Value gt 1000
beginning/ending with z - &$filter=startswith( gab_lastname,'z'), endswith( gab_lastname,'z'), substringof('store',Name)
string or pick list - $filter=gab_ZipCode eq '68105'
Date time - filter=gab_DOB gt datetime'2012-09-01'
Lookup or entity reference - filter=gab_State/Id eq guid'{6512AB94-77F3-E111-9564-0050568C5AD0}'

$expand - Retrieve related records.
For example, to retrieve opportunity records related to accounts,
the query /AccountSet?$expand=opportunity_customer_accounts returns the opportunity records and the account records.

$skip - Sets the number of records to skip before it retrieves records in a collection. - $skip=2

$top - Determines the maximum number of records to return. Products?$top=5

Use the REST Endpoint for Web Resources
The REST endpoint for web resources provides an alternative interface to work with CRM data. You can use the REST endpoint to execute HTTP requests by using a service that is based on a Uniform Resource Identifier (URI).

MS Dynamics CRM Implementation of REST
MS Dynamics CRM 2011 uses the Windows Communication Foundation (WCF) Data Services framework to provide an Open Data Protocol (OData) endpoint that is a REST-based data service. This endpoint is called the Organization Data Service. In Microsoft Dynamics CRM, the service root URI is: [Your Organization Root URL]/xrmservices/2011/organizationdata.svc

OData sends and receives data by using either ATOM or JavaScript Object Notation (JSON). ATOM is an XML-based format. JSON is a text format that allows for serialization of JavaScript objects.

OData Entity Data Model (EDM)
An EDM organizes the data in the form of records of "entity types" and the associations between them.

The MS Dynamics CRM EDM is described in an OData Service Metadata document available at the following path: [Your Organization Root URL]/xrmservices/2011/organizationdata.svc/$metadata

Web Service Data in Web Resources (REST and SOAP Endpoint)

Assign Records, Retrieve Metadata, Execute Messages - SOAP Endpoint Web Serive
<organization URL>/XRMServices/2011/Organization.svc?wsdl

OData System Query Options Using the REST Endpoint

Create, Retrieve, Update, Delete, Associate and Disassociate records  - REST Endpoint Web Service

Limitations
The REST endpoint provides an alternative to the WCF SOAP endpoint, but there are currently some limitations.
  • Only Create, Retrieve, Update, and Delete actions can be performed on entity records.
  • The REST endpoint does not provide all the capabilities available in the SOAP endpoint.
  • Authentication is only possible within the application.
  • The OData protocol is not fully implemented. Some system query options are not available.
    You cannot use late binding with managed code with Silverlight.
REST CODE
CreateOrUpdateContact: function () {
var objVoter = {};
var emptyID = "00000000-0000-0000-0000-000000000000";

objContact.AddressID = { Id: "12345678-9011-1213-1415-161718192021", LogicalName: "address" };
objContact.ContactType = { Value: 750001 };
objContact.RegistrationDate = regDate;
objContact.FirstName = firstName;
objContact.LastName = lastName;
objVoter.StatusCode = { Value: 757580013 };

var jsonEntity = window.JSON.stringify(objVoter);
var odataPath = CommonOperations.GetCrmUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet";
if (queryParams.contactid != null) odataPath += "(guid'" + queryParams.contactid + "')";

$.ajax({
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataPath,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
    XMLHttpRequest.setRequestHeader("Accept", "application/json");
    //update existing record
    if (queryParams.contactid != null) XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (response, textStatus, xhr) {
alert(response)
},
error: function (XmlHttpRequest, textStatus, error) {
   alert(XmlHttpRequest.responseText);
}
});
},

DELETE
//"/XRMServices/2011/OrganizationData.svc/ContactSet(guid'" + queryParams.contactid + "')";
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");

SOAP Code
 GenerateEnvelope: function (request) {
        var envelope = "";
        envelope += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        envelope += "  <s:Body>";
        envelope += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        envelope += request;
        envelope += "    </Execute>";
        envelope += "  </s:Body>";
        envelope += "</s:Envelope>";
        return envelope;
    },
   
GenerateRequest: function (requesttype, keyvalue, requestname) {
        var request = "";
        request += "      <request ";
        if (requesttype.length >0)
            request += "      i:type=\"b:" + requesttype + "\" ";
        request += "       xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
        request += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        request += keyvalue;
        request += "        </a:Parameters>";
        request += "        <a:RequestId i:nil=\"true\" />";
        request += "        <a:RequestName>" + requestname + "</a:RequestName>";
        request += "      </request>";
        return request;
    },
   
    EntityReferenceKeyValue: function (key, entityname, id) {
        var kv = "<a:KeyValuePairOfstringanyType>";
        kv += "     <c:key>" + key + "</c:key>";
        kv += "     <c:value i:type=\"a:EntityReference\">";
        kv += "         <a:Id>" + id + "</a:Id>";
        kv += "         <a:LogicalName>" + entityname + "</a:LogicalName>";
        kv += "         <a:Name i:nil=\"true\" />";
        kv += "     </c:value>";
        kv += "</a:KeyValuePairOfstringanyType>";
        return kv;
    },

StringAnyTypeKeyValue: function (key, datatype, value) {
        var kv = "<a:KeyValuePairOfstringanyType>";
        kv += "     <c:key>" + key + "</c:key>";
        kv += "     <c:value i:type=\"a:" + datatype + "\">";
        kv += "         <a:Value>" + value + "</a:Value>";
        kv += "     </c:value>";
        kv += "</a:KeyValuePairOfstringanyType>";
        return kv;
    },  

ExecuteSoap(envelope) {
    $.ajax({
        type: 'POST',
        async: false,
        url: Xrm.Page.context.getClientUrl()+"/XRMServices/2011/OrganizationData.svc/",
        contentType: 'text/xml; charset=utf-8',
        headers: {
            SOAPAction: "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute"
        },
        data: envelope,
        success: function (data, textStatus, XmlHttpRequest) {
            alert(data)
        },
        error: function (XmlHttpRequest, textStatus, error) {
            alert(error);
        }
    });
}


Change record Owner
var contactid = "get record id";
var teamid = "get current login user team id";
var keyvalue = EntityReferenceKeyValue("Target", "contact", contactid);
keyvalue += EntityReferenceKeyValue("Assignee", "team", teamid);
var request = GenerateRequest("AssignRequest", keyvalue, "Assign")
var envelope = GenerateEnvelope(request);
ExecuteSoap(envelope)


Retrieve Principal Access Request:
var userid = "get current login user id";
var contactid = "get contact record id";
var keyvalue = EntityReferenceKeyValue("Target", "contact", contactid);
keyvalue += EntityReferenceKeyValue("Principal", "systemuser", userid);
var request = GenerateRequest("RetrievePrincipalAccessRequest", keyvalue, "RetrievePrincipalAccess")

Change State and Status Reason
var keyvalue = EntityReferenceKeyValue("EntityMoniker", "contact", voterid);
keyvalue += StringAnyTypeKeyValue("State", "OptionSetValue", state);
keyvalue += StringAnyTypeKeyValue("Status", "OptionSetValue", status);
var request = GenerateRequest("SetStateRequest", keyvalue, "SetState")

Call Action
var StaffContactEntityName = "staffcontact",
    StaffContactEntityId = "{12341234-1234-1234-5668-7890568C3250}",
    ContactEntityName = "contact",
    ContactEntityId = Xrm.Page.data.entity.getId(),
    ActionUniqueName = "SendEmail_Action"
    var keyvalue = EntityReferenceKeyValue('Target', ContactEntityName, ContactEntityId);
    keyvalue += EntityReferenceKeyValue('ChiefOfficial', StaffContactEntityName, StaffContactEntityId);
var request = GenerateRequest('', keyvalue, ActionUniqueName);

Share Record
var keyvalue = EntityReferenceKeyValue("Target", "contact", contactid);
keyvalue += "          <a:KeyValuePairOfstringanyType>";
keyvalue += "            <c:key>PrincipalAccess</c:key>";
keyvalue += "            <c:value i:type=\"b:PrincipalAccess\">";
keyvalue += "              <b:AccessMask>ShareAccess WriteAccess</b:AccessMask>";
keyvalue += "              <b:Principal>";
keyvalue += "                <a:Id>" + userId + "</a:Id>";
keyvalue += "                <a:LogicalName>systemuser</a:LogicalName>";
keyvalue += "                <a:Name i:nil=\"true\" />";
keyvalue += "              </b:Principal>";
keyvalue += "            </c:value>";
keyvalue += "          </a:KeyValuePairOfstringanyType>";
var request = GenerateRequest("GrantAccessRequest", keyvalue, "GrantAccess")

No comments: