Archive for July, 2012

Getting logged in user’s GUID in CRM reports

We can get the logged in user GUID in the custom reports deployed in CRM using “fn_FindUserGuid()”  function

Below is the sample query for the same


SELECT @currUserId=dbo.fn_FindUserGuid()

PRINT @currUserId


Restart remote machine using command prompt

We can restart a remote machine if you are domain administrator.

Consider a scenario Machine 1 & Machine 2 are part of Domain “”.

Assume “Machine 1” hanged and not even letting you to Shut down or Restart.

So to restart the machine 1,

Login as administrator to “Machine 2”

  • Open Command Prompt
  • Type shutdown /I and click Enter
Command Shutdown

Command Shutdown

  • It opens a window as below, click Add, type in the name of the remote device (i.e., Name of Machine 1), and hit OK
Remote Shutdown Dialog

Remote Shutdown Dialog

  • Choose the option “Restart/Shutdown” and enter comments
  • Click Ok


File name ABC.pdf is invalid – error while creating attachment programmatically

The other day I was getting “Invalid file name” error when I try to create an attachment with .pdf file and associating to Email, in my plug-in. (link)


  • Reason was “pdf” was added as blocked file extension for attachments in my CRM organization.

Fix :-

  • Go to “Settings -> Administration -> System Settings”
  • Remove pdf from “Blocked file extension for attachment”
Blocked file extensions

Blocked file extensions

  • Click ‘OK’


XrmServiceToolkit for CRM 2011

XrmServiceToolkit is a JavaScript library which can be used for JavaScript Development under the platform for CRM 2011 environments.

Download from Codeplex link

It contains single jscirpt file “XrmServiceToolkit.js

The library contains three major parts regarding functions.

  • Common: General Methods used for various purpose.
  • Rest: Organization Data Service functions including CRUD, Associate, Disassociate, etc
  • Soap: Organization Service functions including CRUD, Fetch, Associate, Disassociate, etc


Plug-ins in CRM 2011 – Useful points

Plug-in stages

  • Pre validation
    • Registered Plug-in run before the form is validated
    • Useful if you want to implement business logic before the actual validation starts.  i.e., Changes made in plug-in won’t be saved if the validation of the main system plugins complain because the changes are outside the database transaction.
    • Ex – Some “delete” plug-ins. Deletion cascades happen prior to pre-operation, therefore if you need any information about the child records, the delete plugin must be pre-validation.
  • Pre -operation
    • After validation and before the values are saved to the database
  • Post operation
    • Plugin will run after the values have been inserted/changed on the database

Database Transactions in Plug-Ins

  • Plug-ins may or may not execute within the database transaction
  • You can check if the plug-in is executing in-transaction by reading the ‘IsInTransaction‘ property of IPluginExecutionContext
  • Stages 20 and 40 are part of the database transaction while stage 10 and 50 may be part of the transaction
  • If plugin throws an exception, every action done during the transaction will be rollback

Few more Points

  • Whether a plug-in executes synchronously or asynchronously, there is a 2 minute time limit imposed on the execution of a (message) request.
  • If the execution of your plug-in logic exceeds the time limit, a Timeout exception is thrown
  • If a plug-in needs more processing time than the 2 minute time limit, consider using a workflow or other background process
  • ‘Pre-operation’ operations that CRM will do will not be carried out in pre-validation stage.
    • If you are deleting a record that has many-to-many relationship records with another entity; these relationship records will still be available in pre-validation stage, but not in pre-operation stage.
  • “Target” entity (i.e., pluginContext.InputParameters[“Target”])
    • It’s the entity on which plug-in registered
    • It only contains “dirty” attributes. if you convert to early bound, the value of the unchanged attribute will be null

Useful MSDN article :)

Activate or Deactivate record using jscript


Below is the script to Activate or Deactivate record using jscript.

// ‘State’  – Activate 0; InActive 1

// ‘Status’ – Active 1; InActive 2

