Search This Blog

Tuesday, December 2, 2014

How to get Display Status of Tab

Below code will return you the display status of tab.

var tabState = Xrm.Page.ui.tabs.get('economyandinformation_tab').getDisplayState();

It will return you the tab status in below format (expanded or collapsed)
 

Monday, December 1, 2014

Cloning Microsoft CRM Records

Hi Below is the way you can create a multiple copies of any record of any entity.
 
Let say I have 1 record of contact which I need to make close
 
// Parent Contact Record
 
Entity oldcontact = crmservice.Retrieve("contact", ContactId,new ColumnSet(true));

// Child Contact Record
 
Entity newcontact;

newcontact = oldcontact.Clone(true);

newcontact.Attributes.Remove("contactid"); // This is very important step in cloning as you have to avoid duplicate primary key error.

newcontact.Id = Guid.NewGuid(); // create new GUID for new record


crmservice.Create(newcontact);

And you will get a copy of parentcontact record into childcontact

Enjoy.
 

Friday, November 28, 2014

How to read OptionSet Attribute in MS CRM 2011/13

Following is the code on how to read OptionSet Value into Array in JavaScript

function GetMultiSelectOptions(id) {
   
    var optionsArray = new Array();
    var options = Xrm.Page.getAttribute("ap_postprofiletasks").getOptions();  // Read OptionSet Field
    if (options && options.length)
    {
        for (var i = 0; i < options.length; i++) {
            var option = options[i];
            if (option.value && option.text) {
                if (option.value == 778210006) {
                    alert(option.text);
                    optionsArray.push({ text: option.text, value: option.value });
                }
            }
        }
       
    }
    return optionsArray;
}

using OData in Javascript MS CRM 2013


Here is code  for how to fetch entity records from JavaScript Using OData
use Schema names for field names

function MainFunction()
{
    var project = getLookupId("ap_project");
    if (project != null) {
        var filter = "&$filter=";
        filter += "ap_projectId eq guid'" + project + "'";
        var odataQuery = "/ap_projectSet?$select=ap_projectId,ap_TypeOfContract" + filter;
        ExecuteQuery(odataQuery, true, function (data) {
            if (data && data.d && data.d.results && data.d.results[0])
           {
               // Get Results here
                       var typeofcontract = data.d.results[0].yourfieldname.Value;
              
            }
        });
    }
}

function ExecuteQuery(odataQuery, sync, callback) {
    var async = true;
    if (sync) {
        async = false;
    }
    var odataPath = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc";
    var odataUrl = odataPath + odataQuery;
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: odataUrl,
        async: async,
        beforeSend: function (xmlHttpRequest) {
            xmlHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, xmlHttpRequest) {
            if (callback) {
                callback(data);
            }
        },
        error: function (xmlHttpRequest, textStatus, errorObject) {
            alert("Error Occurred : " + textStatus + ": " + JSON.parse(xmlHttpRequest.responseText).error.message.value);
        }
    });
}

function getLookupId(lookupName) {
    var lookupItem = new Array();
    lookupItem = Xrm.Page.getAttribute(lookupName).getValue();
    if (lookupItem != null) {
        return lookupItem[0].id;
    }
    else
        return null;
}

Friday, February 7, 2014

Using Xrm.Utility.openEntityForm with Parameters

Below is a code which will show how to open new Entity Record and pass parameter to the new form while opening

    var phone1 = Xrm.Page.getAttribute("ap_phone1").getValue();
    var phone2 = Xrm.Page.getAttribute("ap_phone2").getValue();
    var phone3 = Xrm.Page.getAttribute("ap_phone3").getValue();
    var phonetype1 = Xrm.Page.getAttribute("ap_phone1type").getValue();
    var phonetype2 = Xrm.Page.getAttribute("ap_phone2type").getValue();
    var phonetype3 = Xrm.Page.getAttribute("ap_phone3type").getValue();

   var parameters = {};

    parameters["ap_phone1"] = phone1;
    parameters["ap_phone2"] = phone2;
    parameters["ap_phone3"] = phone3;
    parameters["ap_phone1type"] = phonetype1;
    parameters["ap_phone2type"] = phonetype2;
    parameters["ap_phone3type"] = phonetype3;

// Opening New Record of "ap_profiling" entity , if you want to open existing record please pass recordID instead of Null in 2nd parameter



  Xrm.Utility.openEntityForm("ap_profiling", null, parameters);

Wednesday, January 29, 2014

Adding MultiSelect CheckBox on MS CRM 2011 Form

Following steps to create multi select checkbox control on MS CRM 2011 form.

1. Create a picklist fields with required options and add it to your CRM form.
2. this picklist field will be converted to checkbox control at runtime.
3. you need to create one more text field in CRM and place it on the form in hidden mode , this field is required to store and read values selected in CheckBox Control.

Call the function below on load of the form

in the below example  "ap_typeofbuilding" is my Picklist control which will be converted to CheckBox Control for Multi select options , and "ap_btypetext" is my text field to read and store values selected in checkbox control.



gMultiSelectBTList = function () {

    // PL - the picklist attribute; PLV - used to save selected picklist values 

    var PL = document.getElementById("ap_typeofbuilding");
    var PLV = document.getElementById("ap_btypetext");

    var picklist = "ap_typeofbuilding";
    var textfield = "ap_btypetext";

    if (!PLV || textfield == '') { PLV = null; }
    if (PL != null) {

        PL.style.display = "none";

        //PLV1.style.display = "none"; 

        // Create a DIV container 

        var addDiv = document.createElement("<div style='overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#ffffff;' />");

        //  var addDiv1 = document.createElement("<div style='overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#EAF3FF;' />"); 

        PL.parentNode.appendChild(addDiv);

        // Initialise checkbox controls 

        for (var i = 1; i < PL.options.length; i++) {
            var pOption = PL.options[i];

            if (!IsChecked(pOption.text))

                var addInput = document.createElement("<input type='checkbox' name=" + pOption1.text + " value=" + pOption1.value + " style='border:none; width:25px; align:left;' onclick='picklistOnClick(" + picklist + "," + textfield + ")' />");

            else

                var addInput = document.createElement("<input type='checkbox' name=" + pOption1.text + " value=" + pOption1.value + " checked='checked' style='border:none; width:25px; align:left;' onclick='picklistOnClick(" + picklist + "," + textfield + ")' />");

            var addLabel = document.createElement("<label />");

            addLabel.innerText = pOption.text;

            var addBr = document.createElement("<br>"); //it's a 'br' flag 



            PL.nextSibling.appendChild(addInput);
            PL.nextSibling.appendChild(addLabel);
            PL.nextSibling.appendChild(addBr);

        }



        // Check if it is selected 

        function IsChecked(pText) {

            if (!PLV) return;

            if (PLV.value != "") {

                var PLVT = PLV.value.split("|");

                for (var i = 0; i < PLVT.length; i++) {

                    if (PLVT[i] == pText)

                        return true;

                }

            }

            return false;

        }

        picklistOnClick = function (oPL, oPLV) {

            if (!oPLV) return;

            oPLV.value = "";

            var getInput = oPL.nextSibling.getElementsByTagName("input");

            for (var i = 0; i < getInput.length; i++) {
                if (getInput[i].checked) {

                    oPLV.value += getInput[i].nextSibling.innerText + "|";
                }

            }

            //MUST DO THIS TO TRIGGER A SAVE EVENT

            var btypetext = Xrm.Page.data.entity.attributes.get("ap_btypetext");
            btypetext.setValue(PLV.value);

        }

    }

}

This is another function which will help you to read selected values in text field and selected them in CheckBox Control ( this is for existing records )

function ReadBTPickList()
{
    var PL = crmForm.all.ap_typeofbuilding;
    var getInput = PL.nextSibling.getElementsByTagName("input");
    var allbtype = Xrm.Page.getAttribute("ap_btypetext").getValue();
    if (allbtype != null) {
        var btype = allbtype.split('|');

        for (var i = 0; i < btype.length - 1; i++) {
            for (var j = 0; j < getInput.length - 1; j++) {
                if (getInput[j].name == btype[i]) {
                    getInput[j].checked = true;
                }
            }
        }

    }
}







Update SubGrid Control at Runtime on Entity Form

Updating Subgrid control on the MS CRM Form.
below example demonstrate the Subgrid on custom entity which will filter Contact in contact sub grid , on search of specific firstname and lastname.

 


function UpdateSubGrid()
        {

            var subgridcontact = window.parent.document.getElementById("contact_subgrid");
            var subgridlead = window.parent.document.getElementById("lead_subgrid");

            var fname = window.parent.Xrm.Page.getAttribute("new_firstname").getValue();
            var lname = window.parent.Xrm.Page.getAttribute("new_lastname").getValue();
            var phonenumber = window.parent.Xrm.Page.getAttribute("new_phonenumber").getValue();

            //If this method is called from the form OnLoad, make sure that the grid is loaded before   proceeding

            if (subgridcontact == null || subgridcontact.readyState != "complete")
             {
                 setTimeout('UpdateSubGrid()', 1000);
                 return;
            }
            if (subgridlead == null || subgridlead.readyState != "complete")
            {
                setTimeout('UpdateSubGrid()', 1000);
                return;
            }

            //Update the fetchXML that will be used by the grid - Search in Contact.
     

            var fetchXml = "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>";
            fetchXml += "<entity name='contact'> <attribute name='firstname'/> <attribute name='lastname'/> <attribute name='mobilephone'/>";
            fetchXml += "<order descending='false' attribute='firstname'/>";
            fetchXml += "<filter type='and'>";
            if (fname != null)
            {
                fetchXml += "<condition attribute='firstname' value='" + fname + "%' operator='like'/>";
             
            }
            if (lname != null)
            {
                fetchXml += "<condition attribute='lastname' value='" + lname + "%' operator='like'/>";
            }
            if (phonenumber != null)
            {
                fetchXml += "<condition attribute='mobilephone' value='" + phonenumber + "%' operator='like'/>";
            }
            fetchXml += "</filter>";
            fetchXml += "</entity>";
            fetchXml += " </fetch>";

            subgridcontact.control.SetParameter("fetchXml", fetchXml);
            //Force the subgrid to refresh
            subgridcontact.control.refresh();
       }

