Tuesday, July 19, 2011

SharedVariables in CRM 2011 plugins

Hi All, There is a slight change in Shared Variables in CRM 2011.          

                // Passing Data to shared Variable
            context.SharedVariables.Add("PrimaryContact", (Object)contact.ToString());


            // Retrieving data from context shared variables.
                Guid contact = new Guid((string)context.SharedVariables["PrimaryContact"]);

Retrieve Attribute Data using MetaData Service in CRM 2011

Hi All, Here I am going to retrieve an Attribute Data using MetaData Service In CRM 2011

RetrieveAttributeRequest retrieveAttributeRequest = new
                RetrieveAttributeRequest
                {

                    EntityLogicalName = entityName,

                    LogicalName = attributeName,

                    RetrieveAsIfPublished = true

                };
                // Execute the request.
                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
             
// Access the retrieved attribute.

                PicklistAttributeMetadata retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

                OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray();
           
                foreach (OptionMetadata option in optionList)
                {
                    if (option.Value == selectedValue)
                    {
                        selectedOptionLabel = option.Label.UserLocalizedLabel.Label;
                        break;

                    }
                }

Wednesday, July 13, 2011

Sharing and Unsharing Records in CRM 2011

Hi All, Here I am going to share Account record with a user and then unsharing the account from the user in CRM 2011. Here is the logic to share and unshare records

sharing

 // Create the request object and set the target and principal access
GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target = new EntityReference(Account.EntityLogicalName, accountId),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal = new EntityReference(SystemUser.EntityLogicalName, userId),
                    AccessMask = actionRights
                }
            };

 // Execute the request.
GrantAccessResponse granted = (GrantAccessResponse)service.Execute(grantRequest);


Unsharing


 // Create the request object and set the target and revokee.
            RevokeAccessRequest revokeRequest = new RevokeAccessRequest()
            {
                Target = new EntityReference(Account.EntityLogicalName, accountId),
                Revokee = new EntityReference(SystemUser.EntityLogicalName, accountuserId)
            };

// Execute the request.
 RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revokeRequest);

Tuesday, July 12, 2011

Maximizing CRM Form using javascript in CRM 2011

Hi All, Maximizing CRM Form script has been changed slightly in CRM 2011. use the following code to maximize CRM Forms using javascript

window.top.moveTo(0,0);
window.top.resizeTo(screen.width, screen.height);

Monday, July 11, 2011

Retrieving optionset Lable data using Metadata service in CRM 2011

Hi All, Using OData service we are not able to get the option set selected text of an entity. Its providing only value field, but not the text. so I have used Metadata service to retrieve Option set text for the selected value.
 Here I am retrieving State option set text from country entity and assigning that option text to text field.

function RetrieveOptionsetLabel()
{
     // Entity schema name 
     var entityLogicalName = "new_country";
     // option set schema name
     var RetrieveAttributeName = "new_state";
     // Target Field schema name to which optionset text needs to be assigned
     var AssignAttributeName = "new_state";

// Option set value for which label needs to be retrieved
        var stateValue = optionValue;
     
        // Calling Metadata service to get Optionset Label
        SDK.MetaData.RetrieveEntityAsync(SDK.MetaData.EntityFilters.Attributes, entityLogicalName, null, false, function (entityMetadata) { successRetrieveEntity(entityLogicalName, entityMetadata, RetrieveAttributeName, stateValue, AssignAttributeName); }, errorDisplay);

}

// Called upon successful metadata retrieval of the entity
function successRetrieveEntity(logicalName, entityMetadata, RetrieveAttributeName, OptionValue, AssignAttributeName) {
    ///<summary>
    /// Retrieves attributes for the entity 
    ///</summary>

    var success = false;
    for (var i = 0; i < entityMetadata.Attributes.length; i++) {
        var AttributeMetadata = entityMetadata.Attributes[i];
        if (success) break;
        if (AttributeMetadata.SchemaName.toLowerCase() == RetrieveAttributeName.toLowerCase()) {
            for (var o = 0; o < AttributeMetadata.OptionSet.Options.length; o++) {
                var option = AttributeMetadata.OptionSet.Options[o];
                if (option.OptionMetadata.Value == OptionValue) {
                    Xrm.Page.getAttribute(AssignAttributeName).setValue(option.OptionMetadata.Label.UserLocalizedLabel.Label);
                    success = true;
                    break;
                }
            }
        }

    }


}


 function errorDisplay(XmlHttpRequest, textStatus, errorThrown) {

     alert(errorThrown);
 }

Note: Dont forget to add "sdk.metadata.js" resource to form before calling these methods. you can find this library in sdk "sdk\samplecode\js\soapforjscript\soapforjscript\scripts".



Saturday, July 9, 2011

Custom Lookup Filter Lookup in CRM 2011 using javascript

Hi All, Some times we will get requirement to set filterlookup using java script. CRM 2011 provides OOB Filter Lookups, but it has some limitations. For Activities they did not provided filter lookup facility. Recently i came accross Letter activity to set filter lookup. Here is the way to set filter lookup  using java script.

Here I am going to set contact lookup with selected account as parent.


