Thursday, October 29, 2009

Auto Numbers in in MS CRM 4.0

I was looking for the simple, supported and mostly acceptable way of auto numbering and got in some blog to use a custom entity in CRM called AutoNumber that tracks the max used autonumber by entity type.

Use a post create callout to populate corresponding entity type’s max value + 1 to the newly-created record, and also to write that new max value to the entry in the AutoNumber record for the entity type.

That way the process fires when offline clients sync their new records to the central database and you end up with no duplicate record contention, since that part of the post callout is (I believe) transaction bound to ensure we don’t get dupes.


There is another simple, supported and mostly acceptable way of auto numbering suggested by “Ayaz Ahmad”.


Read the autonumber attribute Max value and then add 1 to get next auto number. For example you have a custom entity named Project and you want to auto number Project_Ref_Number attribute. But do not retrieve all records. Just retrieve the record with maximum number value by using following two properties of PageInfo Class in SDK and set descending order.

PageInfo.Count = 1;
PageInfo.PageNumber = 1;

Code:-

ColumnSet cols = new ColumnSet();
cols.AddColumns(new string[] { "leadid", "new_autonumber" });

PagingInfo pages = new PagingInfo();
pages.PageNumber = 1;
pages.Count = 1;

QueryExpression query = new QueryExpression();
query.EntityName = EntityName.lead.ToString();
query.ColumnSet = cols;
query.AddOrder("new_autonumber", OrderType.Descending);
query.PageInfo = pages;

RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.ReturnDynamicEntities = true;
request.Query = query;

RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)service.Execute(request);

