Dharun
Dharun

Reputation: 77

Outlook Addin ItemAdd Event handler

I have an outlook addin developed, which has been used by many users. In our addin we have a functionality which will capture any emails getting stored under any specific outlook folder, to capture that i am using ItemAdd event.

User A and User B has same shared mailboxes.

Currently when user A registers a shared folder for capturing emails from addin, only for USER A the ItemAdd event is getting triggered, User B also using the same shared mailbox from our addin, but for him, the event is not triggered. Is it something expected? Do we have any events which triggers if any mails getting added into the specific folders?

Below is the code sample snippet for how the event are registred:

                    Interop.Folder fldr = this.GetFolder(folder.EntryId);
                    if (fldr != null)
                    {
                        Interop.Items items = fldr.Items;
                        items.ItemAdd += MappedItems_ItemAdd;
                    }

        public Interop.Folder GetFolder(string entryId)
        {

            Interop.Folder retVal = null;
            try
            {

                try
                {
                    retVal = m_outlook.Application.Session.GetFolderFromID(entryId) as Interop.Folder;
                }
                catch { }
            if (retVal != null)
            {
                try
                {
                    string name = retVal.Name;
                }
                catch (Exception)
                {
                    retVal = null;
                }
            }

            return retVal;
        }

Upvotes: 0

Views: 201

Answers (1)

Eugene Astafiev
Eugene Astafiev

Reputation: 49455

The cause of the issue is not related to Outlook, but how the garbage collector works in .net based applications. For example, in the code you declare the source items collection in the limited scope of the if condition:

Interop.Folder fldr = this.GetFolder(folder.EntryId);
if (fldr != null)
{
   Interop.Items items = fldr.Items;
   items.ItemAdd += MappedItems_ItemAdd;
}

So, when code finishes and goes out of the if condition the items object is marked for swiping form the heap. GC may remove the object at any point of time it runs and you will never receive events from it. To avoid such kind of issues you need to declare the source object at the class level, so it will never goes out of cope and GC will not mark it for collecting:

// declare at the class the source object of events
Interop.Items items = null;

// in the code somewhere you may set it up to handle events
if (fldr != null)
{
   items = fldr.Items;
   items.ItemAdd += MappedItems_ItemAdd;
}

Upvotes: 0

Related Questions