I have written a console application to retrieve all the Account records. The below code is a method to achieve that. The main logic in retrieving all the records is by passing the PageInfo object to a QueryExpression.
private static void GetAllActiveAccounts(OrganizationServiceProxy service)
{
EntityCollection retrieved;
const int servicePageSize = 5000;
int pageNumber = 1;
string pagingCookie = string.Empty;
const int pageSize = servicePageSize;
int totalRecordsCount = 0;
do
{
var cols = new ColumnSet();
cols.AddColumns(new string[] { ACCOUNT_ID, ACCOUNT_NAME });
var filter = new FilterExpression { FilterOperator = LogicalOperator.And };
filter.AddCondition(new ConditionExpression(STATE_CODE, ConditionOperator.Equal, new object[] { 0 }));
var query = new QueryExpression
{
ColumnSet = cols,
Criteria = filter,
EntityName = ENTITY_ACCOUNT,
PageInfo = new PagingInfo()
{
PageNumber = 1,
Count = pageSize
}
};
if (pageNumber != 1)
{
query.PageInfo.PageNumber = pageNumber;
query.PageInfo.PagingCookie = pagingCookie;
}
retrieved = service.RetrieveMultiple(query);
if (retrieved.MoreRecords)
{
pageNumber++;
pagingCookie = retrieved.PagingCookie;
}
try
{
if (retrieved.Entities.Count > 0)
{
totalRecordsCount += retrieved.Entities.Count;
foreach (var accountEntity in retrieved.Entities)
{
if (accountEntity.Attributes.Contains(ACCOUNT_ID))
{
var accountId = (Guid)accountEntity.Attributes[ACCOUNT_ID];
var accountName = (string)accountEntity.Attributes[ACCOUNT_NAME];
Console.WriteLine("Account Name: " + accountName);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
} while (retrieved.MoreRecords);
Console.WriteLine("Total records: " + totalRecordsCount);
}