Home > Software engineering >  Filtering appointments not working properly
Filtering appointments not working properly

Time:11-14

In my test C# application using Microsoft.Office.Interop.Outlook. I'm trying to receive only calendar events for the specified date. The filter below equals:

[Start] >= '11/13/2022 00:00:00 AM' AND [END] <= '11/14/2022 11:59:59 PM'

But I'm running into two issues. Sort doesn't seem to work, and the second problem is pulling appointments on future dates and skipping the appointments earlier in the morning.

enter image description here

...
DateTime dtFrom = new DateTime(DateTime.Now.Year, 11, 14);            
DateTime dtTo = new DateTime(DateTime.Now.Year, 11, 14);

Recipient teamMember = _app.Session.CreateRecipient("persons_email_address");
teamMember.Resolve();
if (teamMember.Resolved)
{
    MAPIFolder sharedCalendar = _app.Session.GetSharedDefaultFolder(teamMember, OlDefaultFolders.olFolderCalendar);
    if (sharedCalendar.DefaultMessageClass != "IPM.Appointment" || teamMember.DisplayType != 0)
    {
        return; //Calendar not shared.
    }

    var sdf = dtFrom.ToString("MM/dd/yyy")   " 00:00:00 AM";
    var sdt = dtTo.ToString("MM/dd/yyy")   " 11:59:59 PM";
    string restrictCriteria = $"[Start] >= '{sdf}' AND [END] <= '{sdt}'";

    Items items = sharedCalendar.Items;
    items.Sort("[Start]");
    items.IncludeRecurrences = true;
    var results = items.Restrict(restrictCriteria);
    
    for (int i = 1; i <= results.Count; i  )
    {
        try
        {
            AppointmentItem item = sharedCalendar.Items[i];
            Console.WriteLine("Item: {0}", i.ToString());
            Console.WriteLine("Subject: {0}", item.Subject);
            Console.WriteLine("Start: {0}", item.Start);
            //Console.WriteLine("Start: {0}", item.SenderName);
            Console.WriteLine("End: {0}", item.End);
            Console.WriteLine("Categories: {0}", item.Categories);
        }
        catch (System.Exception err)
        {

        }

    }

CodePudding user response:

You need to change the condition (less than Start and greater than End) and format dates according to Outlook requirements. The following code works like a charm on my machine:

using System.Diagnostics;
using System.Runtime.InteropServices;
// ...
private void RestrictCalendarItems(Outlook.MAPIFolder folder)
{
    DateTime dtEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                                  DateTime.Now.Day, 23, 59, 00, 00);
    string restrictCriteria = "[Start]<=\""   dtEnd.ToString("g")   "\""  
                              " AND [End]>=\""   DateTime.Now.ToString("g")   "\"";
    StringBuilder strBuilder = null;
    Outlook.Items folderItems = null;
    Outlook.Items resultItems = null;
    Outlook._AppointmentItem appItem = null;
    int counter = default(int);
    object item = null;
    try
    {
        strBuilder = new StringBuilder();
        folderItems = folder.Items;
        folderItems.IncludeRecurrences = true;
        folderItems.Sort("[Start]");
        resultItems = folderItems.Restrict(restrictCriteria);
        item = resultItems.GetFirst();
        do
        {
            if (item != null)
            {
                if (item is Outlook._AppointmentItem)
                {
                    counter  ;
                    appItem = item as Outlook._AppointmentItem;
                    strBuilder.AppendLine("#"   counter.ToString()  
                                          "\tStart: "   appItem.Start.ToString()  
                                          "\tSubject: "   appItem.Subject  
                                          "\tLocation: "   appItem.Location);
                }
                Marshal.ReleaseComObject(item);
                item = resultItems.GetNext();
            }
        }
        while (item != null);
        if (strBuilder.Length > 0)
            Debug.WriteLine(strBuilder.ToString());
        else
            Debug.WriteLine("There is no match in the "
                               folder.Name   " folder.");
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    finally
    {
        if (folderItems != null) Marshal.ReleaseComObject(folderItems);
        if (resultItems != null) Marshal.ReleaseComObject(resultItems);
    }
}

You may check out the article which I wrote for the technical blog - How To: Use Restrict method in Outlook to get calendar items.

  • Related