Tuesday, September 20, 2011

Update Optionset, lookup data using OData service, JSON

Here I am going to update Optionset and Lookup fields using Odata Service in CRM 2011. In the SDK sample you will find only to update Text fields. After spending some time on Odata service, i got the solution to update Option set and Lookup fields.

        Here i am going to update Account information using Odata service.

function updateOptionset() {
    // Gets the record Guid
    var id = Xrm.Page.data.entity.getId();    
    var changes = {
      // Text field
        Telephone1: "123456789",
     // Option set field    
       Address1_AddressTypeCode: {  Value: 3 },
      // Lookup field
       ParentAccountId: {         
           Id: "8F8338A9-9AB2-E011-9E6D-000C29B0167C", // Guid of the parent account
           LogicalName: "account"
       }
    };
  
    //updateRecord exists in JQueryRESTDataOperationFunctions.js
    updateRecord(id, changes, "AccountSet", updateAccountCompleted, null);
}

function updateRecord(id, entityObject, odataSetName, successCallback, errorCallback) {
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();

    //The XRM OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //id is required
    if (!id) {
        alert("record id is required.");
        return;
    }
    //odataSetName is required, i.e. "AccountSet"
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }

    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(entityObject);

    //Asynchronous AJAX function to Update a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: jsonEntity,
        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.             
            XMLHttpRequest.setRequestHeader("Accept", "application/json");

            //Specify the HTTP method MERGE to update just the changes you are submitting.             
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //The MERGE does not return any data at all, so we'll add the id 
            //onto the data object so it can be leveraged in a Callback. When data 
            //is used in the callback function, the field will be named generically, "id"
            data = new Object();
            data.id = id;
            if (successCallback) {
                successCallback(data, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}


function errorHandler(xmlHttpRequest, textStatus, errorThrow) {  
    alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}

//Called upon successful Account update.
function updateAccountCompleted(data, textStatus, XmlHttpRequest) {   
    //Get back the Account JSON object
    var account = data;
    alert("Account updated: id = " + account.id);
}

Hope it helps!!!!

Adding New Group to Ribbon in CRM 2011

we have seen adding a button and renaming buttons in my previous posts. Now i am going to add a new group to the Ribbon.
Default Account Ribbon at Form Level.
After Adding New Group to Account Ribbon

1. Export the Solution to customize. And open the Customization.XML file for editing.(solution must contain sitemap)
2. Open Account RibbonDiffXml ribbon definition and then edit with the following logic
source code for the sample

 <RibbonDiffXml>
        <CustomActions>
          <CustomAction Id="Sample.account.form.CustomGroup.CustomAction" Location="Mscrm.Form.account.MainTab.Groups._children" Sequence="61">
            <CommandUIDefinition>
              <Group Id="Sample.account.form.CustomGroup.Group" Command="Sample.account.form.CustomGroup.Command" Title="Custom Group" Sequence="11" Template="Mscrm.Templates.Flexible2" Image32by32Popup="/_imgs/Workplace/remove_32.png">
                <Controls Id="Sample.account.form.CustomGroup.Controls">
                  <Button Id="Sample.account.form.CustomGroup.CustomButton1" Command="Sample.account.form.CustomGroup.CustomButton1.Command" Sequence="10" LabelText="Custom Button1" ToolTipTitle="Custom Button ToolTip" ToolTipDescription="Custom Button1 Tooltip Description " TemplateAlias="o1" Image16by16="/_imgs/ribbon/ActivityClose_16.png" Image32by32="/_imgs/ribbon/ActivtiyClose_32.png" />
                  <Button Id="Sample.account.form.CustomGroup.CustomButton2" Command="Sample.account.form.CustomGroup.CustomButton2.Command" Sequence="20" LabelText="Custom Button2" ToolTipTitle="Custom Button ToolTip" ToolTipDescription="Custom Button2 Tooltip Description " TemplateAlias="o1" Image16by16="/_imgs/ribbon/delete16.png" Image32by32="/_imgs/Workplace/remove_32.png" />
                </Controls>
              </Group>
            </CommandUIDefinition>
          </CustomAction>
          <CustomAction Id="Sample.account.form.CustomGroup.MaxSize.CustomAction" Location="Mscrm.Form.account.MainTab.Scaling._children" Sequence="71">
            <CommandUIDefinition>
              <MaxSize Id="Sample.account.form.CustomGroup.MaxSize" GroupId="Sample.account.form.CustomGroup.Group" Sequence="11" Size="LargeLarge" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="Sample.account.form.CustomGroup.CustomButton2.Command">
            <EnableRules>
              <EnableRule Id="Mscrm.Enabled" />
            </EnableRules>
            <DisplayRules />
            <Actions>
              <JavaScriptFunction Library="$Webresource:new_accountmainlib" FunctionName="MyFunction" />
              
            </Actions>
          </CommandDefinition>
          <CommandDefinition Id="Sample.account.form.CustomGroup.Command">
            <EnableRules>
              <EnableRule Id="Mscrm.Enabled" />
            </EnableRules>
            <DisplayRules />
            <Actions />
          </CommandDefinition>
          <CommandDefinition Id="Sample.account.form.CustomGroup.CustomButton1.Command">
            <EnableRules>
              <EnableRule Id="Mscrm.Enabled" />
            </EnableRules>
            <DisplayRules />
            <Actions>
              <Url Address="http://google.com" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules />
          <EnableRules />
        </RuleDefinitions>
        <LocLabels />
      </RibbonDiffXml>

3. Now import the solution and check the changes.

Hope it helps!!!!!

Thursday, August 4, 2011

Changing OOB Ribbon Button Label in CRM 2011

Hi All, Here I am going to change the OOB Ribbon Button label. Now I am going to Change OOB "DeActive" Button Lable to "InActive" on the Account Form.

Account Form Ribbon Before Changing Label for "Deactive" Button

Account Form Ribbon After Changing  "Deactive" Button Label to "InActive"

1. Open “accounribbon.xml” file from the “\sdk\samplecode\cs\client\ribbon\exportribbonxml\exportedribbonxml” location in the CRM 2011 SDK.

2. Find the "Deactive" Ribbon Button definition
 <Group Id="Mscrm.Form.account.MainTab.Save" Command="Mscrm.Enabled" Sequence="10" Title="$Resources:Ribbon.Form.MainTab.Save" Image32by32Popup="/_imgs/ribbon/Save_32.png" Template="Mscrm.Templates.Flexible2">
                <Controls Id="Mscrm.Form.account.MainTab.Save.Controls">
                  <Button Id="Mscrm.Form.account.SaveAsComplete" ToolTipTitle="$Resources:Ribbon.Form.MainTab.Save.SaveAsComplete" ToolTipDescription="$Resources(EntityDisplayName):Ribbon.Tooltip.SaveAsComplete" Command="Mscrm.SavePrimaryActivityAsComplete" Sequence="10" LabelText="$Resources:Ribbon.Form.MainTab.Save.SaveAsComplete" Alt="$Resources:Ribbon.Form.MainTab.Save.SaveAsComplete" Image16by16="/_imgs/ribbon/SaveAsCompleted_16.png" Image32by32="/_imgs/ribbon/SaveAsCompleted_32.png" TemplateAlias="o1" />
                  <Button Id="Mscrm.Form.account.Save" ToolTipTitle="$Resources:Mscrm_Form_Other_MainTab_Save_Save_ToolTipTitle" ToolTipDescription="$Resources(EntityDisplayName):Ribbon.Tooltip.Save" Command="Mscrm.SavePrimary" Sequence="20" LabelText="$Resources:Ribbon.Form.MainTab.Save.Save" Alt="$Resources:Ribbon.Form.MainTab.Save.Save" Image16by16="/_imgs/ribbon/Save_16.png" Image32by32="/_imgs/ribbon/Save_32.png" TemplateAlias="o1" />
                  <Button Id="Mscrm.Form.account.SaveAndClose" ToolTipTitle="$Resources:Mscrm_Form_Other_MainTab_Save_SaveAndClose_ToolTipTitle" ToolTipDescription="$Resources(EntityDisplayName):Ribbon.Tooltip.SaveAndClose" Command="Mscrm.SaveAndClosePrimary" Sequence="30" LabelText="$Resources:Ribbon.Form.MainTab.Save.SaveAndClose" Alt="$Resources:Ribbon.Form.MainTab.Save.SaveAndClose" Image16by16="/_imgs/FormEditorRibbon/SaveAndClose_16.png" Image32by32="/_imgs/ribbon/SaveAndClose_32.png" TemplateAlias="o1" />
                  <Button Id="Mscrm.Form.account.SaveAndNew" ToolTipTitle="$Resources:Mscrm_Form_Other_MainTab_Save_SaveAndNew_ToolTipTitle" ToolTipDescription="$Resources(EntityDisplayName):Ribbon.Tooltip.SaveAndNew" Command="Mscrm.SaveAndNewPrimary" Sequence="40" LabelText="$Resources:Ribbon.Form.MainTab.Save.SaveAndNew" Alt="$Resources:Ribbon.Form.MainTab.Save.SaveAndNew" Image16by16="/_imgs/ribbon/saveandnew16.png" Image32by32="/_imgs/ribbon/saveandnew32.png" TemplateAlias="o2" />
                  <Button Id="Mscrm.Form.account.Activate" ToolTipTitle="$Resources:Ribbon.HomepageGrid.account.Record.Status.Activate" ToolTipDescription="$Resources(EntityPluralDisplayName):Ribbon.Tooltip.Activate" Command="Mscrm.Form.Activate" Sequence="50" Alt="$Resources:Ribbon.HomepageGrid.account.Record.Status.Activate" LabelText="$Resources:Ribbon.HomepageGrid.account.Record.Status.Activate" Image16by16="/_imgs/ribbon/Activate_16.png" Image32by32="/_imgs/ribbon/Activate_32.png" TemplateAlias="o2" />
                  <Button Id="Mscrm.Form.account.Deactivate" ToolTipTitle="$Resources:Ribbon.HomepageGrid.account.Record.Status.Deactivate" ToolTipDescription="$Resources(EntityPluralDisplayName):Ribbon.Tooltip.Deactivate" Command="Mscrm.Form.Deactivate" Sequence="60" Alt="$Resources:Ribbon.HomepageGrid.account.Record.Status.Deactivate" LabelText="$Resources:Ribbon.HomepageGrid.account.Record.Status.Deactivate" Image16by16="/_imgs/ribbon/deactivate16.png" Image32by32="/_imgs/ribbon/Deactivate_32.png" TemplateAlias="o2" />
                  <Button Id="Mscrm.Form.account.Delete" ToolTipTitle="$Resources:Mscrm_Form_Other_MainTab_Management_Delete_ToolTipTitle" ToolTipDescription="$Resources(EntityPluralDisplayName):Ribbon.Tooltip.Delete" Command="Mscrm.DeletePrimaryRecord" Sequence="70" LabelText="$Resources:Ribbon.HomepageGrid.MainTab.Management.Delete" Alt="$Resources:Ribbon.HomepageGrid.MainTab.Management.Delete" Image16by16="/_imgs/ribbon/delete16.png" Image32by32="/_imgs/Workplace/remove_32.png" TemplateAlias="o2" />
                </Controls>
              </Group>

3. Now Export the current solution and then extract the zip file, open "Customizations.xml" file in edit mode.

4.  Find the  <RibbonDiffXml> at Account Entity level and then edit the <customActions> section to rename the 'DeActive" label.

 <CustomActions>
          <CustomAction Id="Sample.Form.account.Deactivate.CustomAction" Location="Mscrm.Form.account.Deactivate" Sequence="61">
            <CommandUIDefinition>
              <Button Id="Mscrm.Form.account.Deactivate" ToolTipTitle="$Resources:Ribbon.HomepageGrid.account.Record.Status.Deactivate" ToolTipDescription="$Resources(EntityPluralDisplayName):Ribbon.Tooltip.Deactivate" Command="Mscrm.Form.Deactivate"  Alt="$Resources:Ribbon.HomepageGrid.account.Record.Status.Deactivate" LabelText="InActive" Image16by16="/_imgs/ribbon/deactivate16.png" Image32by32="/_imgs/ribbon/Deactivate_32.png" TemplateAlias="o2" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>

Here we are changing the OOB "DeActive" Label text to "InActive" in the customActions section. But the Ribbon Button functionality will be same. If you wants to override the functionality of the button, you can change the  <CommandDefinitions> of the button.

5. Now Import the solution back to CRM. verify the changes..

Hope it helps!!!!



Wednesday, August 3, 2011

Useful Tools in CRM 2011

some of the useful tool which are available in Codeplex.

Ribbon Editor Tool : To customize Ribbon easily http://ribboneditor.codeplex.com/

Site Map Editor Tool: For easy sitemap editing http://sitemapeditor.codeplex.com/

JavaScript Resource Manager: http://jswebresourcemanager.codeplex.com/

Odata Designer Tool : http://crm2011odatatool.codeplex.com/

CRM 4 - CRM 2011 javascript converter: http://crm2011scriptconvert.codeplex.com/

MetaData Browser : http://crm2011metabrowser.codeplex.com/

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

Tuesday, June 7, 2011

Executing FetchXML in CRM 2011

Hi friends, in crm 2011 service don't have fetch method to execute fetch XML query. we can execute fetch xml query using RetrieveMultiple method of service. Here i'm going to retrieve system user's team details using fetchxml.

string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                                    <entity name='team'>
                                    <attribute name='name' />
                                    <attribute name='businessunitid' />
                                    <attribute name='teamid' />
                                    <order attribute='name' descending='false' />
                                    <link-entity name='teammembership' from='teamid' to='teamid' visible='false' intersect='true'>
                                        <link-entity name='systemuser' from='systemuserid' to='systemuserid' alias='user'>
                                        <filter type='and'>
                                            <condition attribute='systemuserid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>
                                    </link-entity>
                                    </entity>
                                </fetch>";

                 //  pass user guid as parameter
                string formatXml = string.Format(fetchXml, userid.ToString());

                // Executing fetchxml using  RetrieveMultiple method
                EntityCollection entities = service.RetrieveMultiple(new FetchExpression(formatXml));

                foreach (Entity e in entities.Entities)
                {
                   Guid Id = new Guid(e.Attributes["teamid"].ToString());
                   string TeamName = e.Attributes["name"].ToString();
                }

Force submit in CRM 2011

Hi, I got a requirement to update CRM Field data on a Ribbon Button click. I will be calling the following java script method from ribbon button. Here we will set value to the CRM Field and then set force submit to the field. After that we will call the save method, it will save the crm Form Data.

function SaveData() {

    Xrm.Page.getAttribute("new_field").setValue("100");

     // setting Force Submit to the field, This must be set to save the data
    Xrm.Page.getAttribute("new_field").setSubmitMode("always");

    // Call Form save method
    crmForm.Save();
    

Happy coding.. :)

Monday, May 9, 2011

Hiding Ribbon Button in CRM 2011

Hi All, Here i am going to hide a ribbon button from account entity at form level and home page grid level.

Before Hiding Button from the Account Home page Grid
After Hiding the Button from the Account Home page Grid
Before Hiding button from the Account Form
After Hiding button from the Account Form

Follow the following steps to hide the button from the account entity

1. We needs to find the Id of the button " Add to Marketing List", which we wants to hide. To find the Id of this button go to the CRM Sdk, and find the "accountribbon.xml" file at "sdk\samplecode\cs\client\ribbon\exportribbonxml\exportedribbonxml". Open "accountribbon.xml" file and find the Id of the button which we wants to hide. 
  For "Add to Marketing List" button Id at Home page grid level is "Mscrm.HomepageGrid.account.AddToList"
 For "Add to Marketing List" button Id at Form level is "Mscrm.Form.account.AddToList"
2. Now Export the solution and open the "Customization.xml" file for editing.
3. Find the <RibbonDiffXml> tag at Account entity level, add the following code

Here is the code to copy
<RibbonDiffXml>
 <CustomActions>
 <!-- Hide "Add to Marketing List" button at grid level, here Location will be the button id and HideActionId will be any unique id-->
 <HideCustomAction Location="Mscrm.HomepageGrid.account.AddToList" HideActionId="Sample.HomepageGrid.account.HideMarketingList"/>
 <!-- Hide "Add to Marketing List" button at Form level-->
 <HideCustomAction Location="Mscrm.Form.account.AddToList" HideActionId="Sample.Form.account.HideMarketingList"/>
 </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions />
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules />
          <EnableRules />
        </RuleDefinitions>
        <LocLabels />
      </RibbonDiffXml>

4. Now import the solution back into CRM. You can find the changes.

Thats it.. It's very simple to hide a button in crm2011. we can also use Display rules to hide the buttons. Based on the user security permission we can show the buttons using display rules.




Thursday, May 5, 2011

Sitemap Customization in CRM 2011

Sitemap customization in crm 2011 will be similar to crm 4.0. Now I am just trying add new Area Section to the Existing CRM. Lets see how to add new area,groups and subgroups in crm.



Follow the following steps

1. Add sitemap resource to the solution. In the solution click on "Client Extensions" and then click on "Add Existing" and add "SiteMap".

2. Now Export the solution and then extract the zip file, you will find "Customizations.xml" file. open it in the visual studio for editing.

3. Find the <SiteMap> tag, start editing the sitemap. To get intelligence for sitemap editing, attach the following schema file to visual studio.
   you can find this file in the CRM SDK "sdk\schemas\customizationssolution.xsd". To add this file into visual studio, click on "XML" menu ==> "Schemas" ==> browse the customizationssolution.xsd file and then add. Now you will get intelligence in visual studio.

4. Now edit the sitemap

   Here is the code to add new Area
<!-- Adding New Area to CRM. Give some unique values to Id, ResourceId properties -->
<Area Id="customer_Area" ResourceId="Area_MyArea" ShowGroups="true" Icon="/_imgs/resourcecenter_24x24.gif"  Title="Customer Area">
<!-- Adding new group, Title is mandatory and which will be the display text of area/group -->
<Group Id="MYGroup"  Title="My Group">
<!-- Adding links to the group, Add the required entity links to this group-->
<SubArea Id="nav_contacts" Entity="contact" DescriptionResourceId="Contact_SubArea_Description" GetStartedPanePath="Contacts_Web_User_Visor.html" GetStartedPanePathAdmin="Contacts_Web_Admin_Visor.html" GetStartedPanePathOutlook="Contacts_Outlook_User_Visor.html" GetStartedPanePathAdminOutlook="Contacts_Outlook_Admin_Visor.html" />
<SubArea Id="nav_accts" Entity="account" DescriptionResourceId="Account_SubArea_Description" GetStartedPanePath="Accounts_Web_User_Visor.html" GetStartedPanePathAdmin="Accounts_Web_Admin_Visor.html" GetStartedPanePathOutlook="Accounts_Outlook_User_Visor.html" GetStartedPanePathAdminOutlook="Accounts_Outlook_Admin_Visor.html" >
<!-- If the user contains write privilages on account then only this link will appear-->
<Privilege Entity="account" Privilege="Write"/>
</SubArea>
</Group>
</Area>

 5. After finishing the editing, import back the solution to CRM. changes will be reflected. Thats it... simplified way to edit sitemap...

Wednesday, April 13, 2011

Retrieve using ODATA and JSON in CRM 2011

In this example i am trying to retrieve Account entity information in  form load script using ODATA  and JSON in CRM 2011

To use ODATA service you need two resource files
  JSON and JQuery


you can download these popular resource in web...
Now write following java script in the new web resource file

function init()
{
// write required ODATA query
var odataSelect = "http://server/orgname/XRMServices/2011/OrganizationData.svc/AccountSet(guid'6C2EFF37-BD39-E011-91D1-000C2971AF13')";

$.ajax({
       type: "GET",
       contentType: "application/json; charset=utf-8",
       datatype: "json",
       url: odataSelect,
       beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
       success: function (data, textStatus, XmlHttpRequest) 
           { 
               
                
// Use this method for a selection that  return single entitie
               RetrieveEntityData(data.d);

             
              // Use this method for a selection that may return multiple entities
               RetrieveMultipleEntities(data.d.results);
           
           },
       error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
   });
}



function RetrieveEntityData(Entity)
{  
    // get the fields from the Entity object
     var accountNumber = Entity.AccountNumber;
     var AccountName = Entity.Name;
    
alert(Entity.Name);   
}


function RetrieveMultipleEntities(ManyEntities)
{


  for( i=0; i< ManyEntities.length; i++)
  {
// get the fields from the Entity object
     var Entity = ManyEntities[i];
     var accountNumberAttribute = Entity.AccountId;    
     var AccountName = Entity.Name;
     
alert(Entity.Name);   
  }
}


Just call the init method from the CRM form events, but make sure you have to add JSON and JQuery web resources to the event library before adding this web resource. It has to follow the sequence JSON,JQuery and Custom web Resource.


To get the Required entity ODATA set use the following url




Wednesday, March 16, 2011

Override Add Existing ISV Button functionality in CRM

To override "Add Existing" button default functionality. An Iframe displays accounts assoiciation view. Here I will be adding an confirm alert message to the "Add Existing" button, if the user confirms it will opens the lookup window, otherwise no action will happen.






     Add the following java script code in page load of the entity



getAlertForAddExistingAccountButton = function(lookupUrl) {  
    var iframe = crmForm.all.IFRAME_Accounts; //  IFRAME_Accounts  ID  
    var crmGrid = iframe.contentWindow.document.all['crmGrid'];  
      


  // If it's not N:N lookup dialog, we skip it.   
    if (lookupUrl.toLowerCase().match(/\/_controls\/lookup\/lookupmulti.aspx/i) == null)  
        return lookupUrl;  
      
    // If the lookup window is not concerned with the entity that we are interested in, we skip as well  
    if (GetQueryString(lookupUrl, 'objecttypes') !== crmGrid.GetParameter('otc'))  
        return lookupUrl;  
  
    
    return lookupUrl;  
};

(function replaceCrmLookups() {  


    window.oldOpenStdDlg = window.oldOpenStdDlg || window.openStdDlg;  


    window.openStdDlg = function() {  
    
var cnf = confirm("Are you sure to open Account lookup? ");
if(!cnf)
return;



        arguments[0] = getAlertForAddExistingAccountButton(arguments[0]);  
        
        return oldOpenStdDlg.apply(this, arguments);  


    };  
})();


Now you will get confirm alert on add existing button click before opening the account lookup page.