ExchangeService FindItems Suddenly Intermittently Not Working - c#

This has been working perfectly for probably a year or more, then suddenly, I think as of Saturday October 12th it started failing (FindResults returns no items);
//Tag the sent email so we can pull it back in a moment
Guid myPropertySetId = new Guid("{375a1079-a049-4c2d-a2e1-983d588cbed4}");
ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId, "TelEmailGuid", MapiPropertyType.String);
Guid telEmailGuid = Guid.NewGuid();
message.SetExtendedProperty(myExtendedPropertyDefinition, telEmailGuid.ToString());
//Send the email
message.SendAndSaveCopy(completedFolder);
//Find the sent email
ItemView view = new ItemView(1);
SearchFilter searchFilter = new SearchFilter.IsEqualTo(myExtendedPropertyDefinition, telEmailGuid.ToString());
view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
FindItemsResults<Item> findResults = service.FindItems(completedFolder, searchFilter, view);
return DownloadEmail(findResults.FirstOrDefault().Id.ToString());
I tried tweaking things a little to wait before trying to find the e-mail, this has helped (now maybe 10% succeed). So, I then added a loop, so if not found it will try again a few times. But it seems that if it isn't found the first time, it is not found on subsequent attempts;
//Tag the sent email so we can pull it back in a moment
Guid myPropertySetId = new Guid("{375a1079-a049-4c2d-a2e1-983d588cbed4}");
ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId, "TelEmailGuid", MapiPropertyType.String);
Guid telEmailGuid = Guid.NewGuid();
message.SetExtendedProperty(myExtendedPropertyDefinition, telEmailGuid.ToString());
//Send the email
message.SendAndSaveCopy(completedFolder);
//Find the sent email
ItemView view = new ItemView(1);
SearchFilter searchFilter = new SearchFilter.IsEqualTo(myExtendedPropertyDefinition, telEmailGuid.ToString());
view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
int attempt = 1;
System.Threading.Thread.Sleep(1000);
FindItemsResults<Item> findResults = service.FindItems(completedFolder, searchFilter, view);
while (findResults.TotalCount == 0 && attempt < 5)
{
findResults = service.FindItems(completedFolder, searchFilter, view);
attempt++;
}
return DownloadEmail(findResults.FirstOrDefault().Id.ToString());
Does anyone have any suggestions? I suspect it is a Microsoft issue but perhaps a different approach might allow us to workaround the issue.

It sounds like its an issue with the Search timing out because your not searching an indexed property as the FolderItem Count grow the performance of the search will decline over time (also other factors like server load etc will have a direct effect when searching for item in a Folder with a large item count).
Your search looks pretty static so you could create a Search Folder https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/dd633690(v%3Dexchg.80) which would optimize the search.
The other thing you maybe be able to do is add a DateTime restriction for the search eg I have code that searches for messages based on the Internet MessageId and it has a similar problem when Item counts get large the search times out. So because I know what I'm searching for are always recent email adding a Date Time restriction fixed the issue in this instance eg
SearchFilter internetMessageIdFilter = new SearchFilter.IsEqualTo(PidTagInternetMessageId, InternetMessageId);
SearchFilter DateTimeFilter = new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, DateTime.Now.AddDays(-1));
SearchFilter.SearchFilterCollection searchFilterCollection= new SearchFilter.SearchFilterCollection(LogicalOperator.And);
searchFilterCollection.Add(internetMessageIdFilter);
searchFilterCollection.Add(DateTimeFilter);

Related

Setting ExtendedProperties related to a Room