Read Entity Attributes in MS CRM 2011

below is the way to read Entity Attributes and Display in GridView

// please connect to your CRM organization using appropriate URL

           IOrganizationService crmservice;
            CrmConnection crmconn = new CrmConnection();
            crmservice = crmconn.Connect2CRMNew(orguri);

            RetrieveEntityRequest retrieveEntityRequest = new RetrieveEntityRequest
            {
                EntityFilters = EntityFilters.All,
                LogicalName = entityname,
                RetrieveAsIfPublished = true
            };

            RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)crmservice.Execute(retrieveEntityRequest);
            EntityMetadata currentEntity = retrieveEntityResponse.EntityMetadata;
           
            // Attributes
           
            DataTable dtmain = new DataTable();
            dtmain.Columns.Add(new DataColumn("Schema name"));
            dtmain.Columns.Add(new DataColumn("Data Type"));
            dtmain.Columns.Add(new DataColumn("Size"));
            dtmain.Columns.Add(new DataColumn("Required Level"));
            dtmain.Columns.Add(new DataColumn("Is Audit Enabled"));
            dtmain.Columns.Add(new DataColumn("Is Custom Attribute"));
            dtmain.Columns.Add(new DataColumn("AttributeID"));
           
            foreach(AttributeMetadata allattributes in  currentEntity.Attributes)
            {
                DataRow dtrow = dtmain.NewRow();

                dtrow[0] = allattributes.LogicalName.ToString();
                dtrow[3] = allattributes.RequiredLevel.Value.ToString();
                dtrow[4] = allattributes.IsAuditEnabled.Value.ToString();
                dtrow[5] = allattributes.IsCustomAttribute.Value.ToString();
                dtrow[6] = allattributes.MetadataId.Value.ToString();
                dtrow[1] = allattributes.AttributeType.Value;

                switch (allattributes.AttributeType.Value.ToString())
                {
                    //case "Money":
                    //    dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.MoneyAttributeMetadata)(allattributes)).MaxValue.ToString();
                    //    break;
                    //case "Virtual":
                    //    dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.V)(allattributes)).MaxLength.ToString();
                    //    break;
                    case "Decimal":
                        dtrow[2] = ((Microsoft.Xrm.Sdk.Metadata.DecimalAttributeMetadata)(allattributes)).MaxValue.ToString();
                        break;
                    //case "Boolean":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.BooleanAttributeMetadata)(allattributes)).
                    //    break;
                    //case "State":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.StateAttributeMetadata)(allattributes)).
                    //    break;
                    case "String":
                        dtrow[2] = ((Microsoft.Xrm.Sdk.Metadata.StringAttributeMetadata)(allattributes)).MaxLength.ToString();
                        break;
                    //case "DateTime":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.DateTimeAttributeMetadata)(allattributes)).
                    //    break;
                    case "Integer":
                        dtrow[2] = ((Microsoft.Xrm.Sdk.Metadata.IntegerAttributeMetadata)(allattributes)).MaxValue.ToString();
                        break;
                    //case "Lookup":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.LookupAttributeMetadata)(allattributes)).
                    //    break;
                    //case "Uniqueidentifier":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.Uniq)(allattributes)).
                    //    break;
                    //case "Picklist":
                    //    //dtrow[6] = ((Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata)(allattributes)).OptionSet.
                    //    break;



                };
                dtmain.Rows.Add(dtrow);
            }
            gvAttributes.DataSource = dtmain.DefaultView;
            gvAttributes.DataBind();
            pnlattribute.Visible = true;
            Session.Add("TaskTable",dtmain);

Merge Records in MS CRM 2011 using C#

following in the code to Merge 2 records through Asp.Net

 // Connect to CRM 2011
                    IOrganizationService crmservice;
                    CrmConnection conn = new CrmConnection();
                    crmservice = conn.Connect2CRM();

// below are 2 sample account records





                    //D9E2197D-244C-E211-9675-005056B0000B // Test Account - Vilas M
                    //BA59DFF0-E939-E211-946D-005056B0000B // Test Company - Vilas

                    MergeRequest mreq = new MergeRequest();
                    Guid targetAccountID =  new Guid("D9E2197D-244C-E211-9675-005056B0000B");
                    Guid tobemergedAccountID =  new Guid("BA59DFF0-E939-E211-946D-005056B0000B");
                    mreq.Target = new EntityReference("account", targetAccountID);  // Target Account ID , where other account will be mergered
                    mreq.SubordinateId = tobemergedAccountID;

                    Entity entAccnt = new Entity("account");
                    entAccnt.Attributes["Address1_Line1"] = "Test";

                    mreq.UpdateContent = entAccnt;

                    MergeResponse mresp = (MergeResponse)crmservice.Execute(mreq);
                    Console.WriteLine("Sucessfully Merged !! ");