Posts Tagged ‘CRM’

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.

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 🙂

As mentioned in CRM Sdk, below is the major differences between Data Migration and Data Import.

Data migration and data import use common entity model and messages. However, there are some important differences in the feature sets of the two operations as shown in the following table.

Feature Data Migration Data Import
Import data into Microsoft Dynamics CRM Yes (Only the system administrator can migrate data in the offline mode.) Yes (All users who have appropriate permissions can import data.)
Import data into custom entity types and attributes Yes Yes
Use multiple source files that contain related data Yes No (You can only import one file at a time.)
Assign entity instances to multiple users Yes No (All entity instances are assigned to one user.)
Update existing entity instances No Yes
Detect duplicates No (You can run duplicate detection after you migrate the data.) Yes
Delete all entity instances associated with one job Yes (Use bulk delete feature.) Yes (Use bulk delete feature.)
Automatically map data based on column headings in the source file No Yes
Set the value of the createdon attribute for the entity from source data Yes No
Customize Microsoft Dynamics CRM to match source data No (Custom entities and attributes can be created by Data Migration Manager.) No (Customization must be done before import.)
Apply complex data transformation mapping Yes No
Import state and status information Yes No

 Step 1.

Step 2.

Step 3.

Let me explain the scenario…

Suppose we have City Lookup on Lead entity and we want to populate Region (Lookup), State (Lookup) and Zone (Lookup) on selection of particular City from City Lookup. You need to write below code on OnChange event of City Lookup field.

if(crmForm.all.new_cityid.DataValue !=null)


    var citylookupValues = crmForm.all.new_cityid.DataValue;

    if(citylookupValues[0] !=null)


        var cityID = citylookupValues[0].id;

        var regionID = GetAttributeValueFromID(“new_city”, cityID , “new_regionid”);

        var stateID = GetAttributeValueFromID(“new_city”, cityID , “new_stateid”);

        var zoneID = GetAttributeValueFromID(“new_region”, regionID , “new_zoneid”);   

        if(regionID != null)


            //Create an array to set as the DataValue for the lookup control.

            var regionlookupData = new Array();

            //Create an Object add to the array.

            var regionlookupItem= new Object();

            //Set the id, typename, and name properties to the object.

   = regionID;

            regionlookupItem.typename = ‘new_region’;

   = regionName;

            // Add the object to the array.

            regionlookupData[0] = regionlookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_regionid.DataValue = regionlookupData;

            crmForm.all.new_regionid.ForceSubmit = true;



        if(stateID != null)


            //Create an array to set as the DataValue for the lookup control.

            var statelookupData = new Array();

            //Create an Object add to the array.

            var statelookupItem = new Object();

            //Set the id, typename, and name properties to the object.

   = stateID;

            statelookupItem.typename = ‘new_state’;

   = stateName;

            // Add the object to the array.

            statelookupData[0] = statelookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_stateid.DataValue = statelookupData;

            crmForm.all.new_stateid.ForceSubmit = true;


        if(zoneID != null)


            var zoneName = GetAttributeValueFromID(“new_zone”, zoneID, “new_name”);

            //Create an array to set as the DataValue for the lookup control.

            var zonelookupData = new Array();

            //Create an Object add to the array.

            var zonelookupItem = new Object();

            //Set the id, typename, and name properties to the object.

   = zoneID;

            zonelookupItem.typename = ‘new_zone’;

   = zoneName;

            // Add the object to the array.

            zonelookupData[0] = zonelookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_zoneid.DataValue = zonelookupData;

            crmForm.all.new_zoneid.ForceSubmit = true;






     crmForm.all.new_regionid.DataValue = null;

    crmForm.all.new_stateid.DataValue = null;

    crmForm.all.new_zoneid.DataValue = null;



