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.