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

Refresh ribbon using javascript in CRM 2011

In this article , I am going to explain how to refresh current entity ribbon

Refresh ribbon
Xrm.Page.ui.refreshRibbon()



Attach event to attribute using javascript in CRM 2011

In this article , I am going to explain how to attach event to attribute

Attach event to attribute

crmForm.all.new_isdue.attachEvent("onclick", Onisdueclick);
function  Onisdueclick () {
    alert('Hi');
}


Get Current user id using javascript in CRM 2011

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

Get Current user id
var userID = Xrm.Page.context.getUserId();


Hide a attribute on form using javascript in CRM 2011

In this article , I am going to explain how to hide a attribute on Form

Hide a attribute
Xrm.Page.ui.controls.get("attributename").setVisible(false);



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 on control
Xrm.Page.ui.controls.get("attributename").setFocus();


Save and Close function in javascript for CRM 2011

In this article , I am going to explain javascript save and close functions

Save function
Xrm.Page.data.entity.save();

Save and Close function
Xrm.Page.data.entity.save("saveandclose");

Save and New function
Xrm.Page.data.entity.save("saveandnew");

Close function
Xrm.Page.ui.close();


Get Form type using javascript in CRM 2011

In this article , I am going to explain how to get form type

Get from type
var type = Xrm.Page.ui.getFormType();

getFromType() function returns integer value for different Form states
0 - undefined
1 - Create
2 - Update
3 - Read Only
4 - Disabled
5 - Quick Create (Deprecated)
6 - Bulk Edit



Get and Set control disabled using javascript in CRM 2011

In this article , I am going to explain how to get and set control disable

Get disable control
var isdisable = Xrm.Page.ui.controls.get("attributename").getDisabled();
True value shows disable field

Set control disable
Xrm.Page.ui.controls.get("attributename").setDisabled(true);


Get Current record ID using javascript in CRM 2011

In this article , I am going to explain how to get current record id

Get current record id
var Id = Xrm.Page.data.entity.getId();



Get Server URL using javascript in CRM 2011

In this article , I am going to explain how to get crm server base URL

Get server URL
var serverURL = Xrm.Page.context.getServerUrl();



Wednesday, 8 August 2012

Get Organization Name using javascript in CRM 2011

In this article , I am going to explain how to get current organization name using javascript

Get current organization name
var orgName = Xrm.Page.context.getOrgUniqueName();



Check modified Form using javascript in CRM 2011

In this article , I am going to explain how to check , form is modified or not using getIsDirty() function.
This function will return True in case of form is modified

Get modified form
var ismodified = Xrm.Page.data.entity.getIsDirty();



Get the current entity name using javascript in CRM 2011

In this article , I am going to explain how to get current entity name

Get current entity name
var entity = Xrm.Page.data.entity.getEntityName();

Get the label name of the attribute using javascript in CRM 2011

In this article , I am going to explain how to get attribute label value

Get attribute label name
var label = Xrm.Page.getControl("atrributename").getLabel()

Get OptionSet attribute value and text using javascript in CRM 2011

In this article , I am going to explain how to get OptionSet value and text

var optionset = Xrm.Page.getAttribute("attributename")

Get Optionset Text
var text = optionset.getText();

Get Optionset Value
var value = optionset.getValue();

Tuesday, 7 August 2012

Set attribute requirement level using javascript in CRM 2011


In this article , I am going to explain how to set attribute requirement level using javascript

Requirement level setting
Xrm.Page.getAttribute("attributename").setRequiredLevel("none");
Xrm.Page.getAttribute("attributename").setRequiredLevel("required");
Xrm.Page.getAttribute("attributename").setRequiredLevel("recommended");

Get and Set lookup value using javascript in CRM 2011

In this article , I am going to explain how to set and get CRM lookup attribute value using javascript

Get a lookup value
var lookup = new Array();
lookup = Xrm.Page.getAttribute("attributename").getValue();
if (lookup != null) {
    var name = lookup[0].name;
    var id = lookup[0].id;
    var entityType = lookup[0].entityType;
}

Set a lookup value
var lookup = new Array();
lookup[0] = new Object();
lookup[0].id = recorid;
lookup[0].name = recordname;
lookup[0].entityType = entityname;
Xrm.Page.getAttribute("attributename").setValue(lookup);

Alternate method to set lookup value
Xrm.Page.getAttribute("attributename").setValue([{ id: recorid, name: recordname, entityType: entityname}]);


Get and Set attribute value using javascript in CRM 2011

In this article , I am going to explain how to set and get CRM attribute value using javascript

Get Attribute Value
var name = Xrm.Page.getAttribute("attributename").getValue();

Set Attribute Value
Xrm.Page.getAttribute("attributename").setValue('Navish');

Send an Email in CRM 2011


In this article , I am going to explain how to send an email

