Connect To Organization Web service in MS CRM 2011

Provide the connection to the server using a connection string. You can find the CrmConnection class in namespace Microsoft.Xrm.Client and dll (Microsoft.Xrm.Client.dll which is avaialbale in sdk/bin folder)

//The following example shows the connection string using Active Directory authentication:

Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(“Url=http://<Crm Server>/<Orgnization Name>;Domain=<contoso>;Username= Abc;Password=Abc;”);

// Create object of Organization Service

OrganizationService service  = new OrganizationService(connection);

Entity entity = new Entity(“lead”);
entity[“subject”] = “Test”;
entity[“firstname”] = “Arvind”;
entity[“lastname”] = “Singh”;
Guid leadId = service.Create(entity);

For details, please go through below link

hope it helps..

Calling EXE or Executing command from CRM 2011 Ribbon button

I had a requirement to execute command or call exe file from CRM Ribbon button which open SAP GUI shortcut based on some parameter which we need to pass as  parameter  from CRM Entity Form. We had written the following function which was called from CRM button.

function CallSAPGUI(l_SAPID)
    var l_c_ConvertToCharCode = String.fromCharCode(34);
var obj_ActiveX = new ActiveXObject(‘WScript.Shell’);

l_s_CommendText = ‘start sapshcut.exe’ + ‘ -user=’ + l_c_ConvertToCharCode + l_SAPID + l_c_ConvertToCharCode + ‘ -client=017’ + ‘ -language=EN’ + ‘ -system=ABC’ + ‘ -gui=/M/vhdh08.ct056.tss.loc/S/3600/G/ct_01’ + ‘ -command=*/TTC/ZZ_PP_RAT_TA3/CLA/ZZ_PP_TARHD-NUM=1000-34;’ + ‘ –maxgui’;

 if (obj_ActiveX)
obj_ActiveX.Run(‘cmd.exe /c ‘ + l_c_ConvertToCharCode + l_s_CommendText + l_c_ConvertToCharCode);

We were using this code in CRM 2011 outlook client. Once I deployed this code , I thought this code will work but I got the below error.

Automation server can’t create object

I visited various blog and found that we need to do the following setting in IE. We need to do the below setting for both “Local Intranet ” and” Trusted Sites ” of Security Tab. Once i did the browser setting SAP GUI was working fine on button click.


Hope it will help you !!


Add button in existing group of Ribbon

Let’s say, we want to add a custom button in Activity group of Contact and on click it will open a window to create CustomerVisits (new_customervisit) record which is a custom activity.

Follow the below steps to create a button in existing group.
Step #1 Create a new solution say TestSolution.
Step #2 Open newly created TestSolution and the entity on which you want to button.I have added contact entity.
Step #3 Publish All Customization
Step #4 Export the TestSolution for editing.
Step #5 Open customization.xml file from exported solution for editing.
Step #6 Find out RibbonDiffXml tag and replace the code from <RibbonDiffXml> to </RibbonDiffXml>With below code.




<CustomAction Id=”” Location=”” Sequence=”41″>


<Button Id=”” Command=”” Sequence=”15″ ToolTipTitle=”$” LabelText=”$” ToolTipDescription=”$” TemplateAlias=”isv” Image32by32=”http://<crm&gt;:5555/PuneCRMTest/WebResources/new_customerVisits” Image16by16=”http://<crm&gt;:5555/PuneCRMTest/WebResources/new_AppAdd” />





<RibbonTemplates Id=”Mscrm.Templates”></RibbonTemplates>



<CommandDefinition Id=””>

<EnableRules />

<DisplayRules />


<Url Address=”http://<crm&gt;:5555/PuneCRMTest/main.aspx?etn=new_customervisit&amp;pagetype=entityrecord” PassParams=”false” WinParams=”0″ />





<TabDisplayRules />

<DisplayRules />

<EnableRules />



<LocLabel Id=””>


<Title languagecode=”1033″ description=”CustomerVisits Description” />



<LocLabel Id=””>


<Title languagecode=”1033″ description=”CustomerVisits” />





Step #7 Save the customization.xml file.
Step #8 Zip the all three files (cutomiztion, solution and [Content_Types]) and import into CRM
Step #9 Remove the contact entity from TestSolution.
Step #10 Delete the solution TestSolution.

Import attachment into MS CRM 2011 entity

Let’s say we want to attach some documents in Contact entity records. We can use out of box Import Data Tool to upload data/attachments into MS CRM 2011.To import attachment into particular record we need to identify a unique key for the record(let’s say for contact entity, it’s contact id i.e. GUID or any field which is unique).

Below is the step by step procedure to import attachment for contact’s record.
Prepare Source Data:

Step #1 Go to Data Management ->Templates for Data Import -> Select Note and click on Download.
Step #2 Edit the downloaded template as shown below.

Description of Columns:
Title: This would be Title of attached file.
File Name: File name of the attachment.
Mime Type: Type of attachment like text/plain.
Regarding:  Reference of record’s field name. In my case I have selected Contact’s Full Name.
Document: Document Id of attached file.
Owner: Owner name must be the CRM user.
Description: Description of file.

Step #3 Build the folder structure for attachments and data file:
Below are some guidelines for file size and folder structure.

If you want to Import multiple files in one Import session, you can .zip them together. A .zip file can include files of .csv, .xml, or .txt file types. All files in a single compressed file must be of the same file type.

The .zip file must confirm to one of these folder structure:

  • .zip file having the files and optional attachment folder directly in it:-
    • Attachments (Folder)
    • <File1>
    • <File2>
    • <File3>

Note: By default, the maximum size of the files you can import is 8 megabytes (MB). This means:

  • Any .csv, .txt, or .xml file must not exceed 8 MB.
  • Any individual file inside the .zip file must not exceed 8 MB and the total size of the .zip file, including the Attachment folder, must not exceed 32 MB.

You can choose any of the above file formats and give it as an input to the Import Data wizard. The delimited .txt, .csv, or XML Spreadsheet 2003 format files can be easily created by using Microsoft Office Excel.

In my case, I followed this “ZIP folder that contain data files and one Attachment folder directly under root” i.e.

  • ContactImport(Zip file name)
    • Attachments(folder)
    • Note.xml

Step #4 Import the file using Import Data feature (Data Management ->Imports).
Step #5 Click Next
Step#6 Select “SampleDataMap” and Click Next.
Step#7 Select “Note” for Microsoft Dynamics CRM Record Types and Click Next.
Step#8 Select mapping fields from CRM Fields as shown below and Click Next.
Step#8 Clicks on Next.
Step#9 Select Allow Duplicates “No”  and Click Submit.
You can write Data map Name for future import.
Step#9 Data has been submitted for import. It may take time based on size of data.

Step#10 Please check the contact record for attachment.

Custom Get Started Pane for help or video file

Let’s suppose we want to embed a video or html help file for Account entity on Get Started Pane of Account entity.

The default content for the get started pane is located with the Help content. The content is exposed in the application through attributes in the <SubArea> (SiteMap) element for specific entities. This content cannot be included in a solution and, therefore, cannot be transported with a solution.

To create custom get started pane content, the Microsoft Dynamics CRM SDK includes a set of files that replicate the appearance and behavior of the get started pane pages. These files are located at SDK\Resources\GetStartedPaneTemplate.

Below are steps to create custom get started pane.


We want to place a custom video and help file on Get Started Pane of Account entity.

Step #1 Import solution “helpvisorcomponents_1_0_0_0” which is available at \sdk\resources\getstartedpanetemplate of CRM 2011 sdk.

Step #2 Create a virtual directory (Let’s say” Video”) on server in ISV folder of CRMWeb
and keep the video file there. Update the below url in helpvisortemplate1.htm file.
URL: http://<CrmServer>:5555/ISV/Video/newCRMjquery_ch9.wmv

Step #3 Edit the “helpvisortemplate.htm” file which is at \sdk\resources\getstartedpanetemplate\helpvisor\1033 of CRM 2011 Sdk and rename the file name as helpvisortemplate1.htm .

Step #4 Create html help file say Help.htm.

Step #5 Create below Web Resources in same solution with similar structure as below


Step #6 Add the Site Map to existing solution and export it for editing.

Step #7 Open customization.xml file from exported solution in edit mode.

Replace below code (Usually at 4 places)

<SubArea Id=”nav_accts” DescriptionResourceId=”Account_SubArea_Description” Entity=”account” GetStartedPanePath=”Accounts_Web_User_Visor.html” GetStartedPanePathAdmin=”Accounts_Web_Admin_Visor.html” GetStartedPanePathOutlook=”Accounts_Outlook_User_Visor.html” GetStartedPanePathAdminOutlook=”Accounts_Outlook_Admin_Visor.html” />
With below code
<SubArea Id=”nav_accts” DescriptionResourceId=”Account_SubArea_Description” Entity=”account” GetStartedPanePath=”Accounts_Web_User_Visor.html” GetStartedPanePathAdmin=”Accounts_Web_Admin_Visor.html” GetStartedPanePathOutlook=”Accounts_Outlook_User_Visor.html” GetStartedPanePathAdminOutlook=”Accounts_Outlook_Admin_Visor.html” />

<SubArea Id=”nav_accts” DescriptionResourceId=”Account_SubArea_Description” Entity=”account” GetStartedPanePath=”$webresource:sample_/redir.htm?data=HelpVisorTemplate1.htm” GetStartedPanePathAdmin=”$webresource:sample_/redir.htm?data=HelpVisorTemplate1.htm” GetStartedPanePathOutlook=”$webresource:sample_/redir.htm?data=HelpVisorTemplate1.htm” GetStartedPanePathAdminOutlook=”$webresource:sample_/redir.htm?data=HelpVisorTemplate1.htm” />

Step #8 Save the customization.xml file
Step #9 Zip all the file with updated customization.xml
Step #10 Import the updated solution and publish all customization.
Step #11 the final output should look like as below.
Step #12 on click of video link; it will play a custom video (not out of box) file in media player and “Help”
link will open html help file.


Moving CRM Servers(Application and Database) to New DataCentre

One of our client wanted to move CRM Server from One Data Centre to different data centre but due to some constraint we could not move it by creating New Organization or by new deployment. We had only left option was update IP address manually.

Recently we moved our CRM Server from one data centre to new data centre due to which IP Address of both Application and Database Server was changed. We had updated new IP Address in Registry(MSCRMconfigdb,database,LocalSdkHost,metabase,ServerUrl,SQLRSServerUrl), Application Pool, Web.Config and custom application. But even after updating new IP address on above section  we were getting the following error.

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Source Error:

An unhandled exception was generated during the execution   of the current web request. Information regarding the origin and location of   the exception can be identified using the exception stack trace below.

Stack Trace:

[SocketException (0x274c): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond]
   System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239
   System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35
   System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224

[WebException: Unable to connect to the remote server]
   System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) +1868309
   System.Net.HttpWebRequest.GetRequestStream() +13
   System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +103
   Microsoft.Crm.Metadata.MetadataWebService.GetDataSet() +31
   Microsoft.Crm.Metadata.DynamicMetadataCacheLoader.LoadDataSetFromWebService(Guid orgId) +291
   Microsoft.Crm.Metadata.DynamicMetadataCacheLoader.LoadCacheFromWebService(LoadMasks masks, Guid organizationId) +42
   Microsoft.Crm.Metadata.DynamicMetadataCacheFactory.LoadMetadataCache(LoadMethod method, CacheType type, IOrganizationContext context) +408
   Microsoft.Crm.Metadata.MetadataCache.LoadCache(IOrganizationContext context) +339
   Microsoft.Crm.Metadata.MetadataCache.GetInstance(IOrganizationContext context) +388
   Microsoft.Crm.BusinessEntities.BusinessEntityMoniker..ctor(Guid id, String entityName, Guid organizationId) +116
   Microsoft.Crm.Caching.UserDataCacheLoader.LoadCacheData(Guid key, ExecutionContext context) +323
   Microsoft.Crm.Caching.ObjectModelCacheLoader`2.LoadCacheData(TKey key, IOrganizationContext context) +401
   Microsoft.Crm.Caching.BasicCrmCache`2.CreateEntry(TKey key, IOrganizationContext context) +84
   Microsoft.Crm.Caching.BasicCrmCache`2.LookupEntry(TKey key, IOrganizationContext context) +135
   Microsoft.Crm.BusinessEntities.SecurityLibrary.GetUserInfoInternal(WindowsIdentity identity, IOrganizationContext context, UserAuth& userInfo) +252
   Microsoft.Crm.BusinessEntities.SecurityLibrary.GetCallerAndBusinessGuidsFromThread(WindowsIdentity identity, Guid organizationId) +179
   Microsoft.Crm.Authentication.CrmWindowsIdentity..ctor(WindowsIdentity innerIdentity, Boolean publishCrmUser, Guid organizationId) +252
   Microsoft.Crm.Authentication.WindowAuthenticationProviderBase.Authenticate(HttpApplication application) +431
   Microsoft.Crm.Authentication.AuthenticationStep.Authenticate(HttpApplication application) +172
   Microsoft.Crm.Authentication.AuthenticationPipeline.Authenticate(HttpApplication application) +86
   Microsoft.Crm.Authentication.AuthenticationEngine.Execute(Object sender, EventArgs e) +525
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75


Actually It was still referring Old IP Address at some places. To resolve the issue we enable the trace log and get CrmServerReportInformation with help of “Create File” option of  CrmDiagTool 4.0  and came to know that DeploymentProperty Table(Column Name- ADSdkRootDomain, ADWebApplicationRootDomain and AsyncSdkRootDomain) of MSCRM_Config was still referring old IP Address. We have updated this column with new IP Address as below and everything start working fine.


Update DeploymentProperties SET NVarCharColumn = ‘New IP Address’  WHERE ColumnName= ‘AsyncSdkRootDomain’

Update DeploymentProperties SET NvarCharColumn = ‘New IP Address’  WHERE ColumnName = ‘ADSdkRootDomain’

Update DeploymentProperties SET NvarCharColumn = ‘New IP Address’  WHERE ColumnName = ‘ADWebApplicationRootDomain’


Hope this help you 🙂

Interacting Silverlight with CRM Forms

Silverlight application can get a reference to the Xrm.Page Object instance using either of following approaches.

1. Using HTML bridge feature of Silverlight

ScriptObject  xrm = (ScriptObject)HtmlPage.Window.GetProperty(“Xrm”);

ScriptObject  page= (ScriptObject)xrm.GetProperty(“Page”);

2. Using Dynamic Language Runtime

Using DLR you can utilize the dynamic language keywords which allow resolving method calls at runtime.

dynamic  xrm = (ScriptObject)HtmlPage.Window.GetProperty(“Xrm”);


Below is some important methods/property which is useful for Silverlight Application.

1. Getting the current Theme: This is useful if you are trying to style your Silverlight content in a similar way the user will see the web client. Valid Values are Default, Office12Blue, and Office14Silver.

var theme= xrm.Page.context.getCurrentTheme();

2.      Getting Org Name:

var orgName= xrm.Page.context.getOrgUniqueName();

3.      Getting the Server URL:

var serverUrl = xrm.Page.context.getServerUrl();

4.      Getting the User ID:

Knowing the user id that is working with the current page can be helpful when you need to do things like retrieve all the records that are owned by that person to present on the page.


var  userID = xrm.Page.context.getUserId();

5.      Getting the user’s Role:

var roles = xrm.Page.context.getUserRoles();

6.      Getting the entity logical Name:

String entityname;

7.      Getting the Entity Id:
Guid entityID =;

8.      Checking if Entity is Dirty:

By checking the dirty flag at the entity level you can quickly determine if there have been any changes to any of the fields. This doesn’t give you field level granularity you have to check each attribute if you need that.

bool isDirty =;

9.      Getting the Data as XML:

Using this feature you can get a string that represents the XML that would be sent to the server when the record is saved. The XML contains only the fields which have been modified.

String dataXml =;

10.  Saving Data to the Server:

The save function allows you to simulate saving data to the CRM server just like if the user hit the save button in the ribbon.

11.  Working with the Entity Attributes

You can get to the attributes on an entity via the Attributes collection. The different attribute types can have special methods that are only for their specific type.The following shows which methods each type of attribute currently has.

All Attribute have these methods:

addOnChange,fireOnChange, getAttributeType,getFormat,getInitialValue, getIsDirty, getName, getParent,getRequiredLevel, getSubmitMode, getUserPrivelege, getValue, removeOnChange, setRequiredLevel, setSubmitMode, and setValue

Money,decimal,integer and double have these methods too:

getMax, getMin, and getPrecision

Boolean and Optioset attributes have these methods:


Optionset attributes have these methods:

getOption, getOptions, getSelectedOption, and getText


12.  UI Methods:

The UI methods are high level methods located at and are the starting point for working with the UI controls. This is also the starting point for looking for Controls and Tabs.

Refreshing the Ribbon:

This method is beyond helpful if you are doing any enable/display rules that depends on values on the form. After the value is changed on the form you can use this method to force the ribbon to re-evaluate the data in the form so the ribbon is updated.


13.  Working with Form Controls:

The following methods are on all controls:

getControlType, getDisabled, getLabel, getName, getParent, setDisabled(all except web resources), setFocus, setLabel, and setVisible

The following methods are specific to Lookups;

addCustomeView, getDefaultView, and setDefaultView

The following methods are specific to Option Sets

adoption,clearOptions, and removeOption

The following methods are specific to Web Resources:

getData, getObject, setData, keep in mind the get/setData can only be used with Silverlight Web resources

The Following methods are specific to IFrames:

getSrc, setSrc, and getInitalUrl

The following methods are specific to Subgrids: