Wednesday, February 23, 2011

Increase the Maximum Records exported to Excel in CRM 2011

some times you needs to export more than 10000 records from CRM to reimport it back into other environment. But default CRM supports upto 10000 records while exporting crm records into Excel.
Follow the steps below to make the change at the database level in CRM 2011/4.0 to extend the limitation.

  • Open SQL Mangement Studio
  • Use the <organization>_MSCRM database
  • Open the OrganizationBase table
  • Locate the column – MaxRecordsForExportToExcel
  • Change the value to the new value, to which extent you wants to increase.
Thats it, now you can export data to your wish. No limitation... :)


"My best friend is the one who brings out the best in me."
- Henry Ford

using ODATA to retrieve data from a custom Entity in CRM2011

In this example i am going to retrieve related custom entity attributes information in a CRM form load script using ODATA feature of CRM2011


To use ODATA 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


var ODataPath;
var serverUrl;


// here lid is the parameter that we will be passing while calling this method in crm form
function getCity(lid) {
    // Set Global Variables

    var context = Xrm.Page.context;
    serverUrl = context.getServerUrl();
    ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    startTime = new Date();
     var locid = lid[0].id;
// here i'm passing lookup guid as parameter to retrieve that lookup entity related information   
 retrieveCity(locid );


}


function retrieveCity(Id) {



 var retrieveCityReq = new XMLHttpRequest();


// here is the entityset value you can get from the ODATA organization service
 retrieveCityReq.open("GET", ODataPath + "/new_entitySet(guid'" + Id + "')", true);
 retrieveCityReq.setRequestHeader("Accept", "application/json");
 retrieveCityReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 retrieveCityReq.onreadystatechange = function () {
  retrieveCityReqCallBack(this);
 };
 retrieveCityReq.send();


}


function retrieveCityReqCallBack(retrieveCityReq ) {
 if (retrieveCityReq.readyState == 4 /* complete */) {
  if (retrieveCityReq.status == 200) {
   //Success
   var retrievedCity = JSON.parse(retrieveCityReq.responseText).d;
// here i'm retrieving pick list data
  alert("Retrieved City = " + retrievedCity.new_City.Value+ "");
  
// Assigning retrieved pick list  value to form element
Xrm.Page.getAttribute("new_city").setValue(retrievedCity.new_city.Value); 


     }
  else {
   //Failure
   errorHandler(retrieveBrandtReq);
  alert("retrieve Brand ReqCallBack function failure ");
  }
 }
}


Just call the getCity 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
http://server/XRMServices/2011/OrganizationData.svc/new_enitityset





"The only reward of virtue is virtue; the only way to have a friend is to be one."
- Ralph Waldo Emerson


Monday, February 21, 2011

Adding New Button to Ribbon at form level and grid level for custom entity in CRM2011

Adding New Button to Ribbon at form level and grid level for custom entity in CRM2011


1. Export the solution to which we wants to create custom button
2. Extract the solution and open the "custmizations.xml" file to edit.
3. Find "RibbonDiffXml" tag for the particular custom entity which you want to add button. Now replace the "RibbonDiffXml" tag with the following code, it will adds a button to the chosen entity at grid level and form level.


<RibbonDiffXml>
        <CustomActions>
<!-- This to add button in formlevel after exportdata button , CI_formlevel is any unique Id, sequence Number is the position of the button,75 will shows button before Export Excel,you can find sequence numbers of system buttons in SDK-->
          <CustomAction Id="CI_formlevel" Location="Mscrm.Form.new_entityname.MainTab.ExportData.Controls._children" Sequence="75">
            <CommandUIDefinition>
              <Button Id="B_formbutton" Command="Cmd_JavaScript1" LabelText="Custom Button" ToolTipTitle="My Form Button" ToolTipDescription="Form Level Button" TemplateAlias="o1" Image16by16="$webresource:Icon_imgSmall" Image32by32="$webresource:Icon_imgMedium" />
            </CommandUIDefinition>
          </CustomAction>


<!-- this to add button at gridlevel -->
          <CustomAction Id="CI_Gridlevel" Location="Mscrm.HomepageGrid.new_entityname.MainTab.ExportData.Controls._children" Sequence="75">
            <CommandUIDefinition>
              <Button Id="B_GIncident" Command="Cmd_JavaScript1" LabelText="Grid Button" ToolTipTitle="Grid Button" ToolTipDescription="Grid Level button" TemplateAlias="o1" Image16by16="$webresource:Icon_imgSmall" Image32by32="$webresource:Icon_imgMedium" />
            </CommandUIDefinition>
          </CustomAction>
        </CustomActions>
        <Templates>
          <RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
        </Templates>
        <CommandDefinitions>
          <CommandDefinition Id="Cmd_JavaScript1">
            <EnableRules>
              <EnableRule Id="Mscrm.Enabled" />
            </EnableRules>
            <DisplayRules />
            <Actions>
