Monday, January 21, 2013

IOrganizationService Methods in CRM 2011

NameDescription
public methodAssociateCreates a link between records.
public methodCreateCreates a record.
public methodDeleteDeletes a record.
public methodDisassociateDeletes a link between records.
public methodExecuteExecutes a message in the form of a request, and returns a response.
public methodRetrieveRetrieves a record.
public methodRetrieveMultipleRetrieves a collection of records.
public methodUpdateUpdates an existing record.

The IOrganizationService Web service provides a set of methods used to perform the most common operations on system and custom entities and on the metadata for your organization. These operations can also be performed by using the IOrganizationService.Execute method and the corresponding message.

Create

Use the IOrganizationService.Create method to create an instance (record) of any entity that supports the Create message, including custom entities.

Retrieve

Use the IOrganizationService.Retrieve method to retrieve an instance (record) of an entity..

RetrieveMultiple

Use the IOrganizationService.RetrieveMultiple method to retrieve a collection records. The query can be specified using a query expression or Fetch XML query. If the query includes an aggregate function, xxx.

Update

Use the IOrganizationService.Update method to update an existing record.

Delete

Use the IOrganizationService.Delete method to delete an existing record.

Associate

Use the IOrganizationService.Associate method to create a link between two records that participate in a relationship.

Disassociate

Use the IOrganizationService.Disassociate method to delete the link between two records.

Execute

Use the IOrganizationService.Execute method to execute a message. This includes common processing like create and delete of data records and metadata, or it can be specialized processing such as import or detect duplicates.

Friday, December 28, 2012

Read records synchronously using JSON in CRM 2011


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);
 }

Automatical refreshing the form in crm 2011


function ForceRefreshForm() 

         if(Xrm.Page.data.entity.getIsDirty()) 
                 Xrm.Page.data.entity.save(); 
         else 
                 window.location.reload(true); 
}  

Set the CRM Form as Read Only


function setFormAsReadOnly() {
    // define the logic here
    disableFormFields(true);
}
function doesControlHaveAttribute(control) {
    var controlType = control.getControlType();
    return controlType != "iframe" && controlType != "webresource" && controlType != "subgrid";
}
function disableFormFields(onOff) {
    Xrm.Page.ui.controls.forEach(function(control, index) {
        if (doesControlHaveAttribute(control)) {
            control.setDisabled(onOff);
        }
    });
}

Passing configuration data using Plug-in registration tool (Secured vs. Unsecured)


  • CRM plugin registration tool contain “Unsecure & Secure” configuration sections while registering a “Step”
  • We can pass configuration data and can be used in the plug-in logic.
Secured vs. Unsecured
Below are key differentiations between Secured and Unsecured data configuration
  • Access
    • Data passed through “Unsecure” section is PUBLIC (i.e., It can be read by any user in CRM).
    • Only users with “System Administrator” role have access to the data passed through “Secure” configuration section
  • Storage
    • “Unsecure” config data will be stored along with the Plugin ‘Step’ registration information (i.e., In SdkMessageProcessingStep entity)
    • “Secure” config data will be stored in a separate entity named “SdkMessageProcessingStepSecureConfig
      • Only “System Administrator” has Read access on this entity, hence only users with ‘Sys Admin’ role can access this data
    • Both “Secured & Unsecured” configuration data stored as “Plain text” in DB
  • Outlook Sync
    • “Unsecured” configuration data is downloaded to the user’s computer when they go offline making it Unsecure
    • “Secured” configuration data is NOT downloaded to User’s Computer when they go Offline
How to read Configuration data in Plug-in
In our plug-in class, we can define a constructor that passes two parameters (i.e., unsecure configuration and secure configuration)

public class AccountCreateHandler: IPlugin{
  public AccountCreateHandler(string unsecure, string secure){
    // Do something with the parameter strings.
  }
  public void Execute(IPluginExecutionContext context){
    // Do something here.
  }
}

 If you want to read “Secure” configuration in the plug-in code, either change the user context in plugin registration as “CRM administrator ” or Impersonate to “CRM Administrator” role user in the code

Adding button/Javascript to a Ribbon


Replace the <RibbonDiffXmlwith the below code.It will add the button on Account main form with javascript code

