Pages

Showing posts with label CRM 2011. Show all posts
Showing posts with label CRM 2011. Show all posts

Wednesday, 17 April 2013

JQuery code to Create , Retrieve , Update , Delete entity record in CRM 2011

In this article , I am going to explain how to create , retrieve , update , delete entity record in CRM 2011

First need to add these three javascript files as webresource in CRM
jquery1.4.1.min.js
json2.js
SDK.JQuery.js

these files are in SDK under Script folder (sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts)


var primaryContact = null;

Code to create Account Entity record
function createAccount() {
    getFirstContactToBePrimaryContact();
    var account = {};
    account.Name = "Test Account Name";
    account.Description = "This account was created by the JQueryRESTDataOperations sample.";
    if (primaryContact != null) {
        //Set a lookup value
        account.PrimaryContactId = { Id: primaryContact.ContactId, LogicalName: "contact", Name: primaryContact.FullName };
    }
    //Set a picklist value
    account.PreferredContactMethodCode = { Value: 2 };
    //Set a money value
    account.Revenue = { Value: "2000000.00" };
    //Set a Boolean value
    account.DoNotPhone = true;
    //Create the Account
    SDK.JQuery.createRecord(
     account,
     "Account",
     function (account) {
         alert("The account named \"" + account.Name + "\" was created with the AccountId : \"" + account.AccountId + "\".");
         retrieveAccount(account.AccountId)
     },
     errorHandler
   );

}


Code to retrieve Account Entity record
function retrieveAccount(AccountId) {
    SDK.JQuery.retrieveRecord(
     AccountId,
     "Account",
     null, null,
     function (account) {
         alert("Retrieved the account named \"" + account.Name + "\". This account was created on : \"" + account.CreatedOn + "\".");
         updateAccount(AccountId);
     },
     errorHandler
   );
}

Code to update Account Entity record
function updateAccount(AccountId) {
    var account = {};
    account.Name = "Updated Account Name";
    account.Address1_AddressTypeCode = { Value: 3 };
    account.Address1_City = "Sammamish";
    account.Address1_Line1 = "123 Maple St.";
    account.Address1_PostalCode = "98074";
    account.Address1_StateOrProvince = "WA";
    account.EMailAddress1 = "someone@microsoft.com";
    SDK.JQuery.updateRecord(
     AccountId,
     account,
     "Account",
     function () {
         alert("The account record changes were saved");
         deleteAccount(AccountId);
     },
     errorHandler
   );
}

Code to delete Account Entity record
function deleteAccount(AccountId) {
    if (confirm("Do you want to delete this account record?")) {
        SDK.JQuery.deleteRecord(
       AccountId,
       "Account",
       function () {
           alert("The account was deleted.");
           enableResetButton();
       },
       errorHandler
     );
    }
}

Code to retrieve muliple contact Entity records
function getFirstContactToBePrimaryContact() {
    SDK.JQuery.retrieveMultipleRecords(
     "Contact",
     "$select=ContactId,FullName&$top=1",
     function (results) {
         var firstResult = results[0];
         if (firstResult != null) {
             primaryContact = results[0];
         }
     },
     errorHandler,
     function () {
         //OnComplete handler
     }
   );
}

function errorHandler(error) {
    alert(error.message);
}


JQuery asynchronous and synchronous retrieve using REST in CRM 2011

In this article , i am going to explain how to make asynchronous and synchronous call using javascript in CRM 2011

first you need to add JQuery file on form as webresource and if you want to run javascript code asynchronous  then make async attribute value true else false in below code


function Retrieve() {
    var jSonArray = new Array();

    if (Xrm.Page.getAttribute("account").getValue() != null) {
        //acount guid no
        var studentid = Xrm.Page.data.entity.attributes.get("account").getValue()[0].id;

        var filter = "$select=name&$filter=accountid eq guid'" + studentid + "'"
        var entityset = 'account';

        var pagecontext = Xrm.Page.context;
        var serverUrl = pagecontext.getServerUrl();
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }
        var odataSelect = serverUrl + "/xrmservices/2011/OrganizationData.svc/" + entityset + "Set?" + filter;

        //asynchronous call -> async: true
        //synchronous call -> async: true
        $.ajax({
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: odataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                jSonArray.push(data.d);
                onSaveSuccess(jSonArray);
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
        });
    }

}