function customfilterlookup(AccoundID)
{
//Show Contacts which has selected parent Account
    //build fetchxml, use Advance Find to get Fetchxml
    var viewId = "{a76b2c46-c28e-4e5e-9ddf-951b71202c9d}"; //view Guid
    var entityName = "contact"; // Entity to be filtered
    var viewDisplayName = "Active Contacts"; // Custom name for the lookup window.
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                  "<entity name='contact'>" +
                    "<attribute name='fullname' />" +
                    "<attribute name='parentcustomerid' />" +                  
                    "<attribute name='emailaddress1' />" +
                    "<attribute name='address1_telephone2' />" +
                    "<attribute name='new_city' />" +
                    "<attribute name='address1_stateorprovince' />" +
                    "<attribute name='address1_telephone1' />" +
                    "<attribute name='ownerid' />" +
                    "<attribute name='contactid' />" +
                    "<order attribute='fullname' descending='false' />" +
                    "<filter type='and'>" +
                      "<condition attribute='parentcustomerid' operator='eq'  uitype='account' value='"+AccoundID+"' />" +
                      "<condition attribute='statecode' operator='eq' value='0' />" +
                    "</filter>" +
                  "</entity>" +
                "</fetch>";
    // Build Grid Layout. building a custom view for the Lookup
    //building grid layout with the columns which needs to be displayed in the lookup view
    var layoutXml = "<grid name='resultset' " +
                    "object='1' " +
                    "jump='name' " +
                    "select='1' " +
                    "icon='1' " +
                    "preview='1'>" +
                    "<row name='result' " +
                    "id='contactid'>" + // Id/key attribute of the entity to be filtered
                    "<cell name='fullname' " +
                    "width='250' />" +
                    "<cell name='new_city' " +
                    "width='70' />" +
                    "<cell name='address1_telephone1' " +
                    "width='100' />" +
                    "</row>" +
                    "</grid>";
    // add new view to the lookup
    Xrm.Page.getControl("contact").addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
}

keep smiling.. :)

Wednesday, July 6, 2011

Retrieving Customer Address from parent Account on Contact Form using ODATA

Hi All, Here I am going to retrieve Parent Account Address on contact form using Odata in crm 2011

// Populate Customer Address from Parent Account
function PopulateCustomerAddress(ParentAccount) {

    if (ParentAccount != null) {
        var AccountId = ParentAccount.getValue()[0].id;

        // Pass odataQuery
        var odataQuery = "AccountSet?$select=Address1_Fax,Address1_Line1,Address1_Line2,Address1_StateOrProvince,Address1_Telephone1,Address1_Telephone2,new_regionid&$filter=AccountId eq guid'" + AccountId + "'";

        retrieveRecord(odataQuery, retrieveCustomerAddressCompleted, null);
    }
 
}


// Retrieve Record Details based on the odataQuery
function retrieveRecord(odataQuery, successCallback, errorCallback) {
    var context = Xrm.Page.context;
    //Retrieve the server url,
    serverUrl = context.getServerUrl();
    //The XRM OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //odataQuery is required, i.e. "AccountSet/guid('')"
    if (!odataQuery) {
        alert("odataQuery is required.");
        return;
    }

    //Asynchronous AJAX function to Retrieve a CRM record using OData
    $.ajax({
        type: "GET",
        async: false,      
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + "/" + odataQuery,
        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) {
            if (successCallback) {
                successCallback(data.d, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}

//Called upon successful Retrieval of Customer Address.
function retrieveCustomerAddressCompleted(data, textStatus, XmlHttpRequest) {

    //Get back the Account JSON object
    var Account = data.results[0];
    if (Account != null) {
        Xrm.Page.getAttribute("address1_fax").setValue(Account.Address1_Fax);
        Xrm.Page.getAttribute("address1_line1").setValue(Account.Address1_Line1);
        Xrm.Page.getAttribute("address1_line2").setValue(Account.Address1_Line2);
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(Account.Address1_StateOrProvince);
        Xrm.Page.getAttribute("address1_telephone1").setValue(Account.Address1_Telephone1);
        Xrm.Page.getAttribute("address1_telephone2").setValue(Account.Address1_Telephone2);
        
             // setting lookup field
               if (Account.new_regionid != null && Account.new_regionid .Id != null)
            SetLookupValue("new_region", Account.new_regionid .Id, Account.new_regionid .Name, Account.new_regionid .LogicalName);
    }
    
}

// Set lookup value to a field
function SetLookupValue(fieldName, id, name, entityType) {
    if (fieldName != null) {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = entityType;

        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    }
}

Dont forget to add JSON and JQuery libraries to the form. you can find it in my previous posts click here

Retrieving Entity Object Type code

// Retrieving Entity Object Type code based on entity schema name

function getObjectTypeCode(entityName) {
 
 try {

        var lookupService = new RemoteCommand("LookupService", "RetrieveTypeCode");
        lookupService.SetParameter("entityName", entityName);
        var result = lookupService.Execute();

        if (result.Success && typeof result.ReturnValue == "number") {
            return result.ReturnValue;
        } else {
            return null;
        }
    }
    catch (ex) {
        throw ex;
    }
}