Tuesday, February 7, 2012

code that can retrieve total number of your desired entity



 code that can retrieve total number of your desired entity and return this as int
///

/// Gets the supplied entity count from CRM 2011.
///

/// "Service">The CRM 2011 service.
/// "EntityName">Name of the entity we need get count of.
/// "ServicePageSize">Size of the page (optional).
///
private int GetEntityCount(IOrganizationService Service, string EntityName, int ServicePageSize = 5000)
{
RetrieveMultipleResponse retrieved;
int PageNumber = 1;
string PagingCookie = string.Empty;
int PageSize = ServicePageSize;

do {
QueryExpression query = new QueryExpression() {
EntityName = EntityName,
//ColumnSet = new ColumnSet(Columns),
PageInfo = new PagingInfo() {
PageNumber = 1,
Count = PageSize
}
};

if (PageNumber != 1) {
query.PageInfo.PageNumber = PageNumber;
query.PageInfo.PagingCookie = PagingCookie;
}

RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieved = (RetrieveMultipleResponse)Service.Execute(retrieve);

if (retrieved.EntityCollection.MoreRecords) {
PageNumber++;
PagingCookie = retrieved.EntityCollection.PagingCookie;
}
} while (retrieved.EntityCollection.MoreRecords);

return ((PageNumber - 1) * PageSize) + retrieved.EntityCollection.Entities.Count;
}