function onSaveSuccess(jSonArray) {
    if (jSonArray != null && jSonArray[0].results.length > 0) {
        var accountname = jSonArray[0].results[0].name;
    }
}

Wednesday, 6 March 2013

Execute workflow using javascript in CRM 2011

In this article, i am going to explain how to execute workflow using javascript code. You only need to assign your workflow id to "workflowId" variable


function RunWorkflow() {
    var _return = window.confirm('Are you want to execute workflow.');
    if (_return) {
        var url = Xrm.Page.context.getServerUrl();
        var entityId = Xrm.Page.data.entity.getId();
        var workflowId = '541B45C9-3F88-4448-9690-2D4A365C3172';
        var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
        url = url + OrgServicePath;
        var request;
        request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                      "<s:Body>" +
                        "<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
                          "<request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">" +
                            "<a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">" +
                              "<a:KeyValuePairOfstringanyType>" +
                                "<c:key>EntityId</c:key>" +
                                "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + entityId + "</c:value>" +
                              "</a:KeyValuePairOfstringanyType>" +
                              "<a:KeyValuePairOfstringanyType>" +
                                "<c:key>WorkflowId</c:key>" +
                                "<c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">" + workflowId + "</c:value>" +
                              "</a:KeyValuePairOfstringanyType>" +
                            "</a:Parameters>" +
                            "<a:RequestId i:nil=\"true\" />" +
                            "<a:RequestName>ExecuteWorkflow</a:RequestName>" +
                          "</request>" +
                        "</Execute>" +
                      "</s:Body>" +
                    "</s:Envelope>";

        var req = new XMLHttpRequest();
        req.open("POST", url, true)
        // Responses will return XML. It isn't possible to return JSON.
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        req.onreadystatechange = function () { assignResponse(req); };
        req.send(request);
    }
}

function assignResponse(req) {
    if (req.readyState == 4) {
        if (req.status == 200) {
            alert('successfully executed the workflow');
        }
    }
}

Expand only selected tab using java script in CRM 2011 (After RU12)


In this article i am going to explaining how to expand only selected tab from left side navigation links and other tab will collapsed

you need to call this "SetTabonClick" javascript function on your form onload event to auto expand and collapse tabs from left side navigation links


ffunction SetTabonClick() {
    var tabs = Xrm.Page.ui.tabs.get();
    for (var i in tabs) {
        var tab = tabs[i];
        var tabName = tab.getName();
        var tabindex = 'tab' + i;
        var tabindexTab = 'tab' + i + 'Tab';
        toggleTabDisplayState(tabName, tabindex, tabindexTab);
    }
}
function toggleTabDisplayState(tabName, tabindex,tabindexTab) {
    var link = document.getElementById(tabindexTab); //tab1Tab
    link.onclick = function () {
    Mscrm.Details.loadArea(this, 'areaForm');$find('crmForm').GetTab($get(tabindex, $get('crmForm')), true);
     
        var tabs = Xrm.Page.ui.tabs.get();
        for (var i in tabs) {
            var tab = tabs[i];
            if (tab.getName() == tabName) {
                tab.setDisplayState("expanded");
            }
            else {
                tab.setDisplayState("collapsed");
            }
        }
    }
}

Friday, 4 January 2013

Change Default Calendar View in CRM 2011

In this article , I am going to explain how to change Default Calendar View "Day" to "Monthly" or Weekly"

In Personal Setting Option Go to File -> Options-> Acvivities Tab-> Default Calendar View




Expand only selected tab using java script in CRM 2011 (Without RU12)

In this article i am going to explaining how to expand only selected tab from left side navigation links and other tab will collapsed

you need to call this "SetTabonClick" javascript function on your form onload event to auto expand and collapse tabs from left side navigation links


