Thursday 5 September 2013

Retrieve OptionSet Text in CRM 2011 using C# in Plugin

Retrieve Normal(Local) Option Set Text


// Get Normal option set Text
string optionsetText = entity.FormattedValues["new_optionset"];

or

string optionsetText = entity.GetFormattedAttributeValue("new_optionset");

Retrieve Global Option Set Text

int OptionsetValue = ((Microsoft.Xrm.Sdk.OptionSetValue)entity["new_localoptionset"]).Value;
string GlobaloptionsetText= GetOptionsetText(entity, service, "new_globaloptionset", OptionsetValue );



   // Retrieves Global Option set Selected Text
        // Parameters: 1. Entity Name   2. Service  3. Global Option Set Name   4. optionset selected value
        public string GetOptionsetText(Entity entity, IOrganizationService service,string  optionsetName,int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;
            try
            {


                RetrieveOptionSetRequest retrieveOptionSetRequest =
                    new RetrieveOptionSetRequest
                    {
                        Name = optionsetName
                    };

                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse =
                    (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);

                // Access the retrieved OptionSetMetadata.
                OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                // Get the current options list for the retrieved attribute.
                OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
                foreach (OptionMetadata optionMetadata in optionList)
                {
                    if (optionMetadata.Value == optionsetValue)
                    {
                        optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
break;
                    }
                }
            }
            catch (Exception)
            {


                throw;
            }
            return optionsetSelectedText;
        }

Monday 19 August 2013

How to hide the “New” or “Properties” button from the CRM 2011 Lookup Dialog

How to hide the “New” or “Properties” button from the CRM 2011 Lookup Dialog.

Here’s the new way to hide the “New” button:

var lookupControl = Sys.Application.findComponent("some_lookupid");
 
  if (lookupControl != null)
  {
       lookupControl._element._behaviors[0].AddParam("ShowNewButton", 0);

   }

Display Custom Advance Find view in Iframe in CRM 2011 by Guru Prasad

Display Custom Advance Find view in Iframe in CRM 2011  by Guru Prasad

Hi All, To bind FetchXml to Iframe Adi Katz,MVP has provided nice article to do in CRM4.0. Thanks Adi Katz for the great article. I just started converting it to work with CRM 2011. Here is the working copy of mine, to bind FetchXml to Iframe.


function loadIFrame() {

    window.fetchActivtities = new FetchViewer("IFRAME_TEST");
    fetchActivtities.FetchXml = getFetchXml();
    fetchActivtities.LayoutXml = getLayoutXml();
    fetchActivtities.Entity = "activitypointer";
    fetchActivtities.QueryId = "{00000000-0000-0000-00aa-000010001899}"; // view GUID
    fetchActivtities.RegisterOnTab(2); //IFRAME TAB INDEX


}



function getFetchXml() {

//  FetchXML Query
    return ' <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">' +
                '<entity name="activitypointer">' +
                 ' <attribute name="subject" />' +
                 ' <attribute name="scheduledstart" />' +
                 ' <attribute name="regardingobjectid" />' +
                 ' <attribute name="prioritycode" />' +
                 ' <attribute name="scheduledend" />' +
                 ' <attribute name="activitytypecode" />' +
                 ' <attribute name="instancetypecode" />' +
                 ' <order attribute="scheduledend" descending="false" />' +
                '<filter type="and">'+
                  '<condition attribute="regardingobjectid" operator="in">'+
                    '<value  uitype="account">{7CC58DF6-3114-E111-8E22-1CC1DEEAE7D7}</value>'+                  
                 ' </condition>'+
                '</filter>'+
                '  <attribute name="activityid" />' +
               ' </entity>' +
             ' </fetch>';

}

function getLayoutXml() {

// grid layout, you can get easily from Customization.xml file
    return '<grid name="resultset" object="4200" jump="subject" select="1" icon="1" preview="1">' +
               ' <row name="result" id="activityid" multiobjectidfield="activitytypecode">' +
               '   <cell name="instancetypecode" width="100" ishidden="1" />' +
               ' </row>' +
             ' </grid>';

}