function  GetAttributeValueFromID(sEntityName, sGUID, sAttributeName)



    * sEntityName: the name of the CRM entity (account, etc.)

    * whose attribute value wish to look up

    * sGUID: string representation of the unique identifier of the specific object whose attrbuite value we wish to look up

    * sAttributeName – the schema name of the attribute whose value we wish returned



    var sXml = “”;

    //var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);

    var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP.6.0”);


    //var serverurl = “;;

    var serverurl = “”;


    //set up the SOAP message

    sXml += “<?xml version=\”1.0\” encoding=\”utf-8\” ?>”;

    sXml += “<soap:Envelope xmlns:soap=\”\””

    sXml += ” xmlns:xsi=\”\””

    sXml += ” xmlns:xsd=\”\”>”;

    sXml += “<soap:Body>”;

    sXml += “<entityName xmlns=\”\”>” +

    sEntityName + “</entityName>”;

    sXml += “<id xmlns=\”\”>” +

    sGUID + “</id>”;

    sXml += “<columnSet xmlns=\”\””

    sXml += ” xmlns:q=\”\””

    sXml += ” xsi:type=\”q:ColumnSet\”><q:Attributes><q:Attribute>” +

    sAttributeName + “</q:Attribute></q:Attributes></columnSet>”;

    sXml += “</soap:Body>”;

    sXml += “</soap:Envelope>”;


    // send the message to the CRM Web service

    oXmlHttp.Open(“POST”, serverurl +




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

    oXmlHttp.setRequestHeader(“Content-Length”, sXml.length);



    // retrieve response and find attribute value

    //var result = oXmlHttp.responseXML.selectSingleNode(“//” + sAttributeName);

    var result = oXmlHttp.responseXML.selectSingleNode(“//*[local-name()=\””+  sAttributeName +”\”]”);

    if (result == null)


    return “”;



    return result.text;


This is an example on how to create a button on the form, using java script. First of all we need to create a nvarchar attribute and put it on the form where we want our button.
In this example my attribute’s schema name is new_test.

Here is the code


someFunction = function()


alert(“button clicked!”);


// This is how we call the button, what we see

crmForm.all.new_test.DataValue = “Button”;

// We could align it a bit = “center”;

crmForm.all.new_test.vAlign = “middle”;

//we make the mouse look as a hand when we’re moving over = “hand”; = “#CADFFC”; = “#FF0000”; = “#330066”; = “bold”;

crmForm.all.new_test.contentEditable = false;

//we attach some events in order to make it look nice 🙂





function color3() { = “#6699FF”;


function color4() { = “CADFFC”;


function color1() { = “000099”;


function color2() { = “FF0000”;


//here we attach what we want our button do

Replace a field to a label (use replaceNode())
/* replace new_field_d to a label */
if (crmForm.all.new_field != null)
var html = document.createElement( “”);
html.innerText = “this is a lable”;

Append text under a field (you don’t need to create an attribute for that)
/* append text under new_field */
if(crmForm.all.new_field != null)
var html= document.createElement( “”);
html.innerText = “this is a text field”;

private bool RevokeAccessToEntity(ICrmService service, Guid guidValue, Guid entityID, string EntityName)
bool isSuccess = false;
// Create the SecurityPrincipal object.
SecurityPrincipal principal = new SecurityPrincipal();

// PrincipalId is the GUID of the team whose access is being revoked.
principal.Type = SecurityPrincipalType.Team;

principal.PrincipalId = guidValue;

// Create the target for the request.
TargetOwnedDynamic target = new TargetOwnedDynamic();
// EntityId is the GUID of the Opportunity to which
// access is being revoked.
target.EntityId = entityID;
target.EntityName = EntityName;

// Create the request object.
RevokeAccessRequest revoke = new RevokeAccessRequest();
// Set the properties of the request object.
revoke.Revokee = principal;
revoke.Target = target;
// Execute the request.

RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revoke);
isSuccess = true;
catch (Exception ex)
isSuccess = false;
throw ex;
return isSuccess;


using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.Crm.Sdk;

using Microsoft.Crm.SdkTypeProxy;

using Microsoft.Crm.Sdk.Query;

using System.Web.Services.Protocols;

namespace CRM.Customization.AutoNumber


public class AutoNumberPlugIns:IPlugin


DynamicEntity entity = null;

int startNumber;

string prefix = string.Empty;

string seperator = string.Empty;

int nextMaxNumber;

string uniqueId = string.Empty;

#region IPlugin Members

public void Execute(IPluginExecutionContext context)


if (context.InputParameters.Properties.Contains(“Target”) &&

context.InputParameters.Properties[“Target”] is DynamicEntity)


entity = (DynamicEntity)context.InputParameters.Properties[“target”];

ICrmService service = context.CreateCrmService(true);

if (entity.Name ==“new_testentity”)


// Find maximum number

int maxNumber = FindMaxNumber(service);

nextMaxNumber=maxNumber + 1;

if (nextMaxNumber > 0)


bool isRetrivePrefixSuccess = RetrievePrefixSufixAndStartNumber(service);

if (isRetrivePrefixSuccess)


if (nextMaxNumber >= startNumber)


string buildAutoNumber = prefix + seperator + nextMaxNumber.ToString();

uniqueId = buildAutoNumber;

StringProperty uId = new StringProperty(“new_uniqueid”, uniqueId);


CrmNumber nextNumber = new CrmNumber();

nextNumber.Value = nextMaxNumber;

CrmNumberProperty uniqueNo = new CrmNumberProperty(“new_uniqueno”, nextNumber);








private int FindMaxNumber(ICrmService service)


int maxNo=0;

QueryExpression query = new QueryExpression();

query.EntityName = “new_testentity”;

ColumnSet cols = new ColumnSet();


query.ColumnSet = cols;

query.AddOrder(“new_uniqueno”, OrderType.Descending);

PagingInfo pageInfo = new PagingInfo();

pageInfo.Count = 1;

pageInfo.PageNumber = 1;

query.PageInfo = pageInfo;

RetrieveMultipleRequest request = new RetrieveMultipleRequest();

request.Query = query;

request.ReturnDynamicEntities = true;

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

DynamicEntity testEntity = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];

for (int i = 0; i < testEntity.Properties.Count; i++)


if (testEntity.Properties.Contains(“new_uniqueno”))


CrmNumber uniqueNumber = (CrmNumber)testEntity.Properties[“new_uniqueno”];

maxNo = uniqueNumber.Value;



return maxNo;


private bool RetrievePrefixSufixAndStartNumber(ICrmService service)




QueryByAttribute query = new QueryByAttribute();

query.EntityName = “new_autonumber”;

ColumnSet cols = new ColumnSet();





query.ColumnSet = cols;

query.Attributes = new string[] { “new_entityname” };

query.Values = new object[] { “new_testentity” };

RetrieveMultipleRequest request = new RetrieveMultipleRequest();

request.Query = query;

request.ReturnDynamicEntities = true;

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

DynamicEntity dynamicsEntity = (DynamicEntity)response.BusinessEntityCollection.BusinessEntities[0];

if (dynamicsEntity.Properties.Count > 0)


// DynamicEntity autoNumberEntity = (DynamicEntity)dynamicsEntity.BusinessEntities[0];

// Extract the fullname from the dynamic entity string fullname;

for (int i = 0; i < dynamicsEntity.Properties.Count; i++)


if (dynamicsEntity.Properties.Contains(“new_startnumber”))


CrmNumber startNo = (CrmNumber)dynamicsEntity.Properties[“new_startnumber”];

startNumber = startNo.Value;


if (dynamicsEntity.Properties.Contains(“new_prefix”))


String prefixId = (String)dynamicsEntity.Properties[“new_prefix”];

prefix = prefixId.ToString();


if (dynamicsEntity.Properties.Contains(“new_separator”))


String seperaterId = (String)dynamicsEntity.Properties[“new_separator”];

seperator = seperaterId.ToString();




return true;


catch (SoapException ex)


throw ex;