Create contact and share the record which contains Lookup,Picklist and string datatype


This sample will show how to create Contact record in CRM 4.o through Web Application which contains Lookup, Picklist and String datatype.

I have created a custom entity(new_hobby) and created a 1-N relationship from Hobby to Contact. I have also created Team called CRM Team and added members to that team. Whenever a contact will be created, contact will be shared to the CRM Team which have only Read Access to that contact.

First create Web Reference to CrmService and MetaDataService  to create proxy class and include this into project with the help of using statement.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrmPractice.CrmSdk;
using System.Web.Services.Protocols;
using CrmPractice.MetaDataSdk;
namespace CrmPractice
{
public partial class _Default : System.Web.UI.Page
{
public static Dictionary<string, string> dics = new Dictionary<string, string>();
public static Dictionary<string, string> AddDics = new Dictionary<string, string>();
List<ListItem> HobbyList = new List<ListItem>();
List<ListItem> Addlist = new List<ListItem>();
string teamId = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CrmService service = GetCrmService();
CrmPractice.MetaDataSdk.MetadataService metadataService = GetMetaDataService();

//Populate Lookup Value
PopulateLookupValue(service);

//Populate Picklist Value using metadataservice
GetPickListValue(metadataService);
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
CrmService service = GetCrmService();

//Create contact record
contact conts = new contact();
conts.firstname = txtFirstName.Text;
conts.lastname = txtLastName.Text;
conts.mobilephone = txtMobileNo.Text;

// Set Hobby Lookup value

Lookup hobbyLookup = new Lookup();
hobbyLookup.name = ddlHobby.SelectedItem.Value.ToString();
hobbyLookup.type = EntityName.new_hobby.ToString();
hobbyLookup.Value = new Guid(dics[ddlHobby.SelectedItem.Value.ToString()]);
conts.new_hobbyid = hobbyLookup;

// Set AddressType Picklist value

Picklist addPickList=new Picklist();
addPickList.name=ddlAddressType.SelectedItem.Value.ToString();
addPickList.Value=Convert.ToInt16(AddDics[ddlAddressType.SelectedItem.Value.ToString()]);

conts.address1_addresstypecode = addPickList;
conts.emailaddress1  = txtEmailId.Text;

//Create Contact
Guid contactId = service.Create(conts);

// Get Team id to share the record
teamId = GetTeamId(service);

// Share record with Team
ShareWithTeam(service, contactId.ToString(), teamId);

//Clear the field
ClearField();
}
catch(SoapException ex)
{
ex.Detail.InnerText.ToString();
}
}

/// <summary>

/// /Populate Hobbylist from CRM and bind it with DropDownlist

/// </summary>

/// <param name=”service”>CRM Service</param>

private void PopulateLookupValue(CrmService service)
{
try
{
ColumnSet cols = new ColumnSet();
cols.Attributes = new string[] { “new_name”, “new_hobbyid”, };

OrderExpression order = new OrderExpression();
order.AttributeName = “new_name”;
order.OrderType = OrderType.Ascending;

QueryExpression query = new QueryExpression();
query.ColumnSet = cols;
query.EntityName = EntityName.new_hobby.ToString();
query.Orders = new OrderExpression[] { order };

BusinessEntityCollection hobbies = service.RetrieveMultiple(query);

DropDownList hb = new DropDownList();
for (int i = 0; i < hobbies.BusinessEntities.Length; i++)
{
new_hobby hobby = (new_hobby)hobbies.BusinessEntities[i];
dics.Add(hobby.new_name.ToString(), hobby.new_hobbyid.Value.ToString());
HobbyList.Add(new ListItem(hobby.new_name.ToString(), hobby.new_hobbyid.Value.ToString()));
hb.Attributes.Add(hobby.new_name.ToString(), hobby.new_hobbyid.Value.ToString());
}

ddlHobby.DataSource = HobbyList;
ddlHobby.DataBind();
}
catch (SoapException ex)
{
ex.Detail.InnerText.ToString();
}
}

/// <summary>

/// Get Picklist value using metadata service and bind

/// it with dropdown

/// </summary>

/// <param name=”metaDataService”>MetaDataService</param>