For Better Understanding I divided this article in four parts
(i)      Create the 'From:' activity party for the email
(ii)     Create the 'To:' activity party for the email
(iii)    Create an e-mail message
(iv)    Create the request to send email

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

Create the 'From:' activity party for the email
ActivityParty fromParty = new ActivityParty
{
    PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
};

Create the 'To:' activity party for the email
ActivityParty toParty = new ActivityParty
{
    PartyId = new EntityReference(Contact.EntityLogicalName, _contactId)
};

Create an e-mail message
Email email = new Email
{
    To = new ActivityParty[] { toParty },
    From = new ActivityParty[] { fromParty },
    Subject = "e-mail",
    Description = "SendEmail Message.",
    DirectionCode = true
};

Create the request to send email
SendEmailRequest sendEmailreq = new SendEmailRequest
{
    EmailId = _emailId,
    TrackingToken = "",
    IssueSend = true
};

SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);


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

    Guid _contactId = new Guid("67B45Cdf-C56F-456F-B145-1237435430E6");

    WhoAmIRequest systemUserRequest = new WhoAmIRequest();
    WhoAmIResponse systemUserResponse = (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);
    Guid _userId = systemUserResponse.UserId;

    // Create the 'From:' activity party for the email
    ActivityParty fromParty = new ActivityParty
    {
        PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
    };

    // Create the 'To:' activity party for the email
    ActivityParty toParty = new ActivityParty
    {
        PartyId = new EntityReference(Contact.EntityLogicalName, _contactId)
    };

    // Create an e-mail message.
    Email email = new Email
    {
        To = new ActivityParty[] { toParty },
        From = new ActivityParty[] { fromParty },
        Subject = "e-mail",
        Description = "SendEmail Message.",
        DirectionCode = true
    };
    Guid _emailId = _serviceProxy.Create(email);

    // Use the SendEmail message to send an e-mail message.
    SendEmailRequest sendEmailreq = new SendEmailRequest
    {
        EmailId = _emailId,
        TrackingToken = "",
        IssueSend = true
    };

    SendEmailResponse sendEmailresp = (SendEmailResponse)_serviceProxy.Execute(sendEmailreq);
}

Send an Email Using a Template in CRM 2011

In this article , I am going to explain how to send an email using template id

For Better Understanding I divided this article in four parts
(i)      Create the 'From:' activity party for the email
(ii)     Create the 'To:' activity party for the email
(iii)    Create an e-mail message
(iv)    Create the request to send email

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

Create the 'From:' activity party for the email
ActivityParty fromParty = new ActivityParty
{
    PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
};

Create the 'To:' activity party for the email
ActivityParty toParty = new ActivityParty
{
    PartyId = new EntityReference(Contact.EntityLogicalName, _contactId)
};

Create an e-mail message
Email email = new Email
{
    To = new ActivityParty[] { toParty },
    From = new ActivityParty[] { fromParty },
    Subject = "e-mail",
    Description = "SendEmailFromTemplate Message.",
    DirectionCode = true
};

Create the request to send email
SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
{
    Target = email,

    // Use a built-in Email Template of type "contact".
    TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),

    // The regarding Id is required, and must be of the same type as the Email Template.
    RegardingId = _contactId,
    RegardingType = Contact.EntityLogicalName
};

SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)_serviceProxy.Execute(emailUsingTemplateReq);
Guid _emailId = emailUsingTemplateResp.Id;

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

    Guid _contactId = new Guid("67B45Cdf-C56F-456F-B145-1237435430E6");

    WhoAmIRequest systemUserRequest = new WhoAmIRequest();
    WhoAmIResponse systemUserResponse = (WhoAmIResponse)_serviceProxy.Execute(systemUserRequest);
    Guid _userId = systemUserResponse.UserId;

    // Create the 'From:' activity party for the email
    ActivityParty fromParty = new ActivityParty
    {
        PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId)
    };

    // Create the 'To:' activity party for the email
    ActivityParty toParty = new ActivityParty
    {
        PartyId = new EntityReference(Contact.EntityLogicalName, _contactId)
    };

    // Create an e-mail message.
    Email email = new Email
    {
        To = new ActivityParty[] { toParty },
        From = new ActivityParty[] { fromParty },
        Subject = "e-mail",
        Description = "SendEmailFromTemplate Message.",
        DirectionCode = true
    };

    // Create the request to send email
    SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest
    {
        Target = email,

        // Use a built-in Email Template of type "contact".
        TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"),

        // The regarding Id is required, and must be of the same type as the Email Template.
        RegardingId = _contactId,
        RegardingType = Contact.EntityLogicalName
    };

    SendEmailFromTemplateResponse emailUsingTemplateResp = (SendEmailFromTemplateResponse)_serviceProxy.Execute(emailUsingTemplateReq);
    Guid _emailId = emailUsingTemplateResp.Id;
}