I need the current appointment. If no current appointment then the next or even previous appointment.
I figure to use Restrict
to limit the set of appointments, and then choose either the first or last appointment depending on the restrict argument (e.g. Restrict to appointments ending after current time, or appointments starting before current time).
I'm having trouble with the string filter needed as argument.
A simple VB example (code stump):
myStart = Format(Date, "mm/dd/yyyy hh:mm AMPM")
strRestriction = "[Start] <= '" & myStart & "'"
'Restrict the Items collection
Set oResItems = oItems.Restrict(strRestriction)
'Sort
oResItems.Sort "[Start]"
I am attempting to do the same in C#.
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Get the NameSpace and Logon information.
// Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("mapi");
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
//Log on by using a dialog box to choose the profile.
oNS.Logon(Missing.Value, Missing.Value, true, true);
// Get the Calendar folder.
Outlook.MAPIFolder oCalendar = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
// Get the Items (Appointments) collection from the Calendar folder.
oItems = oCalendar.Items;
oItems.IncludeRecurrences = true;
// THIS IS THE PROBLEM AREA
String filter = "[Start] <= '" + DateTime.Now.ToString("MM/dd/yyyy hh:mm AMPM") + "'";
Outlook.Items restrictedItems = oItems.Restrict(filter);
// Take the last item on the list - should be current or next appointment
restrictedItems.Sort("[Start]");
Outlook.AppointmentItem oAppt = restrictedItems.GetLast();
// Done. Log off.
oNS.Logoff();
I imagine since the filter is a string, the date format needs to be yyyy/mm/dd HH:mm:ss? I can't find any documentation on how to manipulate the [Start], like parsing it to a date or something.
Depending on the date format, I will either get the wrong appointment, or will be unable to use GetLast due to the filter excluding all appointments.
I've seen examples, but either they loop through the appointments (too inefficient), or the date formats look like they can't be trusted to return the correct appointment (For example https://social.msdn.microsoft.com/Forums/vstudio/en-US/c6a8bd21-6534-43be-b23e-1068651da92e/retrieve-appointment-items-from-outlook-2007-calendar-restrict?forum=vsto, which seems to have the date hardcoded instead if using DateTime.Now
.)
UPDATE: I'm currently looping through like shown below. Any suggestions for more efficient code?
DateTime currentTime = DateTime.Now;
foreach (Outlook.AppointmentItem item in oItems)
{
if (item.Start <= currentTime && item.End.Subtract(new TimeSpan(0, 10, 0)) > currentTime)
{
appointmentArrayList.Add(item);
}
}
By following the information found here, I was able to get it to work using "yyyy-MM-dd HH:mm" as the format string for the toString call.
Hope this helps.