function FetchViewer(iframeId) {
    var Instance = this;
    var vDynamicForm;
    var m_iframeTab;
    var m_iframeDoc;

    Instance.Entity = "";
    Instance.Iframe = null;
    Instance.FetchXml = "";
    Instance.QueryId = "";
    Instance.LayoutXml = "";

    Instance.RegisterOnTab = function (tabIndex) {
        Instance.Iframe = document.getElementById(iframeId);

        if (!Instance.Iframe)
            return alert("Iframe " + iframeId + " is undefined");

        m_iframeDoc = getIframeDocument();
        var loadingGifHTML = "<table height='100%' width='100%' style='cursor:wait'>";
        loadingGifHTML += "<tr>";
        loadingGifHTML += "<td valign='middle' align='center'>";
        loadingGifHTML += "<img alt='' src='/_imgs/AdvFind/progress.gif'/>";
        loadingGifHTML += "<div/><b>Loading View...</b>";
        loadingGifHTML += "</td></tr></table>";
        m_iframeDoc.body.innerHTML = loadingGifHTML;

        Instance.Refresh();

    }

    function RefreshOnReadyStateChange() {

        if (Instance.Iframe.readyState != 'complete')
            return;

        Instance.Refresh();
    }

    Instance.Refresh = function () {
   
        if (!Instance.Iframe)
            return alert("Iframe " + iframeId + " is undefined");

        m_iframeDoc = getIframeDocument();

        Instance.Iframe.detachEvent("onreadystatechange", RefreshOnReadyStateChange);

        var create = m_iframeDoc.createElement;
        var append1 = m_iframeDoc.appendChild;
        vDynamicForm = create("<FORM name='vDynamicForm' method='post'>");

        var append2 = vDynamicForm.appendChild;
        append2(create("<INPUT type='hidden' name='FetchXml'>"));
        append2(create("<INPUT type='hidden' name='LayoutXml'>"));
        append2(create("<INPUT type='hidden' name='EntityName'>"));
        append2(create("<INPUT type='hidden' name='DefaultAdvFindViewId'>"));
        append2(create("<INPUT type='hidden' name='ViewType'>"));
        append1(vDynamicForm);

        vDynamicForm.action = prependOrgName("/AdvancedFind/fetchData.aspx");
        vDynamicForm.FetchXml.value = Instance.FetchXml;
        vDynamicForm.LayoutXml.value = Instance.LayoutXml;
        vDynamicForm.EntityName.value = Instance.Entity;
        vDynamicForm.DefaultAdvFindViewId.value = Instance.QueryId;
        vDynamicForm.ViewType.value = 1039;
        vDynamicForm.submit();


        Instance.Iframe.attachEvent("onreadystatechange", OnViewReady);
    }

    function OnViewReady() {
        if (Instance.Iframe.readyState != 'complete') return;

        Instance.Iframe.style.border = 0;
        Instance.Iframe.detachEvent("onreadystatechange", OnViewReady);
        m_iframeDoc = getIframeDocument();
        m_iframeDoc.body.scroll = "no";
        m_iframeDoc.body.style.padding = "0px";
    }

    function getIframeDocument() {
        return Instance.Iframe.contentWindow.document;
    }

}

Monday 12 August 2013

Sub Grid Custom Filter in MSCRM 2011

function FilterContactsBasedLookUpFiled() {

    var grid = document.getElementById('gridname');

    if (grid == null) {
        setTimeout('FilterContactsBasedOnShipTo()', 2000);
    }
    else {

        var lookupfield = new Array;
        var lookupid = null;

        lookupfield = Xrm.Page.getAttribute("Lookup").getValue();

        if (lookupfield != null) {

            lookupid = lookupfield[0].id;
        }

        //Else the function will return and no code will be executed.

        else {

            return;
        }

        //This method is to ensure that grid is loaded before processing.


        //This is the fetch xml code which will retrieve all the order products related to the order selected for the case.
        var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
        fetchXml += "<entity name='qcg_contact_shipping_address'>";
        fetchXml += " <attribute name='qcg_shippingaddress' />";
        fetchXml += "<attribute name='qcg_role' />";
        fetchXml += "<attribute name='qcg_contact' />";
        fetchXml += "<order attribute='qcg_shippingaddress' descending='false' />";
        fetchXml += "<link-entity name='contact' from='contactid' to='qcg_contact' alias='am'>";
        fetchXml += " <filter type='and'>";
        fetchXml += "  <condition attribute='parentcustomerid' operator='eq'  value='" + lookupid + "' />";
        fetchXml += "</filter>";
        fetchXml += "</link-entity>";
        fetchXml += "</entity>";
        fetchXml += "</fetch>";

        //Setting the fetch xml to the sub grid.

        grid.control.SetParameter("fetchXml", fetchXml);

        //This statement will refresh the sub grid after making all modifications.

        grid.control.refresh();
    }

}

Thursday 8 August 2013

Formula filed functionality in MSCRM 2011 like Sales Force.

This needs Jquery  Library support


// This function is called in onchange of some  look up field.
function RetrieveAccountInfo() {

// Get the lookup filed id value
    customerAttribute = XP.data.entity.attributes.get("xxxid");

    if (customerAttribute != null) {

        customerValue = customerAttribute.getValue();
        if (customerValue != null && customerValue[0] != null) {
            customerType = customerValue[0].typename;
            customerId = customerValue[0].id;
            return retrieveRecord(customerId, "AccountSet", retrieveCompleted, null);
        }
    }
}

// Firing the Rest call to get the all the attributes of this look up record
function retrieveRecord(id, odataSetName, successCallback, errorCallback) {
    //var context = GetGlobalContext();

    var odataEndPoint = "/XRMServices/2011/OrganizationData.svc";
    if (!id) {
        alert("record id is required.");
        return;
    }
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + odataEndPoint + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {

            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (successCallback) {
                successCallback(data.d, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}

// Call Back method to parse values from response
function retrieveCompleted(data, textStatus, XmlHttpRequest) {
    /*Display the required fields and hide if the fields are null */
    entity = data;
    if (!IsNull(entity.xxxxfield. value)) {

        if (entity.xxxxfield.LogicalName == "pricelevel") {

            var lookupValue = new Array();
            lookupValue[0] = new Object();
            lookupValue[0].id = entity.xxxxfield.Id;
            lookupValue[0].name = entity.xxxxfield.Name;
            lookupValue[0].entityType = entity.xxxxfield.LogicalName;
            XP.getAttribute("pricelevelid").setValue(lookupValue);


        }
        else {
            XP.getAttribute("xxxxfiledvalue").setValue(null);
        }
    }
    else {
        XP.getAttribute("xxxxfiledvalue").setValue(null);
    }
}