I'm trying to get number of unread emails from Exchange for specific user.
I'm able to get number of emails from Inbox like so:
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
ItemView view = new ItemView(int.MaxValue);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
int unreadCount = 0;
foreach (EmailMessage i in findResults)
{
unreadCount++;
}
label1.Text = unreadCount.ToString();
This works great.
I'm also able to get all subfolders is Inbox:
FindFoldersResults findResults1 = service.FindFolders(
WellKnownFolderName.Inbox,
new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep });
foreach (Folder folder in findResults1.Folders)
{
Console.WriteLine(folder.DisplayName);
}
Problem is that I'm not able to combine these two together.
I know that I can do nested foreach loop, but I would like to avoid that.
I found these question: Exchange Web Services (EWS) FindItems within All Folders, but it requires to at least use Outlook 2010 in order to create AllItems
folder.
I know that I can create SearchFilterCollection
, but how to add rules to it so that it will search for unread emails in Inbox and all subfolders?
EDIT:
This what I have tried to do so far:
private int getEmailCount()
{
int unreadCount = 0;
FolderView viewFolders = new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep, PropertySet = new PropertySet(BasePropertySet.IdOnly) };
ItemView viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) };
SearchFilter unreadFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, unreadFilter, viewEmails);
unreadCount += findResults.Count();
FindFoldersResults inboxFolders = service.FindFolders(WellKnownFolderName.Inbox, viewFolders);
foreach (Folder folder in inboxFolders.Folders)
{
findResults = service.FindItems(folder.Id, unreadFilter, viewEmails);
unreadCount += findResults.Count();
}
return unreadCount;
}
Basically this works, but when I have created multiple subfolders it started to work very slow.
Instead of multiple queries can I do one to get same results?