<RibbonDiffXml>
<CustomActions>
<CustomAction Id="CA_MyFirstButton" Location="Mscrm.Form.account.MainTab.Save.Controls._children" Sequence="31">
<CommandUIDefinition>
<Button Id="B_MyFirstButton" Command="MSCRM.Form.account.MainTab.Save.Controls._children" LabelText="My First Button" ToolTipTitle="My First Button Tool Tip Title" ToolTipDescription="My First Button Tool Tip Description"
TemplateAlias="o1" Image16by16="/_imgs/ribbon/saveandclose16.png" Image32by32="/_imgs/ribbon/saveandclose32.png" /></CommandUIDefinition>
</CustomAction>
</CustomActions>
<Templates>
<RibbonTemplates
Id="Mscrm.Templates"/>
</Templates>
<CommandDefinitions>
<CommandDefinition Id="MSCRM.Form.account.MainTab.Save.Controls._children">
<EnableRules />
<DisplayRules />
<Actions>
<JavaScriptFunction FunctionName="hello" Library="$webresource:new_test">
<CrmParameter Value="CommandProperties"></CrmParameter>
</JavaScriptFunction>
</Actions>
</CommandDefinition>
</CommandDefinitions>
<RuleDefinitions>
<TabDisplayRules/>
<DisplayRules/>
<EnableRules/>
</RuleDefinitions>
<LocLabels/>
</RibbonDiffXml>

create a web resource test and add the below function

function hello(){
alert("My First Button with Custom button");
}

whenever you click on the custom button it shows an alert

Saturday, December 22, 2012

CRUD operations using Jquery in MS CRM 2011


function onLoad(context) {
    var accountId = Xrm.Page.data.entity.getId();
    //ReadMethod("MostRecent");
    //deleteAccount("41FB760C-2C4B-E211-AB64-0800270618E2");
    //WriteMethod("SAI KRISHNA YADAV");
    //updateRecord(accountId, "AccountSet");
}

function ReadMethod(queryName) {
    try {
        // debugger;
        var serverUrl;
        //serverUrl = Xrm.Page.context.getServerUrl() + oDataQuery;
        var accountId = Xrm.Page.getAttribute("primarycontactid").getValue()[0].id;
        $.ajax({
            type: "GET",
            url: "http://test/CRM2011VM/XRMServices/2011/organizationData.svc/ContactSet?$select=FullName&$filter=ContactId eq guid'" + accountId + "'",
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (result) {
                //debugger;
                if (result != undefined && result.d != undefined && result.d.results != undefined && result.d.results != null) {
                    // for (var i = 0; i < result.d.results.length; i++) {
                    alert(result.d.results[0].FullName);
                    //WriteMethod(result.d.results[0].FullName);
                    //}
                }
            },
            error: function (res) {
                //  debugger;
                alert(res.responseText);
            }
        });

    } catch (e) {
        debugger;
        alert(e.Description);
    }
}

function WriteMethod() {
    try {
        var serverUrl;
        var serverUrl = Xrm.Page.context.getServerUrl();
        var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/AccountSet";

        // Define attribute values for the CRM object you want created
        var newAccount = new Object();
        newAccount.Name = "Samplee";
        newAccount.Telephone1 = "123";
        newAccount.Fax = "456";

        //Parse the entity object into JSON
        var jsonEntity = window.JSON.stringify(newAccount);

        //Asynchronous AJAX function to Create a CRM record using OData
        $.ajax({ type: "POST",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: serverUrl + ODATA_ENDPOINT,
            data: jsonEntity,
            beforeSend: function (XMLHttpRequest) {
                //Specifying this header ensures that the results will be returned as JSON.
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
            },
            success: function (data, textStatus, XmlHttpRequest) {
                var NewCRMRecordCreated = data["d"];
                alert("CRM GUID created: " + NewCRMRecordCreated.AccountId);

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("failure");
            }
        });

    } catch (e) {
        debugger;
        alert(e.Description);
    }
}

function deleteAccount(id) {
    // Get Server URL
    var serverUrl = Xrm.Page.context.getServerUrl();
    //The OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //Asynchronous AJAX function to Delete a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + "/" + "AccountSet" + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            //Specify the HTTP method DELETE to perform a delete operation.
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("Record deleted successfully!!!!");
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert("Error while deletion – " + errorThrown);
        }
    });
}


function updateRecord(id, odataSetName) {
    // Get Server URL
    var serverUrl = Xrm.Page.context.getServerUrl();
    var newAccount = new Object();
    newAccount.Name = "Samplee";
    newAccount.Telephone1 = "123";
    newAccount.Fax = "456";
    var jsonEntity = window.JSON.stringify(newAccount);
    //The OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    //Asynchronous AJAX function to Update a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: jsonEntity,      
        url: Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/AccountSet(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
            //Specify the HTTP method MERGE to update just the changes you are submitting.
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("Updated successfully");
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (XmlHttpRequest && XmlHttpRequest.responseText) {
                alert("Error while updating " + odataSetName + " ; Error – " + XmlHttpRequest.responseText);
            }
        }
    });
}


Add the onLoad function in Form onload/onChange of any field..