I am very new to EWS and Exchange in general, so not really sure what is the best approach.
Background
I am trying to set configuration information about a room. I was hoping that the EWS API provided me with a Room object that I can add ExtendedProperties on, however, it appears that rooms are just an email address.
I then saw that each room had a CalendarFolder associated with it, so I am now trying to set the room configuration in the CalendarFolder, which is what the original question below refers to.
Original Question
I am trying to do a simple update of a CalendarFolder using:
var folderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(roomEmail.Address));
var myCalendar = CalendarFolder.Bind(service, folderId, PropertySet.FirstClassProperties);
myCalendar.DisplayName += "Updated";
myCalendar.Update();
However, when I call .Update() I get "The folder save operation failed due to invalid property values."
I believe that the problem might have something to do with myCalendar not having all of the properties that the calendar folder has on the server. So when I update the object it is only sending a partial object which is causing validation errors.
How would I go about updating a CalendarFolder?
After further research
I also stumbled across the following, which does work:
FindFoldersResults root = service.FindFolders(WellKnownFolderName.Calendar, new FolderView(500));
foreach (var folder in root.Folders)
{
folder.DisplayName = "confRoom1";
folder.Update();
}
I'm sure there is a difference between the two approaches, but I don't understand the differences between the folder that I get using the different query methods:
new FolderId(WellKnownFolderName.Calendar, new Mailbox(roomEmail.Address));
var myCalendar = CalendarFolder.Bind(service, folderId, PropertySet.FirstClassProperties);
and
service.FindFolders(WellKnownFolderName.Calendar, new FolderView(500));
Which approach would give me the correct CalendarFolder where I can set the ExtendedProperties for the room?
I'm sure there is a difference between the two approaches, but I don't understand the differences between the folder that I get using the different query methods:
new FolderId(WellKnownFolderName.Calendar, new Mailbox(roomEmail.Address));
var myCalendar = CalendarFolder.Bind(service, folderId, PropertySet.FirstClassProperties);
and
service.FindFolders(WellKnownFolderName.Calendar, new FolderView(500));
The First binds to the default calendar folder in a Mailbox and the second get the subfolders within the Default calendar folder. You can rename the subfolders within the default calendar folder because they are user created. You cannot rename the Default calendar folder in a Mailbox because its a special folder. If you want to set a Extended property (which you can do on a special folder then it easy just define it and set it) eg
ExtendedPropertyDefinition MyCustomProp = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.PublicStrings, "MyCustomProp", MapiPropertyType.String);
CalendarFolder CalendarFolder = CalendarFolder.Bind(service,new FolderId(WellKnownFolderName.Calendar, "user#domain.com"));
CalendarFolder.SetExtendedProperty(MyCustomProp, "My Value");
CalendarFolder.Update();
What you want to get that value you must define a propertySet that tells exchange to return that value when you either Bind or use FindItems (Exchange will not return your property by default) eg
PropertySet MyPropSet = new PropertySet(BasePropertySet.FirstClassProperties);
MyPropSet.Add(MyCustomProp);
CalendarFolder = CalendarFolder.Bind(service, new FolderId(WellKnownFolderName.Calendar, "mailbox#domain.com"),MyPropSet);
Object PropValue = null;
if (CalendarFolder.TryGetProperty(MyCustomProp, out PropValue))
{
Console.WriteLine(PropValue);
}

How to restore deleted appointment

How to restore deleted appointment using EWS 2.0?
I think i could search for it in the WellKnownFolderName.RecoverableItemsDeletions folder. But all i have is ItemId. And sadly I cant use it in SearchFilter...
What is the best way?
my try:
ItemView view = new ItemView(10);
SearchFilter searchFilter = new SearchFilter.IsEqualTo(ItemSchema.Id, itemChange.ItemId);
var findResults = exchangeService.FindItems(WellKnownFolderName.RecoverableItemsDeletions, searchFilter, view);
List<ItemId> ids = null;
foreach (var findResult in findResults)
{
Debug.WriteLine(findResult.Id.ToString());
ids.Add(findResult.Id);
}
exchangeService.MoveItems(ids, WellKnownFolderName.Calendar);
an error occurs:
{"Values of type 'ItemId' can't be used as comparison values in search filters."}
Set your WellKnownFolderName to DeletedItems when you are searching for the appointments. And you should set up your search filter to only return appointments since the DeletedItems folder can hold more than just the appointments you are looking for. Here is an example that should work for you.
ItemView view = new ItemView(10);
// Only look for appointments
SearchFilter searchFilter = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, "IPM.Appointment");
// Look for items in the DeletedItems folder
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.DeletedItems, searchFilter, view);
// Move each of the deleted items back to the calendar
List<ItemId> ItemsToMove = new List<ItemId>();
foreach (Item item in results)
{
ItemsToMove.Add(item.Id);
}
service.MoveItems(ItemsToMove, WellKnownFolderName.Calendar);