function SetTabonClick() {
var tabs = Xrm.Page.ui.tabs.get();
    for (var i in tabs) {
        var tab = tabs[i];
        var tabName = tab.getName();
        var tabindex = 'tab' + i;
        var tabindexTab = 'tab' + i + 'Tab';
        toggleTabDisplayState(tabName, tabindex, tabindexTab);
    }
}

function toggleTabDisplayState(tabName, tabindex,tabindexTab) {
    var link = document.getElementById(tabindexTab); //tab1Tab
    link.onclick = function () {
        loadArea('areaForm');
        crmForm.GetTab($get(tabindex, crmForm), true); //tab1

        var tabs = Xrm.Page.ui.tabs.get();
        for (var i in tabs) {
            var tab = tabs[i];
            if (tab.getName() == tabName) {
                tab.setDisplayState("expanded");
            }
            else {
                tab.setDisplayState("collapsed");
            }
        }
    }
}



Monday, 24 December 2012

Code to validate an appointment in CRM 2011


In this article , I am going to explain how to Validate an appointment

For Better Understanding I divided this article in two parts
(i)      Retrieve the appointment to be validated
(ii)     Use the Validate message

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;


Retrieve an appointment
Guid _appointmentId = new Guid("0a4252a0-7e70-11d0-a5d6-28db04c10000");

ColumnSet cols = new ColumnSet("scheduledstart", "scheduledend", "statecode", "statuscode");
                    Appointment retrievedAppointment = (Appointment)_serviceProxy.Retrieve(Appointment.EntityLogicalName,
                                                               _appointmentId, cols);


Use the validate message
ValidateRequest validatedReq = new ValidateRequest();
validatedReq.Activities = new EntityCollection();
validatedReq.Activities.Entities.Add(retrievedAppointment);
validatedReq.Activities.MoreRecords = false;
validatedReq.Activities.PagingCookie = "";
validatedReq.Activities.EntityName = Appointment.EntityLogicalName;
ValidateResponse validateResp = (ValidateResponse)_serviceProxy.Execute(validatedReq);



Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    // This statement is required to enable early-bound type support.
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

           //Retrieve the appointment to be validated

            Guid _appointmentId = new Guid("0a4252a0-7e70-11d0-a5d6-28db04c10000");
            ColumnSet cols = new ColumnSet("scheduledstart", "scheduledend", "statecode", "statuscode");
            Appointment retrievedAppointment =          (Appointment)_serviceProxy.Retrieve(Appointment.EntityLogicalName,
                                                       _appointmentId, cols);
         
            //Use the Validate message

            ValidateRequest validatedReq = new ValidateRequest();
            validatedReq.Activities = new EntityCollection();
            validatedReq.Activities.Entities.Add(retrievedAppointment);
            validatedReq.Activities.MoreRecords = false;
            validatedReq.Activities.PagingCookie = "";
            validatedReq.Activities.EntityName = Appointment.EntityLogicalName;
            ValidateResponse validateResp = (ValidateResponse)_serviceProxy.Execute(validatedReq);


}


Thursday, 11 October 2012

Code to book an appointment in crm 2011


In this article , I am going to explain how to Book and Validate appointment

For Better Understanding I divided this article in four parts
(i)      Get the current user information
(ii)     Create the ActivityParty instance
(iii)    Create the appointment instance
(iv)    Book request message

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

Get the current user information
WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);


Create the ActivityParty instance
ActivityParty party = new ActivityParty
{
    PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId)
};


Create the appointment instance
Appointment appointment = new Appointment
{
    Subject = " Appointment 1",
    Description = "Appointment to Book.",
    ScheduledStart = DateTime.Now.AddHours(1),
    ScheduledEnd = DateTime.Now.AddHours(2),
    Location = "Office",
    RequiredAttendees = new ActivityParty[] { party },
    Organizer = new ActivityParty[] { party }
};