private void GetPickListValue(MetadataService metaDataService)
{
try
{
DropDownList address = new DropDownList();

AttributeMetadata metadata = new AttributeMetadata();
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest();
attributeRequest.EntityLogicalName = EntityName.contact.ToString();
attributeRequest.LogicalName = “address1_addresstypecode”;

RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)metaDataService.Execute(attributeRequest);

PicklistAttributeMetadata addressType = (PicklistAttributeMetadata)attributeResponse.AttributeMetadata;
for (int i = 0; i < addressType.Options.Length; i++)
{
AddDics.Add(addressType.Options[i].Label.UserLocLabel.Label, addressType.Options[i].Value.Value.ToString());
Addlist.Add(new ListItem(addressType.Options[i].Label.UserLocLabel.Label, addressType.Options[i].Value.Value.ToString()));
}
ddlAddressType.DataSource = Addlist ;
ddlAddressType.DataBind();

}

catch (SoapException ex)

{

ex.Detail.InnerText.ToString();

}

}

/// <summary>

/// Get CrmService

/// </summary>

/// <returns>CrmService</returns>

private CrmService GetCrmService()
{
CrmPractice.CrmSdk.CrmAuthenticationToken token = new CrmPractice.CrmSdk.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = “CMDev”;

CrmService service = new CrmService();
service.Url = http://<CrmServer>/mscrmservices/2007/crmservice.asmx;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.CrmAuthenticationTokenValue = token;
return service;
}

/// <summary>

/// Get Metadata service

/// </summary>

/// <returns>MetaDataService</returns>

private MetaDataSdk.MetadataService  GetMetaDataService()
{
CrmPractice.MetaDataSdk.CrmAuthenticationToken token = new CrmPractice.MetaDataSdk.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = “CMDev”;
MetaDataSdk.MetadataService  service = new MetaDataSdk.MetadataService();
service.Url = http://<CrmServer>/mscrmservices/2007/metadataservice.asmx;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.CrmAuthenticationTokenValue = token;
return service;
}

/// <summary>

/// Get TeamId to share the record

/// </summary>

/// <returns>Team Id</returns>

private string GetTeamId(CrmService service)
{
// Query express to find out team id to share the rescord
QueryByAttribute query = new QueryByAttribute ();
query.EntityName =EntityName.team.ToString();

ColumnSet cols = new ColumnSet ();
cols.Attributes=new string[]{“teamid”};

query.ColumnSet = cols;query.Attributes =new string[] { “name”};
query.Values =new string[] { “CRM Team” };

BusinessEntityCollection retrieved = (BusinessEntityCollection)service.RetrieveMultiple(query);
if(retrieved.BusinessEntities.Length> 0 )
{
team newTeam = (team )retrieved.BusinessEntities[0];
CrmPractice.CrmSdk.Key teamGuid = (CrmPractice.CrmSdk.Key )newTeam.teamid;
teamId = teamGuid.Value.ToString();
}
return teamId;
}

private void ShareWithTeam(CrmService service,string recordId,string teamId)
{
// Create the SecurityPrincipal Object
SecurityPrincipal principal = new SecurityPrincipal();
principal.Type = SecurityPrincipalType.Team;

// PrincipalId is the Guid of the user to whom access is being granted
principal.PrincipalId = new Guid(teamId);

// Create the PrincipalAccess Object
PrincipalAccess principalAccess = new PrincipalAccess();

// Set the PrincipalAccess Object’s Properties
principalAccess.Principal = principal;

// Gives the principal access to read
principalAccess.AccessMask = AccessRights.ReadAccess;

// Create the Target Object for the Request
TargetOwnedContact  target = new TargetOwnedContact();

// EntityId is the Guid of the contact access is being granted to
target.EntityId = new Guid(recordId);

// Create the Request Object
GrantAccessRequest grant = new GrantAccessRequest();

// Set the Request Object’s properties
grant.PrincipalAccess = principalAccess;
grant.Target = target;

// Execute the Request
GrantAccessResponse granted = (GrantAccessResponse)service.Execute(grant);
}
private voidClearField()
{
txtFirstName.Text=””;
txtLastName.Text=””;
txtMobileNo.Text=””;
txtEmailId.Text=””;
}
}
} 

Hope its help you 🙂

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 172.23.201.162:80

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 172.23.201.162:80

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 172.23.201.194:80]
   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.

USE MSCRM_CONFIG

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 🙂

%d bloggers like this: