Archive for the ‘Microsoft .NET’ Category

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 🙂

public void SendMail(ICrmService service,Guid ownerID, Guid fromGuid, ArrayList toGuid,Guid recordRegardingID,Guid templateId,Enum  enitityName)

// Create an instance of email
email myEmail = new email();
//set the owner of the mail
myEmail.ownerid = new Owner();
myEmail.ownerid.type = EntityName.systemuser.ToString();
myEmail.ownerid.Value = ownerID;
// specify the from part of the email
activityparty from = new activityparty();
from.partyid = new Lookup();
from.partyid.type = EntityName.systemuser.ToString();
// guid of the system user who is sending the mail
from.partyid.Value = fromGuid;
myEmail.from = new activityparty[] { from };

activityparty[] apTo = new activityparty[toGuid.Count];
// creating as many activity party as the no of users or members in a team
int i = 0;
foreach (String memberID in toGuid)
apTo[i] = new activityparty();
apTo[i].partyid = new Lookup();
apTo[i].partyid.type = EntityName.systemuser.ToString();
apTo[i].partyid.Value = new Guid(memberID);
} = apTo;
TargetSendFromTemplateEmail myTargetSendFromTemplateEmail = new TargetSendFromTemplateEmail();
myTargetSendFromTemplateEmail.Email = myEmail;
SendEmailFromTemplateRequest mySendEmailFromTmpRequest = new SendEmailFromTemplateRequest();
// Specify entity instance id for RegardingID
mySendEmailFromTmpRequest.RegardingId = recordRegardingID;
// Specify the type of entity
mySendEmailFromTmpRequest.RegardingType = enitityName.ToString();
// Specify the email instance to be sent
mySendEmailFromTmpRequest.Target = myTargetSendFromTemplateEmail;
// Specify the template to be used ( Either a global or created specfially for that entity)
mySendEmailFromTmpRequest.TemplateId = templateId;
SendEmailFromTemplateResponse mySendEmailFromTmpResponse =(SendEmailFromTemplateResponse)service.Execute(mySendEmailFromTmpRequest);


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;






// Set up the CRM Service.

CrmAuthenticationToken token = new


// You can use enums.cs from the SDK\Helpers folder to get

the enumeration for AD Authentication.

token.AuthenticationType = 0;

token.OrganizationName =”AdventureWorksCycle”;

CrmService service = new CrmService();




service.CrmAuthenticationTokenValue = token;

service.Credentials =


// Create the column set object that indicates the

properties to be retrieved.

ColumnSet cols = new ColumnSet();

// Set the properties of the column set.

cols.Attributes = new string [] {“fullname”};

// contactGuid is the GUID of the record being retrieved.

Guid contactGuid = new Guid(“4D507FFE-ED25-447B-80DE-


// Retrieve the contact.

// The EntityName indicates the EntityType of the object

being retrieved.

contact contact =


contactGuid, cols);


CrmDiscovery service is a global installable level service that allow the caller to determine the correct organization and URL for his/her need.

Below example show how to create and configure CrmDiscoveryService Web Service proxy.


// Create and configure the CrmDiscoveryService Web service


CrmDiscoveryService discoveryService = new


discoveryService.UseDefaultCredentials = true;




// Retrieve the list of organizations that the logged on

user belongs to.

RetrieveOrganizationsRequest orgRequest = new


RetrieveOrganizationsResponse orgResponse =



// Locate the target organization in the list.

OrganizationDetail orgInfo = null;

foreach (OrganizationDetail orgDetail in






orgInfo = orgDetail;




// Check whether a matching organization was not found.

if (orgInfo == null)

throw new Exception(“The specified organization was not