CRM4: Useful c#.net snippet to get user or contact by email address

Useful snippet of code that i use all the time, may be helpful to others…

public Guid getUserByEmailAddress(String email, CrmService service)
{
QueryExpression query = new QueryExpression();
query.EntityName = “systemuser”;
ColumnSet columns = new ColumnSet();
columns.Attributes.Add(“systemuserid”);
query.ColumnSet = columns;
query.Criteria = new FilterExpression();
query.Criteria.FilterOperator = LogicalOperator.And;
ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = “internalemailaddress”;
condition1.Operator = ConditionOperator.Equal;
condition1.Values = new object[] { email.Trim()};
query.Criteria.Conditions.Add(condition1);

RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.Query = query;
//retrieve the contacts
RetrieveMultipleResponse response = null;

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

foreach (systemuser cont in response.BusinessEntityCollection.BusinessEntities)
{
 return cont.systemuserid.Value;
}
return new Guid();
}

public Guid getContactByEmailAddress(String email, CrmService service)
{
QueryExpression query = new QueryExpression();
query.EntityName = “contact”;
ColumnSet columns = new ColumnSet();
columns.Attributes.Add(“contactid”);
query.ColumnSet = columns;
query.Criteria = new FilterExpression();
query.Criteria.FilterOperator = LogicalOperator.And; ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = “emailaddress1”;
condition1.Operator = ConditionOperator.Equal; condition1.Values = new object[] { email.Trim() };
query.Criteria.Conditions.Add(condition1);
RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.Query = query;
//retrieve the contacts
RetrieveMultipleResponse response = null;
response = (RetrieveMultipleResponse)service.Execute(request);
foreach (contact cont in response.BusinessEntityCollection.BusinessEntities)
{
return cont.contactid.Value;
}
}

Enjoy

Jonathan

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.