Book Request message
BookRequest book = new BookRequest
{
    Target = appointment
};
BookResponse booked = (BookResponse)_serviceProxy.Execute(book);
Guid _appointmentId = booked.ValidationResult.ActivityId;


Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());


    // Get the current user information
    WhoAmIRequest userRequest = new WhoAmIRequest();
    WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);

    // Create the ActivityParty instance.
    ActivityParty party = new ActivityParty
    {
        PartyId = new EntityReference(SystemUser.EntityLogicalName, userResponse.UserId)
    };


    // Create the appointment instance.
    Appointment appointment = new Appointment
    {
        Subject = " Appointment 1",
        Description = "Appointment to Book.",
        ScheduledStart = DateTime.Now.AddHours(1),
        ScheduledEnd = DateTime.Now.AddHours(2),
        Location = "Office",
        RequiredAttendees = new ActivityParty[] { party },
        Organizer = new ActivityParty[] { party }
    };



    // Use the Book request message.
    BookRequest book = new BookRequest
    {
        Target = appointment
    };
    BookResponse booked = (BookResponse)_serviceProxy.Execute(book);
    Guid _appointmentId = booked.ValidationResult.ActivityId;

}

Wednesday, 10 October 2012

Code to retrieve the schedule of Multiple users in CRM 2011

In this article , I am going to explain how to  retrieve the schedule of Multiple users

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

    // Get the current user's information.
    WhoAmIRequest userRequest = new WhoAmIRequest();
    WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
    Guid _currentUserId = userResponse.UserId;

    // Create another user
    Guid _otherUserId = new Guid("0a4252a0-7e70-11d0-a5d6-28db04c10000");
         

    // Retrieve the schedule of the current and the other user.                                            
    QueryMultipleSchedulesRequest scheduleRequest = new QueryMultipleSchedulesRequest();
    scheduleRequest.ResourceIds = new Guid[2];
    scheduleRequest.ResourceIds[0] = _currentUserId;
    scheduleRequest.ResourceIds[1] = _otherUserId;
    scheduleRequest.Start = DateTime.Now;
    scheduleRequest.End = DateTime.Today.AddDays(7);
    scheduleRequest.TimeCodes = new TimeCode[] { TimeCode.Available };

    QueryMultipleSchedulesResponse scheduleResponse = (QueryMultipleSchedulesResponse)_serviceProxy.Execute(scheduleRequest);
                   
}


Code to retrieve the schedule of a system user in CRM 2011

In this article , I am going to explain how to  retrieve the schedule of a system user

Namespace need to include 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Crm.Sdk.Messages;

Complete Code
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
                                                    serverConfig.HomeRealmUri,
                                                    serverConfig.Credentials,
                                                    serverConfig.DeviceCredentials))
{
    _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

                   
    // Get the current user's information.
    WhoAmIRequest userRequest = new WhoAmIRequest();
    WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);

    // Retrieve the schedule of the current user.                                            
    QueryScheduleRequest scheduleRequest = new QueryScheduleRequest
    {
        ResourceId = userResponse.UserId,
        Start = DateTime.Now,
        End = DateTime.Today.AddDays(7),
        TimeCodes = new TimeCode[] { TimeCode.Available }
    };
    QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)_serviceProxy.Execute(scheduleRequest);
}

Friday, 10 August 2012

Soap XML RetrieveMultiple using javascript in CRM 2011


In this article , I am going to explain how to use Soap XML Retrieve web service
http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple

In this javascript code i am fetching all contact have same value as custom attribute value

