Tuesday, December 02, 2008

CRM 4.0 Get accountid from Customer Name (account name)

I could not find a c# web services example of how to get the accountid from an account given the name of the customer. Here is some c# code that can easily be adapted to search for other entities. In this example CrmService is my connection to the web service.

Use it like this :-

string accountid = GetAccountId("My Company Name");




private string GetAccountID (string customername)
{
string ret = "";

// Query condition
ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "name";
condition.Operator = ConditionOperator.Equal;
condition.Values = new object[1];
condition.Values[0] = customername;

// FilterExpression
FilterExpression filterPrincipal = new FilterExpression();
filterPrincipal.FilterOperator = LogicalOperator.And;
filterPrincipal.Conditions = new ConditionExpression[] { condition };

// Columns to return
ColumnSet columns = new ColumnSet();
columns.Attributes = new string[] { "accountid" };

// Query Contact
QueryExpression Query = new QueryExpression();
Query.EntityName = EntityName.account.ToString();
Query.ColumnSet = columns;
Query.Criteria = filterPrincipal;

// Get entities
BusinessEntityCollection entities = (BusinessEntityCollection) CrmService.RetrieveMultiple (Query);
foreach (BusinessEntity entity in entities.BusinessEntities)
{
account Account = entity as account;
return Account.accountid.Value.ToString();
}
return "";
}

No comments: