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

Posted: February 26, 2012 in Lookup, Microsoft Dynamics CRM
Tags: , , , , , ,

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 🙂

Advertisements
Comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s