using filter to get tasks modified after specific date

Do you have any experiences with SearchFilter of EWS? I'm trying to get tasks with last modified time newer than value of variable date. It works with this code really in weird way, I've also tried to change date to UTC time format. Any advice what I'm doing wrong?
//Create the extended property definition.
ExtendedPropertyDefinition taskLastUpdate = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Task, 0x3008, MapiPropertyType.SystemTime);
//Create the search filter.
SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(taskLastUpdate, date.ToString("s") + "Z");
//Get the tasks.
FindItemsResults<Item> tasks = _service.FindItems(WellKnownFolderName.Tasks, filter, new ItemView(100));
I'm not sure why it didn't work way with ExtendedPropertyDefinition.
Solution:
SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime, date );
SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, greaterthanfilter);
Folder folder = Folder.Bind(_service, WellKnownFolderName.Tasks); //Or the folder you want to search in
FindItemsResults<Item> results = folder.FindItems(filter, new ItemView(1000));

EWS - how do I find all incomplete tasks?

I am using Exchange Web Services to try to get a list of all Outlook tasks which are not complete.
I have an instance of ExchangeService, and attempt to find all incomplete tasks like this:
SearchFilter searchFilter = new SearchFilter.IsNotEqualTo(TaskSchema.Status, TaskStatus.NotStarted);
FindItemsResults<Item> tasks = service.FindItems(WellKnownFolderName.Tasks, searchFilter, view);
However, on the last line, I get a "ServiceResponseException: The specified value is invalid for property." This seems weird to me because the EWS documentation explicitly states that the Task.Status is supposed to be one of the TaskStatus enumeration values. Creating a SearchFilter which compares against a string value does not cause an exception, but I haven't tried any of the other enumeration options to see whether they give the same behavior.
I am able to do this using ExtendedPropertyDefinition with Exchange 2007.
I am using PidLidTaskComplete Canonical Property.
Full list of named properties available here.
//Create the extended property definition.
ExtendedPropertyDefinition taskCompleteProp = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.Task, 0x0000811C, MapiPropertyType.Boolean);
//Create the search filter.
SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(taskCompleteProp, false);
//Get the tasks.
FindItemsResults<Item> tasks = service.FindItems(WellKnownFolderName.Tasks, filter, new ItemView(50));
I believe you may also achieve that without using any magic numbers:
var view = new ItemView(20);
var query = new SearchFilter.IsNotEqualTo(TaskSchema.IsComplete, true);
var results = exchangeService.FindItems(WellKnownFolderName.Tasks, query, view);
This does work on a certain version of exchange :)

Exchange Web Services: Batching with FindItemsResult<Item>

I'm writing an app to process email attachments, using Exchange Web Services.
The general structure of my problem area is as follows:
public static void Main()
{
FindItemsResults<Item> findResults = FindItems();
foreach (Item item in findResults)
{
DoSomethingWithItem(item);
}
}
public static FindItemsResults<Item> FindItems()
{
FindItemsResults<Item> findResults;
ItemView view = new ItemView(10); //batching 10 at a time
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
view.PropertySet = new PropertySet(
BasePropertySet.IdOnly,
ItemSchema.Subject,
ItemSchema.DateTimeReceived);
findResults = service.FindItems(
WellKnownFolderName.Inbox,
new SearchFilter.SearchFilterCollection(
LogicalOperator.Or,
new SearchFilter.ContainsSubstring(ItemSchema.Subject, Properties.Settings.Default.EmailSubject)),
view);
//return set of emails
return findResults;
}
At first, this looked OK - it processed my earlier test examples perfectly well. But when I start testing with bulk loads, I realised that it was only processing the first 10 items, since I was specifying a batch size of 10 items (ItemView view = new ItemView(10)), but I wasn't checking for further batches.
I could have simply increased the batch size, but a quick google later, I found a better example:
public static FindItemsResults<Item> FindItems()
{
FindItemsResults<Item> findResults;
ItemView view = new ItemView(10, 0, OffsetBasePoint.Beginning);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
view.PropertySet = new PropertySet(
BasePropertySet.IdOnly,
ItemSchema.Subject,
ItemSchema.DateTimeReceived);
do
{
findResults = service.FindItems(
WellKnownFolderName.Inbox,
new SearchFilter.SearchFilterCollection(
LogicalOperator.Or,
new SearchFilter.ContainsSubstring(ItemSchema.Subject, Properties.Settings.Default.EmailSubject)),
view);
//any more batches?
if (findResults.NextPageOffset.HasValue)
{
view.Offset = findResults.NextPageOffset.Value;
}
}
while (findResults.MoreAvailable);
return findResults;
}
This loops through as many emails as I care to throw at it, but for reasons I can't yet understand, the foreach loop now only processes the first item in findResults.
Even though findResults contains more than one item (findResults.Items.Count > 1), with my second example, findResults.MoreAvailable = false. Fair enough, I've looped through the batches earlier, so it makes sense that I'm looking at the end of the last batch.
But how do I reset findResults so that it will process the whole lot? I tried setting findResults.MoreAvailable but it is readonly... What am I missing?
CONCLUSION:
OK, so I can either process the items one batch at a time, or I can add each item in each batch to a List and process them later, as I currently do.
There is not a lot between them; I've initially started using a List, but I'll consider the choice further.
It seems to my that your main problem is that you try define a function which returns FindItemsResults<Item>. If you use paring of results you will have not one object of this type. Instead of that on retrieving of every new page the FindItemsResults<Item> will be overwritten. Following example display subjects of all items from the Inbox:
ItemView view = new ItemView(10, 0, OffsetBasePoint.Beginning);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
view.PropertySet = new PropertySet(
BasePropertySet.IdOnly,
ItemSchema.Subject,
ItemSchema.DateTimeReceived);
// save the folder where we will make searching to do this one time
Folder myInbox = Folder.Bind(service, WellKnownFolderName.Inbox);
FindItemsResults<Item> findResults;
do
{
findResults = myInbox.FindItems(
new SearchFilter.ContainsSubstring(ItemSchema.Subject,
Properties.Settings.Default.EmailSubject)),
view);
foreach (Item item in findResults)
{
// Do something with the item.
Console.WriteLine();
if (item is EmailMessage)
{
EmailMessage em = item as EmailMessage;
Console.WriteLine("Subject: \"{0}\"", em.Subject);
}
else if (item is MeetingRequest)
{
MeetingRequest mr = item as MeetingRequest;
Console.WriteLine("Subject: \"{0}\"", mr.Subject);
}
else
{
// we can handle other item types
}
}
//any more batches?
if (findResults.NextPageOffset.HasValue)
{
view.Offset = findResults.NextPageOffset.Value;
}
}
while (findResults.MoreAvailable);
The code display the subjects on the console output. If you want to use EmailMessage or MeetingRequest in another way you should modify the code correspondent. You can also define a delegate which do something with the found EmailMessage or MeetingRequest and call the delegate on the place of Console.WriteLine. If you do need to same all items somewhere, then you will have to create some collection like List<Item>, fill there in the function and return instead of FindItemsResults<Item> which you currently do.

Categories

Resources