Soap XML retrievemutliple
var contactname = Xrm.Page.getAttribute("new_contact").getValue();
var authenticationHeader = GenerateAuthenticationHeader();
if (contactname != null && contactname != "undefined") {
    var Accountxml = "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
    authenticationHeader +
    "  <soap:Body>" +
    "    <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    "      <query xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:QueryExpression\'>" +
    "        <q1:EntityName>contact</q1:EntityName>" +

    "        <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
    "          <q1:Attributes>" +
    "            <q1:Attribute>address1_city</q1:Attribute>" +
    "            <q1:Attribute>address1_stateorprovince</q1:Attribute>" +
    "          </q1:Attributes>" +
    "        </q1:ColumnSet>" +

    "        <q1:Distinct>false</q1:Distinct>" +

    "        <q1:PageInfo>" +
    "          <q1:PageNumber>1</q1:PageNumber>" +
    "          <q1:Count>1</q1:Count>" +
    "        </q1:PageInfo>" +

    "        <q1:Criteria>" +
    "          <q1:FilterOperator>And</q1:FilterOperator>" +
    "          <q1:Conditions>" +
    "            <q1:Condition>" +
    "              <q1:AttributeName>firstname</q1:AttributeName>" +
    "              <q1:Operator>Equal</q1:Operator>" +
    "              <q1:Values>" +
    "                <q1:Value xsi:type=\"xsd:string\">" + contactname + "</q1:Value>" +
    "              </q1:Values>" +
    "            </q1:Condition>" +
    "          </q1:Conditions>" +
    "        </q1:Criteria>" +
    "      </query>" +
    "    </RetrieveMultiple>" +
    "  </soap:Body>" +
    "</soap:Envelope>" +
    "";
    // Create an instance of an XMLHTTP object.
    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open(
            "POST",
            "/mscrmservices/2007/CrmService.asmx",
            false
            );

    xmlHttpRequest.setRequestHeader(
            "SOAPAction",
            "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple"
            );

    xmlHttpRequest.setRequestHeader(
            "Content-Type", "text/xml; charset=utf-8"
            );

    xmlHttpRequest.setRequestHeader(
            "Content-Length", Accountxml.length
            );

    // Send the XMLHttp request.
    xmlHttpRequest.send(Accountxml);
    // Capture the XMLHttp response in XML format.
    var resultXml = xmlHttpRequest.responseXML;

    if (resultXml.selectSingleNode("//q1:address1_city") != null) {         Xrm.Page.getAttribute("address1_city").setValue(resultXml.selectSingleNode("//q1:address1_city").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_city").setValue(null);
    }


    if (resultXml.selectSingleNode("//q1:address1_stateorprovince") != null) {         Xrm.Page.getAttribute("address1_stateorprovince").setValue(resultXml.selectSingleNode("//q1:address1_stateorprovince").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(null);
    }

}

Soap XML Retrieve using javascript in CRM 2011

In this article , I am going to explain how to use Soap XML Retrieve web service
http://schemas.microsoft.com/crm/2007/WebServices/Retrieve

In this javascript code i am fetching Account entity address into using  Contact parentcustomerid attribute and filling in Contact address fields

Soap XML retrieve

if (Xrm.Page.getAttribute("parentcustomerid").getValue() != null) {
    //acount guid no
    var parentcustomerID = Xrm.Page.data.entity.attributes.get("parentcustomerid").getValue()[0].id;
    var xml = "<?xml version='1.0' encoding='utf-8'?>" +
    "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
    " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
    " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
    GenerateAuthenticationHeader() +
    "<soap:Body>" +
    "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
    "<entityName>account</entityName>" +
    "<id>" + parentcustomerID + "</id>" +
    "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>" +
        "<q1:Attributes>" +
            "<q1:Attribute>address1_addresstypecode</q1:Attribute>" +
            "<q1:Attribute>address1_name</q1:Attribute>" +
            "<q1:Attribute>address1_line1</q1:Attribute>" +
            "<q1:Attribute>address1_line2</q1:Attribute>" +
            "<q1:Attribute>address1_city</q1:Attribute>" +
            "<q1:Attribute>address1_stateorprovince</q1:Attribute>" +
            "<q1:Attribute>address1_postalcode</q1:Attribute>" +
            "<q1:Attribute>address1_country</q1:Attribute>" +
            "<q1:Attribute>address1_telephone1</q1:Attribute>" +
        "</q1:Attributes>" +
    "</columnSet>" +
    "</Retrieve>" +
    "</soap:Body>" +
    "</soap:Envelope>";
    var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
    xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
    xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
    xmlHttpRequest.send(xml);
    var resultXml = xmlHttpRequest.responseXML;

    if (resultXml.selectSingleNode("//q1:address1_addresstypecode") != null) { Xrm.Page.getAttribute("address1_addresstypecode").setValue(resultXml.selectSingleNode("//q1:address1_addresstypecode").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_addresstypecode").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_name") != null) {
Xrm.Page.getAttribute("address1_name").setValue(resultXml.selectSingleNode("//q1:address1_name").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_name").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_line1") != null) {
Xrm.Page.getAttribute("address1_line1").setValue(resultXml.selectSingleNode("//q1:address1_line1").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_line1").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_line2") != null) {
Xrm.Page.getAttribute("address1_line2").setValue(resultXml.selectSingleNode("//q1:address1_line2").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_line2").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_city") != null) {
Xrm.Page.getAttribute("address1_city").setValue(resultXml.selectSingleNode("//q1:address1_city").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_city").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_stateorprovince") != null) {
Xrm.Page.getAttribute("address1_stateorprovince").setValue(resultXml.selectSingleNode("//q1:address1_stateorprovince").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_postalcode") != null) {
Xrm.Page.getAttribute("address1_postalcode").setValue(resultXml.selectSingleNode("//q1:address1_postalcode").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_postalcode").setValue(null);
    }

    if (resultXml.selectSingleNode("//q1:address1_country") != null) {
Xrm.Page.getAttribute("address1_country").setValue(resultXml.selectSingleNode("//q1:address1_country").nodeTypedValue);
    }
    else {
        Xrm.Page.getAttribute("address1_country").setValue(null);
    }
}

Open popup window using javascript in CRM 2011

In this article , I am going to explain how to open popup window

CRM function to open a Popup window
var url = "http://crm2011:5555/test/main.aspx?etn=account&pagetype=entityrecord";
var name = "popup";
var width = 800;
var height = 600;
var feature = "status=1";
openStdWin(url, name, width, height, feature);

Set focus on control using javascript in CRM 2011

In this article , I am going to explain how to set focus on control

Set focus
Xrm.Page.getControl("attributename").setFocus(true);

Expand / Collapse tab using javascript in CRM 2011

In this article , I am going to explain how to expand and collapse tabs

Expand tab
Xrm.Page.ui.tabs.get("tabname").setDisplayState('expanded');

Collapse tab
Xrm.Page.ui.tabs.get("tabname").setDisplayState('collapsed');

Thursday, 9 August 2012

Hide and Show section using javascript in CRM 2011

In this article , I am going to explain how to hide section

Hiding Section
Xrm.Page.ui.tabs.get(tabIndex).sections.get(sectionIndex).setVisible(false);
or
Xrm.Page.ui.tabs.get(tabIndex).sections.get("sectionName").setVisible(false);

Showing Section
Xrm.Page.ui.tabs.get(tabIndex).sections.get(sectionIndex).setVisible(true);
or
Xrm.Page.ui.tabs.get(tabIndex).sections.get("sectionName").setVisible(true);

Hide and Show tab using javascript in CRM 2011

In this article , I am going to explain how to hide and show tab

Hiding tab
Xrm.Page.ui.tabs.get(tabindex).setVisible(false);
or
Xrm.Page.ui.tabs.get("tabname").setVisible(false);

Showing tab
Xrm.Page.ui.tabs.get(tabindex).setVisible(true);
or
Xrm.Page.ui.tabs.get("tabname").setVisible(true);

Get data in fields that have changed on form using javascript in CRM 2011

In this article , I am going to explain how to get only changed data

Get changed data 
Xrm.Page.data.entity.getDataXml()



Get current user roles using javascript in CRM 2011

In this article , I am going to explain how to get current user roles

Current user roles
var UserRoles = Xrm.Page.context.getUserRoles();



Retrieve form all controls using javascript in CRM 2011

In this article , I am going to explain how to retrieve form all controls

Retrieve all controls
Xrm.Page.ui.controls.forEach(function (control, index) {
    var attribute = control.getAttribute();
    if (attribute != null) {
        var attributeName = attribute.getName();
    }
});