function ActivateOrDeactivate(entityName, entityId, status, state) {

var setStateRequest = ‘<s:Envelope xmlns:s=”“>’ +

‘<s:Body>’ +

‘<Execute xmlns=”” xmlns:i=”“>’ +

‘<request i:type=”a:UpdateRequest” xmlns:a=”“>’ +

‘<a:Parameters xmlns:b=”“>’ +

‘<a:KeyValuePairOfstringanyType>’ +

‘<b:key>EntityMoniker</b:key>’ +

‘<b:value i:type=”a:EntityReference”>’ +

‘<a:Id>’ + entityId + ‘</a:Id>’ +

‘<a:LogicalName>’ + entityName + ‘</a:LogicalName>’ +

‘<a:Name i:nil=”true”></a:Name>’ +

‘</b:value>’ +

‘</a:KeyValuePairOfstringanyType>’ +

‘<a:KeyValuePairOfstringanyType>’ +

‘<b:key>State</b:key>’ +

‘<b:value i:type=”a:OptionSetValue”>’ +

‘<a:Value>’ + state + ‘</a:Value>’ +

‘</b:value>’ +

‘</a:KeyValuePairOfstringanyType>’ +

‘<a:KeyValuePairOfstringanyType>’ +

‘<b:key>Status</b:key>’ +

‘<b:value i:type=”a:OptionSetValue”>’ +

‘<a:Value>’ + status + ‘</a:Value>’ +

‘</b:value>’ +

‘</a:KeyValuePairOfstringanyType>’ +

‘</a:Parameters>’ +

‘<a:RequestId i:nil=”true”></a:RequestId>’ +

‘<a:RequestName>SetState</a:RequestName>’ +

‘</request>’ +

‘</Execute>’ +

‘</s:Body>’ +


var req = new XMLHttpRequest();

var serverUrl = Xrm.Page.context.getServerUrl();“POST”, serverUrl, false);

req.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);

req.setRequestHeader(“SOAPAction”, ““);


if (req.status != 200) {

alert(“Error while set status – “+req.responseXML);



How Do I call this method :-

  • Below is the sample to activate “Contact” record

var contactId={contact GUID};

ActivateOrDeactivate(“contact”, contactId, 0, 1);


Hide or Show Form Assistant in CRM 2011


We can Enable/Disable and Expand/Collapse the ‘Form Assistant’ by default in CRM 2011 using Form properties.

Navigate to “Settings -> Default Solution -> Entity Customization Form -> Form Properties”

Form Assistant Settings

Form Assistant Settings

You can even use below JScript to hide/show the Form Assistant

document.getElementById(‘tdRelatedInformationPane’).style.display = ‘none’;  // ‘none’ to hide and ‘block’ to show


Adding file as “Attachment” to activities programmatically in plug-in


We can add file as attachment and associate to the CRM objects i.e., Email, Task etc…

Email with attachment

Email with .pdf file as attachment

The entity that store attachment information is “activitymimeattachment”

Below is the code snippet to add “.pdf” file as attachment to the Email activity

Entity attachment = new Entity(“activitymimeattachment”);

attachment[“subject”] = “My Subject”;

string fileName = “Sample.pdf”;

attachment[“filename”] = fileName;

byte[] fileStream= = new byte[] { }; //Set file stream bytes

attachment[“body”] = Convert.ToBase64String(fileStream);

attachment[“mimetype”] = “text/plain”;

attachment[“attachmentnumber”] = 1;

Guid emailId; //GUID of Email activity

attachment[“objectid”] = new EntityReference(“email”, emailId);

attachment[“objecttypecode”] = “email”;

IOrganizationService service;


Note :-

  • In the above code the property “objecttypecode” is slight misleading, as it expects “EntityLogicalName” rather than “EntityTypeCode”
  • So make sure to set  attachment[“objecttypecode”] = EntityLogicalName (i.e., email)