<!-- call java script library function -->
              <JavaScriptFunction Library="$webresource:new_jscrlib" FunctionName="myfunction"></JavaScriptFunction>
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>
        <RuleDefinitions>
          <TabDisplayRules />
          <DisplayRules />
          <EnableRules />
        </RuleDefinitions>
        <LocLabels />
      </RibbonDiffXml>


4. Now zip the solution files and import back to CRM. Thats it you can see the custom button at form level and grid level.

From Ribbon button calling On demand workflow for selected records of grid in CRM2011

From Ribbon button calling On demand workflow for selected records of grid in CRM2011


Add the following code in the customization.xml file while customizing the ribbon button
<CommandDefinitions>
          <CommandDefinition Id="Cmd_JavaScript2">
            <EnableRules>
              <EnableRule Id="Mscrm.Enabled" />
            </EnableRules>
            <DisplayRules />
            <Actions>
              <JavaScriptFunction Library="$webresource:new_callworkflow" FunctionName="myworkflow">
               // Add this line to get the list of selected records guid's
               <CrmParameter Value="SelectedControlSelectedItemReferences" />
              </JavaScriptFunction>
            </Actions>
          </CommandDefinition>
</CommandDefinitions>



Add this java script in the web resource "new_callworkflow"
function Myfunction(SelectedControlSelectedItemReferences) {

    var allItems = new Array
    var allItems = SelectedControlSelectedItemReferences

    var iTotal = allItems.length;
    if (iTotal > 0) {
        for (var i = 0; i < iTotal; i++) {
        //    alert(allItems[i].Id)
callworkfow(allItems[i].Id);
        }
        alert("Success");
    }
    else
      alert("Please select any record to perform required action");
  

}


function callworkfow(id)
{

try
{

var guid;

if(id == null)
{

 guid =Xrm.Page.data.entity.getId();
}
else
guid = id;

// assign workflow guid
var WorkflowId ="0ACBCECD-DE6C-4E86-A767-0B1EE34B03D2";

  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\">" +
    Xrm.Page.context.getAuthenticationHeader() +
    "<soap:Body>" +
    "<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    "<Request xsi:type=\"ExecuteWorkflowRequest\">" +
    "<EntityId>" + guid + "</EntityId>" +
    "<WorkflowId>" + WorkflowId + "</WorkflowId>" + //WorkflowId = guid of the workflow
    "</Request>" +
    "</Execute>" +
    "</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/Execute");
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
  xmlHttpRequest.send(xml);

  var resultXml = xmlHttpRequest.responseXML;

if(id == null)
alert("Success");
  return (resultXml.xml);
}
catch(e)
{
  alert("Failed to Execute");
}
}

CRM2011 java script samples

Here are few basic CRM2011 java script samples

Get the value from a CRM field
var varMyValue = Xrm.Page.getAttribute(“CRMFieldSchemaName”).getValue() ;

Set the value of a CRM field
Xrm.Page.getAttribute(“po_CRMFieldSchemaName”).setValue(‘My New Value’);


// Hiding An Attribute
Xrm.Page.ui.controls.get("ownerid").setVisible(false);


Hide/Show a tab/section
Xrm.Page.ui.tabs.get(5).setVisible(false);
Xrm.Page.ui.tabs.get(5).setVisible(true);
 Xrm.Page.ui.tabs.get(tabNumber).sections.get(sectionNumber).setVisible(false);
 Xrm.Page.ui.tabs.get(tabNumber).sections.get(sectionNumber).setVisible(true);

Call the onchange event of a field
Xrm.Page.getAttribute(“CRMFieldSchemaName”).fireOnChange();

Get the selected value of picklist
Xrm.Page.getAttribute(“CRMFieldSchemaName”).getSelectedOption().text;

Set the requirement level
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“none”);
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“required”);
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“recommended”);

Set the focus to a field
Xrm.Page.getControl(“CRMFieldSchemaName”).setFocus(true);



// Hide Left Navigation link
Xrm.Page.ui.navigation.items.get("navContact").setVisible(false);


// Hide Left Navigation Pane
document.getElementById("crmNavBar").parentElement.style.display = "none";


Stop an on save event
event.returnValue = false;

Return array of strings of users security role GUIDs:
Xrm.Page.context.getUserRoles()


// Retrieving Object Type Code of Entity, etc = Entity Type Code
var etc = Xrm.Page.context.getQueryStringParameters().etc;



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