if (retrieved.BusinessEntityCollection.BusinessEntities.Count > 0)
{
DynamicEntity results = (DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[0];
if (results.Properties.Contains("new_autonumber"))
{
nextNumber = Convert.ToInt32(results.Properties["new_autonumber"].ToString()) + 1;
//add nextNumber as the entity property for the coresponding entity
}
}

One more consideration should be taken in account to register your auto number plugin to at PreCreate rather at PostCreate.

Limitation:
In multi-user environment, this approach can come up with duplicate numbers in Project_Ref_Number when more than one user is creating project records.

Wednesday, October 28, 2009

Datetime format in SSRS report while running in CRM/Web App in MS CRM 4.0

When we run our report in CRM/ Web App automatically date format get change from MM/DD/YYYY to DD/MM/YYYY or vice versa in report parameters.
Actually this is the limitation of the reporting service. By default the “language property of the report” is US English. But when we run the report in Client browser the date time format get decided by the Language settings of client browser not by the language property of the report.

The format of date time parameter is always decided by the Language settings of client browser regardless of the Language property of our report (or in CRM).

Examples:-
If we have the Client browser language settings in English (AU), the date format in parameter bar will be as (regardless of the Language property of our report (or in CRM)):-
But when we run the same in the Client browser where language settings is in French (Canada) the date format in parameter bar will be as (regardless of the Language property of our report (or in CRM)):-

We can change the date time format in the report data using
1. CultureInfo (by adding the vb script in code section of the report) in Web App
2. CRM_CalendarTypeCode from the user settings in CRM.

Monday, October 19, 2009

OnLoad, Onsave and OnChange code sharing/reuse in MS CRM 4.0

There are three events in CRM form, OnLoad, OnSave, OnChange. OnLoad and OnSave are in the form level and OnChange is in field level. Sometimes it’s needed to write the same code/method in OnLoad, or Onsave or OnChange or all three events.

Actually these events trigger in a sequence, first OnLoad then OnChange (if any) and finally OnSave. So whatever methods we have written in the OnLoad of the form it will be available in OnChange and OnSave of the form.

If there are any method/methods in OnLoad event we can reuse those methods in OnChange event of any field and OnSave of the form just by calling the method (no need to redefine the method definition again).

And also sometimes it’s required to write the same code what we have in OnChange of any field in OnLoad/OnSave. We can achieve the same just by calling the OnChange code of the field using “<field_Schema>_onchange0();” method.

Tuesday, October 13, 2009

UserId of the Calling User in MS CRM 4.0

function GetCurrentUserInfo() {
var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
xmlhttp.open("POST", "/mscrmservices/2007/crmservice.asmx", false);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
var soapBody = "<soap:Body>" +
"<Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
"<Request xsi:type='WhoAmIRequest' />" +
"</Execute></soap:Body>";
var soapXml = "<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'>";
soapXml += GenerateAuthenticationHeader();
soapXml += soapBody;
soapXml += "</soap:Envelope>";
xmlhttp.send(soapXml);
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(xmlhttp.responseXML.xml);
var userid = xmlDoc.getElementsByTagName("UserId")[0].childNodes[0].nodeValue;

return userid;
}

How to edit the list of entities displayed in the Look for picklist in Lookup window in MS CRM 4.0

The regarding lookup windows generally display a list of all entities that can be associated with an activity. Quite often this feature becomes quite an issue with the users always having to select the appropriate entity from the list before applying the search. The longer the list of entities the more time consuming it is to search using the lookup window.It would be a boon to have only selected entities in the list. Well this is not available for customization through the CRM customization area. But it could be done by adding the Jscript to onload of the form.

There are few properties of the Lookup control being set when we open a form and those are “Lookup Types”, “Lookup Type names” ,”Lookup Type Icons” and “default type”.

We need to over load the default settings by writing our own logic in onload of the form to load specific list of entities to show up in the Look for section.

/*Give the entity type code that you want in below script we want to show account, contact, Lead and Opportunity in order in the list */
crmForm.all.regardingobjectid.lookuptypes = "1,2,3,4";

/*Make sure you set the path of the entity images correctly for the list specified above */
crmForm.all.regardingobjectid.lookuptypeIcons = "/_imgs/ico_16_1.gif:/_imgs/ico_16_2.gif:/_imgs/ico_16_3.gif:/_imgs/ico_16_4.gif:";

/*The below script is to set default entity in the multiple entity lookup. Here we set the default entity to be Opportunity */
crmForm.all.regardingobjectid.defaulttype = "3";


Above example will show Account, Contact, Opportunity and Lead in the Look For entity list and default entity is Opportunity.

Wednesday, September 30, 2009

Appropriate W3P.exe instance while debugging the MS CRM Application

There are more than one W3P.exe instances running in a CRM system (CRM app pool, reporting service etc). While debugging the MSCRM Application sometimes we get more than one W3P.exe instances. And usually we attach all those instances which slowdowns the processing of the system.

It’s unnecessary overload on system processing. We can avoid this by attaching the appropriate W3P.exe instance.

To find out which instance to attach in debugger just run the IISAPP.VBS in command prompt, it will list out all the W3P.exe instances with their port no. Now just match the port no of the CRM App Pool/ Default App Pool with the available processes list, attach the appropriate W3P.exe and start debugging.

Tuesday, September 29, 2009

CRM Report error in case of Custom DB Object in MS CRM 4.0

While doing the reports for CRM, sometimes its required to create our own custom objects (like function, procedure or table) and use them in reports or to include some CRM tables(Entity, Attribute) in our Query.

When we use a custom object or CRM table in our Query it work perfectly for the admin user but it doesn’t work for the non-admin user.

In this case we need to add the permission “NT Authority\Network Services” for that particular object in DB.

Monday, September 28, 2009

Lookup: Retrieve Column values from Lookup window in MS CRM 4.0

if(Xrm.Page.getAttribute("<lookupId>") != null)
{
var entityId = document.getElementById( "<lookupId>");
var lookupItems = entityId.items[0].values;

alert(lookupItems[0].value); // First column value of Lookup
alert(lookupItems[1].value); // Second column value of Lookup
alert(lookupItems[2].value); // Third column value of Lookup
alert(lookupItems[3].value); // Fourth column value of Lookup
alert(lookupItems[4].value); // Fifht column value of Lookup
alert(lookupItems[5].value); // Sixth column value of Lookup
}

Note: You should disable the Automatic Resolution, so that users cannot add values automatically. This script will work only if the Lookup View is loaded.

Change the text and display of the navigation item in MS CRM 4.0

Change the text and display of the navigation item:-



var iOpps = 0;
if(document.getElementById('navOpps') != null)
{
document.getElementById('navOpps').getElementsByTagName('NOBR')[0].innerText =
document.getElementById('navOpps').getElementsByTagName('NOBR')[0].innerText + " (" + iOpps + ")";
document.getElementById('navOpps').getElementsByTagName('NOBR')[0].style.color = "#FF0000";
document.getElementById('navOpps').getElementsByTagName('NOBR')[0].style.fontWeight = "700";
}

Thursday, September 10, 2009

Change the color of the service appointment / appointment in service calendar in MS CRM 4.0

In Service Management, there are Time Blocks displayed in the appointment book. The color of the time blocks varies according to the status of the appointment. The section named “ServiceManagement” of isv.config.xml allows for customization of these colors by providing a mapping to the .css file that defines them. These .css files are located at \SM\Gantt\style\GanttControl.css.aspx.

Export and open the “isv.config”, search for the . Under the , for every Status(1 – Requested, 2 – Tentative, 3 – Pending, 4 – Reserved, 6 - In Progress, 7 – Arrived, 8 – Completed, 9 – Canceled ,10 - No Show) CssClass has been defined.

Open the GanttControl.css.aspx file using VS and search the CssClass name (like ganttBlockServiceActivityStatus1, ganttBlockServiceActivityStatus2) and change the color acording to your requirement.

Wednesday, September 9, 2009

Script for hide 'Add existing button' in MS CRM 4.0

Sometimes it required to hide the “add existing” button from the grid. Here is the Jscript to achieve the same. There is a Test entity (custom entity) in Contact entity where I am hiding the “add existing” button.

//Script for hide 'Add existing button'

HideAddExistingButton('new_contact_test', ['Add existing Test to this record']);

function HideAddExistingButton(relationshipName, buttonToolTip)
{
var navElement = document.getElementById('nav_' + relationshipName);
if (navElement != null)
{
navElement.onclick = function LoadAreaOverride()
{
loadArea(relationshipName);
HideButton(document.getElementById(relationshipName + 'Frame'), buttonToolTip);
}
}
}



function HideButton(Iframe, buttonToolTip)
{
Iframe.onreadystatechange = function HideTitledButtons()
{
if (Iframe.readyState == 'complete')
{
var iFrame = frames[window.event.srcElement.id];
var liElements = iFrame.document.getElementsByTagName('li');

for (var j = 0; j < buttonToolTip.length; j++)
{
for (var i = 0; i < liElements.length; i++)
{
if (liElements[i].getAttribute('title') == buttonToolTip[j])
{
liElements[i].style.display = 'none';
break;
}
}
}
}
}
}


“relationshipName” you can get it from the entity customization, it’s basically the relationship name in between the entities. “buttonToolTip” is the tool tip defined for the add exixting button.

Thursday, September 3, 2009

How to change the record title in MS CRM 4.0

Sometimes we get requirement like change the opportunity title or account title , it should be in red color based on some condition or title should be combination of few fields there in the form.


Here is the Jscript to achieve the same.

//Change the Main Title
var cells = document.getElementsByTagName("span");
for (var i = 0; i < cells.length; i++)
{
if (cells[i].className == "ms-crm-Form-Title")
{
cells[i].style.color = "#FF0000";
cells[i].style.fontWeight = "700";
break;
}
}





Tuesday, September 1, 2009

Bulk 'save as completed/Cancel' of the CRM activities in MS CRM 4.0

There is no direct way to do the same in CRM. But there are workarounds you can achieve the same.
1. Create an ISV button on the grid tool bar. On click of this button you will the GUID of all the selected records (in the grid). Once you will get the GUID of all the activity, you can call web service using Jscript (AJAX call) and update these records as completed.

getSelected('crmGrid') will return you an array of the GUIDs of the selected records.

Limitation –

· getSelected('crmGrid') method has a limitation , it will return you the GUID of max 50 records.

· After updating the activity using AJAX call, records will still appear in the grid, unless n until you will refresh the grid.

2. Create an ISV button on the grid tool bar. On click of this button you will the GUID of all the selected records (in the grid). Once you will get the GUID of all the activity, you call you own custom page, which will update those records as completed, and it will show you a user friendly message. On close of this custom page refresh the grid.

To Refresh the grid - crmGrid.Refresh();

limitation of creating the custom attributes in MS CRM 4.0

There is no limitation of creating the custom attributes in CRM. You can create n no of attributes within an entity. Bt as you know we have tables corresponding to each n every entity in the CRM DB and there is a limitation in database level. SQL Server allows up to 1024 columns per table and the amount of data stored in any row cannot exceed 8060 bytes. If so, while creating or updating CRM page will through SQL server error or sometimes it won’t allow you to perform any operation on this entity/records.

You can determine the number of bytes available for entities by running the following query in _METABASE database.

select e.Name, Bytes_Remaining = 8060 - (sum(a.length))from entity e
join attribute a on e.entityid = a.entityidwhere a.iscustomfield = 1
and a.islogical = 0group by e.Name

You can determine the number of bytes used for entities by running the following query in _METABASE database.

select e.Name, Physical_Size = sum(a.length)from entity e
join attribute a on e.entityid = a.entityidwhere a.iscustomfield = 1
and a.islogical = 0group by e.Name

More than 10,000 records not returned by CRM service in MS CRM 4.0

There is a limitation in CRM service, when we retrieve data using
RetrieveMultiple or fetch xml; actually it returns max 10,000 records.

There is an unsupported way to increase the no of records returned by CRM service. You need to update the CRM DB.

There is a table named “OrganizationBase”, in this you have a column named “MaxRecordsForExportToExcel”, which defines the no of records returned by CRM service.

By default this column has been set to 10,000, which we can change according to our requirement.

Or we can use direct SQL query for the same.

Monday, August 31, 2009

CRM Pre-Filtering:

CRM Pre-Filtering:

To enable the pre filtering in the report just we need to add an alias for the filtered views which starts with “CRMAF_”. A query such as “Select name from FilteredAccount” can simply be changed to “Select name from FilteredAccount as CRMAF_Account”. Aliasing the Filtered View with a prefix of CRMAF_ will allow CRM to recognize that you would like to enable this entity for pre-filtering.


When you enable the CRM Pre-filtering functionality using the CRMAF_ method, CRM will take a query such as the following and modify it when it is uploaded into CRM:
This is the sample query:-


SELECT name, accountnumber
FROM FilteredAccount as CRMAF_Account

Becomes:
SELECT name, accountnumber
FROM (@P1) as CRMAF_Account

Then CRM will pass a query to the P1 parameter depending on how the report is being filtered. For example: when we run the report from the Reports area, the Pre-filtering functionality show all Accounts that are Active, and the resulting query would be something like:

SELECT name, accountnumber
FROM (select FilteredAccount.* from FilteredAccount where statecode = 0) as CRMAF_Account


If we are running the same report within a specific Account, the resulting query would be something like:

SELECT name, accountnumber
FROM (select FilteredAccount.* from FilteredAccount where AccountId = ‘’) as CRMAF_Account

If we are running the same report for a list of Accounts (suppose 3 accounts are selected from a view), the resulting query would be something like:

SELECT name, accountnumber
FROM (select FilteredAccount.* from FilteredAccount where AccountId in (’<1staccountid>’, ‘<2ndaccountid>’, ‘<3rdaccountid>’) as CRMAF_Account

AJAX Calls using JavaScript to retrieve data for N:N relationship in MS CRM 4.0

//**************************************************
//AJAX Call to get the Competitors for an Oportunity
//**************************************************


var sOppID = crmForm.ObjectId;

var returnXML="";

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>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>competitor</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:AllColumns\" />" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>competitorid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>competitor</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>opportunitycompetitors</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>competitorid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkEntities>" +
" <q1:LinkEntity>" +
" <q1:LinkFromAttributeName>opportunityid</q1:LinkFromAttributeName>" +
" <q1:LinkFromEntityName>opportunitycompetitors</q1:LinkFromEntityName>" +
" <q1:LinkToEntityName>opportunity</q1:LinkToEntityName>" +
" <q1:LinkToAttributeName>opportunityid</q1:LinkToAttributeName>" +
" <q1:JoinOperator>Inner</q1:JoinOperator>" +
" <q1:LinkCriteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>opportunityid</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
" <q1:Values>" +
" <q1:Value xsi:type=\"xsd:string\">" + sOppID + "</q1:Value>" +
" </q1:Values>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:LinkCriteria>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </q1:LinkEntity>" +
" </q1:LinkEntities>" +
" </query>" +
" </RetrieveMultiple>" +
" </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/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var returnXML = xmlHttpRequest.responseXML;

if(returnXML != null)
{
var returnNodes = returnXML.selectNodes("//BusinessEntity/q1:competitorid");
if(returnNodes.length > 0)
{

// DEFINE YOUR LOGIC HERE


}
}

Sunday, August 30, 2009

Generic method for Ajax calls using javascript to retrieve data in MS CRM 4.0

//limitation – This is the generic method supported only for 1:N or N:1 relationship



// This is a generic method for Ajax calls using javascript to retrieve data
//****************************************************************************
SoapRequestDynamic = function(entityName, searchColumn, searchValue, returnColumn)
{
var returnPacket = "";
for (var i = 0; i < returnColumn.length; i++)
{
returnPacket += " <q1:Attribute>" + returnColumn[i] + "</q1:Attribute>"
}

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>" +
" <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
" <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
" <q1:EntityName>" + entityName + "</q1:EntityName>" +
" <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
" <q1:Attributes>" +
returnPacket +
" </q1:Attributes>" +
" </q1:ColumnSet>" +
" <q1:Distinct>false</q1:Distinct>" +
" <q1:Criteria>" +
" <q1:FilterOperator>And</q1:FilterOperator>" +
" <q1:Conditions>" +
" <q1:Condition>" +
" <q1:AttributeName>" + searchColumn + "</q1:AttributeName>" +
" <q1:Operator>Equal</q1:Operator>" +
" <q1:Values>" +
" <q1:Value xsi:type=\"xsd:string\">" + searchValue + "</q1:Value>" +
" </q1:Values>" +
" </q1:Condition>" +
" </q1:Conditions>" +
" </q1:Criteria>" +
" </query>" +
" </RetrieveMultiple>" +
" </soap:Body>" +
"</soap:Envelope>" +
"";

return xml;
}
// End of SoapRequestDynamic Function

// Start of HttpPostRequest
HttpPostRequest = function(xml)
{
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
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);
xmlHttpRequest.send(xml);

//alert(xmlHttpRequest.responseXML.xml);
var resultXml = xmlHttpRequest.responseXML.selectSingleNode("//BusinessEntity");

return resultXml;
}
// End of HttpPostRequest

var sObjectID = crmForm.ObjectId;

//Actual Call for Relationships
/// finding out opportunity relationships
//var buXml = HttpPostRequest(SoapRequestDynamic(entityName, searchColumn, searchValue, returnColumn));

var buXml = HttpPostRequest(SoapRequestDynamic("customeropportunityrole", "opportunityid", sObjectID, ["customeropportunityroleid"]));


if(buXml != null )
{
var buNodes = buXml.selectNodes("//BusinessEntity/q1:customeropportunityroleid");
if(buNodes.length > 0)
{
// DEFINE YOUR LOGIC HERE
}
}



// for your referance
//http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/3ec3cfcd-62ea-49b5-9239-14aee58bd7b9

Wednesday, August 19, 2009

Hide navigation items of an entity in MS CRM 4.0

//define the entity names you want to hide

NavMenuHide("Service Lines","Target Achievements","Account Plan");

function NavMenuHide()
{
if (arguments == null arguments.length == 0) return;
var navBar = document.getElementById("crmNavBar");
if (!navBar) return;
var optionItems = navBar.getElementsByTagName("nobr");
var exitCount = 0;
for (opt=0; opt < optionItems.length ;opt++ )
{
for (a=0; a {
if (optionItems[opt].innerText == arguments[a])
{
// --- hide the menu item
optionItems[opt].parentNode.style.display = "none";
// --- have all of the args been processed?
exitCount ++;
if (exitCount == arguments.length) return;
}
}
}
}

Dynamic Picklist in CRM 4.0

var PAccountType = crmForm.all.new_picklist;
PAccountType.originalPicklistOptions = PAccountType.Options;
var PStartIndex =2;
var PEndIndex =3;
if (PStartIndex > -1 && PEndIndex > -1)
{
// Create a new array, which will hold the new picklist options
var PTempArray = new Array();

// Initialize the index for the temp array
var PIndex = 0;

// Now loop through the original Sub-Industry options, pull out the
// requested options a copy them into the temporary array.
for (var i = PStartIndex; i <= PEndIndex; i++)
{

PTempArray[PIndex] = PAccountType.originalPicklistOptions[i];
PIndex++;
}

PAccountType.Options = PTempArray;

Show the related records of an entity in a tab of the parent form in MS CRM 4.0

Show the related records of an entity in a tab of the parent form.

“tabSet” you can find in the customization, it’s basically the relationship name.
Or else you can run the Fiddler and get the complete URL of the related entity IFRAME (which appears in the parent form) and from the URL you can copy the “tabSet” name.

crmForm.all.new_iframe_name.src =
GetFrameSource(new_contact_new_qualification);

function GetFrameSource(tabSet)
{
if (crmForm.ObjectId != null)
{
var oId = crmForm.ObjectId;
var oType = crmForm.ObjectTypeCode;
var security = crmFormSubmit.crmFormSubmitSecurity.value;
return "areas.aspx?oId=" + oId + "&oType=" + oType + "&security=" +
security + "&tabSet=" + tabSet;
}
else
{
return "about:blank";
}
}

Tuesday, August 18, 2009

Currency symbol in reports in case of Multi currency in MS CRM 4.0

When we develop a custom report for the MSCRM always it’s a question to show the corresponding currency symbol. Take an example we have a report in which we are showing all the opportunity of value more than 1M (in all currencies).

If you will change the currency format to any of the out of box format it will show just the dollar ($) symbol.

To show the corresponding currency symbol of the opportunity, we need to select one more field in the SQL Query named “crm_moneyformatstring” from the corresponding filtered view. This field (crm_moneyformatstring) is there in every CRM entity if there is at test one currency field in the corresponding entity.

And define the format of the money field by selecting “crm_moneyformatstring” field from the dataset. (right click on the box in the table/matrix, click on the properties, select format , in the format select crm_moneyformatstring from the dataset)

Microsoft Dynamics CRM Pre-Filtering

Just need to alias the filtered views with a name that starts with “CRMAF_”. A query such as “Select name from FilteredAccount” can simply be changed to “Select name from FilteredAccount as CRMAF_Account”. Aliasing the Filtered View with a prefix of CRMAF_ will allow CRM to recognize that you would like to enable this entity for pre-filtering.

When you enable the CRM Pre-filtering functionality using the CRMAF_ method, CRM will take a query such as the following and modify it when it is uploaded into CRM:

SELECT name, accountnumber FROM FilteredAccount as CRMAF_Account

Becomes:

SELECT name, accountnumber FROM (@P1) as CRMAF_Account

Then CRM will pass a query to the P1 parameter depending on how the report is being filtered. For example: If you are running the report from the Reports area and use the Pre-filtering functionality to filter to only show Accounts that are Active, the resulting query would be something like:

SELECT name, accountnumber FROM (select FilteredAccount.* from FilteredAccount where statecode = 0) as CRMAF_Account

If you are within a specific Account and run the report, the resulting query would be something like:

SELECT name, accountnumber FROM (select FilteredAccount.* from FilteredAccount where AccountId = ‘’) as CRMAF_Account

When you are looking at a list of Accounts with 3 selected and choose the option to run the report against the selected records, the resulting query would be something like:

SELECT name, accountnumber FROM (select FilteredAccount.* from FilteredAccount where AccountId in (’<1staccountid>’, ‘<2ndaccountid>’, ‘<3rdaccountid>’) as CRMAF_Account

Custom Tooltips for every field on a CRM Form in MS CRM 4.0

Tooltips are available on every field on a MS CRM form. The current tooltips show the text of the label but we can change the contents of the current tooltips.
The restrictions to the tooltips are:-
1. Its unformatted text
2. And should not be more than 512 characters.

The onLoad code:
crmForm.all.new_attribute_c.title = “contents of the tooltip”

Capturing Previous Value on OnChange of Form Field in MS CRM 4.0

When you change the "Account Number" value, you want to populate a field called "Prior Account Number" with the previous value. The issue is that OnChange events happen AFTER the value has changed, so you can't copy the former value to the Prior Account Number field.

One solution is to use another field to store the previous value. Let's call this field accounttemp. (We will need to include this field on the form so we can access it via javascript, but we can hide it by either putting it on a hidden tab or using javascript to hide the field.)

Once we have our accounttemp and Prior Account Number field added to the Account form, we can add javascript to the OnChange event for the Account Number field. To make this happen we will need to make sure that the following steps happen in order:

1. Value of account temp field is copied to Prior Account Number field
2. Value of Account Number field is copied to the accounttemp field

Here's how that would look in Jscript:
crmForm.all.new_prioraccountnumber.DataValue=crmForm.all.new_accounttemp.DataValue;
crmForm.all.new_accounttemp.DataValue = crmForm.all.accountnumber.DataValue ;

The result is that the first time a value is entered into the Account Number field, the Prior Account Number field will remain blank, but the new value will be copied to the accounttemp field. The next time that the value of the Account number changes, the previous value will be copied to the Prior Account Number field.


Note—this will only work if the values are entered via the form. If you import this data from Scribe or the CRM import utility, the value will not be in the accounttemp field, so the process won't work for the initial change. The workaround is that when you import your account information, import the account number to the account number field AND the accounttemp field.

Monday, August 17, 2009

Load Form Tab on Click of the Tab in MS CRM 4.0

document.all.tab2Tab.attachEvent('onclick', UpdateTab2);

function UpdateTab2()
{
if(crmForm.ObjectId!=null)
{
var oId=crmForm.ObjectId
crmForm.all.new_accountguid.DataValue = oId;
if( oId != null )
{
oId=oId.substr(1,36) crmForm.all.IFRAME_Divisions.src=GetCrmServerUrl() + '/sfa/accts/areas.aspx?oType=1&security=852407&tabSet=new_account_new_divisions'+'&oId=%7b'+oId+'%7d';
}
}
}
function GetCrmServerUrl()
{
var CRM_URL='';
if(AUTHENTICATION_TYPE == 0)
{
CRM_URL = '/' + ORG_UNIQUE_NAME;
}
return CRM_URL;
}

Reorder Navigation Items in MSCRM 4.0

if(document.getElementById('crmNavBar'))
{
//arrabge the navigation Item in order you want to display
var oTempArray = new Array('navInfo','nav_new_account_new_accountplan','nav_new_account_new_accountserviceline','navContacts','navAddresses','navActivities', 'navActivityHistory', 'navSubAct','navRelationships','navOpps','navQuotes','navOrders','navInvoices','navService','navContracts','navListsInSFA','navCampaignsInSFA');
var i; var iStartIndex = 0;
// total no of navigation items defined in the oTempArray variable
var iEndIndex = 10;
var iEndObject = document.getElementById(oTempArray[iEndIndex]);
for(iStartIndex; iStartIndex <= iEndIndex; iStartIndex++ )
{
if(document.getElementById(oTempArray[iStartIndex]))
{
i = document.getElementById(oTempArray[iStartIndex]);
i.parentNode.parentNode.insertBefore(i.parentNode, iEndObject.parentNode );
}
}
}