// usage
SetLookupValue("new_field", "GUID", "Name", "new_entityname");

//Getting parent window context in child window
var parentcontext = window.top.opener.parent.Xrm.Page.context;


//Getting Parent window Object type code
var parobjcode = window.top.opener.parent.Xrm.Page.context.getQueryStringParameters().etc;

// get parent  Entity fields data
var parentFieldData = window.top.opener.parent.Xrm.Page.getAttribute("crmfield").getValue();

// Get the Server url with org Name
var serverAndOrgUrl = Xrm.Page.context.getServerUrl();
// Get the Current Organization Unique Name
var OrgName ="/"+Xrm.Page.context.getOrgUniqueName();

calling crms service from java script in CRM2011

//calling crms service from java script in CRM2011

Here I am going to call CRM service using java script to retrieve data from a custom entity and assign the result values to the current form fields.

function SetBrand(brachid)
{

try
{


if(brachid!= null && brachid!= "" )
{
brachid= brachid.replace("%7b","").replace("%7d","");

var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();

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\">" +
 authenticationHeader+
 "<soap:Body>" +
 // Specify the RetrieveMultiple message.
 "<RetrieveMultiple xmlns="+
 "\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 // Specify that this is a QueryByAttribute query.
 "<query xmlns:q1="+
 "\"http://schemas.microsoft.com/crm/2006/Query\" "+
 "xsi:type=\"q1:QueryByAttribute\">" +
 // Query the customeraddress entity.
 "<q1:EntityName>new_branch</q1:EntityName>" +
 // Set the columns you want to return.
 "<q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 "<q1:Attributes>" +
 "<q1:Attribute>new_brand</q1:Attribute>" +
 "</q1:Attributes>" +
 "</q1:ColumnSet>" +
 // Specify the attribute that you are querying on.
 "<q1:Attributes>" +
 "<q1:Attribute>new_branchid</q1:Attribute>" +
 "</q1:Attributes>" +
 // Set the value of the attribute using the customerid
 // value of the case record.
 "<q1:Values>" +
 "<q1:Value xsi:type=\"xsd:string\">"+
 brachid+
 "</q1:Value>" +
 "</q1:Values>" +
 "</query>" +
 "</RetrieveMultiple>" +
 "</soap:Body>" +
 "</soap:Envelope>";
// Create an instance of an XMLHTTP object.
 var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
// Configure the XMLHttp object for the
// Microsoft CRM Web services.
 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", xml.length );
// Send the XMLHttp request.
 xmlHttpRequest.send(xml);
// Capture the XMLHttp response in XML format.
 var resultXml = xmlHttpRequest.responseXML;

// Create an XML document that you can parse.
 var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
 oXmlDoc.async = false;
// Load the document that has the results.
 oXmlDoc.loadXML(resultXml.xml);
 // Get only the BusinessEntity results.
 var businessEntities = oXmlDoc.getElementsByTagName('BusinessEntity');

// Loop through the BusinessEntity elements.
 for (i=0;i < businessEntities.length;i++)
 {
     if (businessEntities[i].selectSingleNode('./q1:new_brand') != null)
       {
    
        var NameElement = businessEntities[i].selectSingleNode('./q1:new_brand');
        // We already know it is not null.
        var NameValue = NameElement.text;
    // Set the value of the lookup field to the value of the array.

            Xrm.Page.getAttribute("new_brand").setValue(NameValue);
       }
  }
}
}
catch (e)
{}

}

Re-arange the tabindex sequence in left to right order in MSCRM

The following code will re-arange the tabindex sequence in a left to right order.

function OnCrmPageLoad()

{
     ReArangeTabIndex();
}



function ReArangeTabIndex()

{

    for( var i = 0 ; i < crmForm.all.length ; i++ )

    {

          if( crmForm.all[ i ].tabIndex )

              crmForm.all[ i ].tabIndex = 1000 + (i*10);

    }
}

calling ondemand workflow using java script

Here is the logic to call on-demand workflow from java script.

function TriggerWorkflow() {

//  pass the workflow guid
var WorkflowId ="61A3C919-9636-44DC-87E4-C5FF2A63F2B4";

  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>" +
    "<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
    "<Request xsi:type=\"ExecuteWorkflowRequest\">" +
    "<EntityId>" + crmForm.ObjectId + "</EntityId>" +
    "<WorkflowId>" + WorkflowId + "</WorkflowId>" + //WorkflowId = guid of the workflow
    "</Request>" +
    "</Execute>" +
    "</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/Execute");
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
  xmlHttpRequest.send(xml);

  var resultXml = xmlHttpRequest.responseXML;
  return (resultXml.xml);
}