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;
}
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;
}
Related
Win 10 - VS 2019 - Office365 - Exchange Online
My first post - woo hoo!!! (Although I have been lurking forever.)
I am writing my first Outlook Add-in with my first experience with C#. I have been hacking on computers since the 1980s and have had experience with about 10 different languages but am very new to this C# and .NET environment.
What I have will build without complaint and works as intended - most of the time.
namespace RoomReservations
{
public partial class ThisAddIn
{
private Outlook.Inspectors inspectors = null;
private Outlook.UserProperty objUserPropertyEventId = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
inspectors = this.Application.Inspectors;
inspectors.NewInspector += new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
// Note: Outlook no longer raises this event. If you have code that
// must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
}
void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
{
#pragma warning disable IDE0019 // Use pattern matching
Outlook.AppointmentItem appt = Inspector.CurrentItem as Outlook.AppointmentItem;
#pragma warning restore IDE0019 // Use pattern matching
// is it an AppointmentItem
if (appt != null)
{
// is it a meeting request
if (appt.MeetingStatus == Outlook.OlMeetingStatus.olMeeting)
{
appt.Save();
// save EventId as UserProperty
Outlook.AppointmentItem mtg = null;
mtg = (Outlook.AppointmentItem)Inspector.CurrentItem;
mtg.MeetingStatus = Outlook.OlMeetingStatus.olMeeting;
if (mtg != null)
{
if (mtg is Outlook.AppointmentItem)
{
string strEntryId = mtg.EntryID;
Outlook.UserProperties objUserProperties = mtg.UserProperties;
objUserPropertyEventId = objUserProperties.Add("MeetingEntryId", Outlook.OlUserPropertyType.olText, true, 1);
objUserPropertyEventId.Value = strEntryId;
}
}
if (mtg != null)
Marshal.ReleaseComObject(mtg);
}
if (appt != null)
Marshal.ReleaseComObject(appt);
}
// define event handler for ItemSend
Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
}
public void Application_ItemSend(object Item, ref bool Cancel)
{
// use EventId to identify current meeting request
var app = new Microsoft.Office.Interop.Outlook.Application();
var ns = app.Session;
Outlook.AppointmentItem meeting = ns.GetItemFromID(objUserPropertyEventId.Value);
// is ItemSend a request or a cancel
if (meeting.MeetingStatus != Outlook.OlMeetingStatus.olMeetingCanceled)
{
// ItemSend is a request
MessageBox.Show("Not Cancelled.");
if (meeting is Outlook.AppointmentItem)
{
if (meeting.MeetingStatus == Outlook.OlMeetingStatus.olMeeting)
{
// if a location was provided
if (meeting.Location != null)
{
Cancel = true;
bool blnTorF = false;
Outlook.Recipient recipConf;
// has the user included "JHP - Room Reservations" for placement
// on the shared calendar for all conference room availability
foreach (Outlook.Recipient objUser in meeting.Recipients)
{
if (objUser.Name == "JHP - Room Reservations")
blnTorF = true;
}
// add "JHP - Room Reservations" if not already included
if (blnTorF == false)
{
recipConf = meeting.Recipients.Add("JHP - Room Reservations");
recipConf.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
if (recipConf != null)
Marshal.ReleaseComObject(recipConf);
}
// add reservarion to specific conference room calendar
String strLocation = meeting.Location;
Outlook.Recipient recipRoomUser;
if (strLocation.Contains("142"))
{
recipRoomUser = meeting.Recipients.Add("conference142#jhparch.com");
recipRoomUser.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
}
if (strLocation.Contains("150"))
{
recipRoomUser = meeting.Recipients.Add("conference150#jhparch.com");
recipRoomUser.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
}
if (strLocation.Contains("242"))
{
recipRoomUser = meeting.Recipients.Add("conference242#jhparch.com");
recipRoomUser.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
}
if (strLocation.Contains("248"))
{
recipRoomUser = meeting.Recipients.Add("conference248#jhparch.com");
recipRoomUser.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
}
// send request
meeting.Recipients.ResolveAll();
meeting.Send();
}
}
}
}
else
{
// ItemSend is a cancel
MessageBox.Show("Meeting is cancelled.");
}
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
When working correctly, a meeting request will put 4 separate entries on 4 separate calendars. A meeting cancel will remove 4 separate entries from 4 separate calendars. The erratic behavior that occurs for a request includes placing the meeting event on only 2 calendars. Unusual behavior that occurs for a cancel includes deleting the meeting event from only 2 calendars. Or the meeting cancel has to be sent out 3 or 4 times before the meeting event is removed from all calendars. But then, I send another meeting request without changing any code and it is placed on all 4 calendars, as expected. And a cancel of that request will remove it from all 4 calendars on the first try. This odd behavior is common within our test group of three users, each running the identical add-in.
I feel like I understand how the native functions [if, foreach, etc.] work. But I don't know what I don't know. I have added some housekeeping [Marshal.ReleaseComObject()]. I'm not sure if it is everywhere it needs to be. I'm not sure if there are other means of housekeeping I am not aware of that could be causing this behavior. I am having a difficult time understanding why this will work, then not work, then work - all without changing any code.
Thanks for any leads that point in the direction of discovery,
Chris
The best way to understand how the code works is to run it under the debugger. Just set some breakpoints and run the solution hitting F5 in Visual Studio. When your breakpoints are hit you can go line-by-line and see intermediate results.
First of all, there is no need to subscribe to the ItemSend event in the NewInspector event handler. That is an Application-wide event, so you need to subscribe only once at startup.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
inspectors = this.Application.Inspectors;
inspectors.NewInspector += new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
// define event handler for ItemSend
Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(Application_ItemSend);
}
Second, the item which is being sent is passed as a parameter to the ItemSend event handler, so you can use it instead of getting a separate one. So, the following code doesn't make sense:
public void Application_ItemSend(object Item, ref bool Cancel)
{
// use EventId to identify current meeting request
var app = new Microsoft.Office.Interop.Outlook.Application();
var ns = app.Session;
Outlook.AppointmentItem meeting = ns.GetItemFromID(objUserPropertyEventId.Value);
Instead, use the parameter:
public void Application_ItemSend(object Item, ref bool Cancel)
{
Outlook.AppointmentItem meeting = Item as Outlook.AppointmentItem;
Third, there is no need to create a new Outlook Application instance in the ItemSend event handler, use the Application property of your add-in class instead
Fourth, if you need to change the outgoing item there is no need to call the Send method in the ItemSend event handler.
meeting.Send();
Use the second parameter if you want to allow or cancel any further processing of that item. For example, if the event procedure sets this argument to true, the send action is not completed and the inspector is left open.
Fifth, I'd recommend using the try/catch blocks to log exceptions and release underlying COM objects in the finally, so you could be sure that everything went well and all objects were released. For example:
private void CreateSendItem(Outlook._Application OutlookApp)
{
Outlook.MailItem mail = null;
Outlook.Recipients mailRecipients = null;
Outlook.Recipient mailRecipient = null;
try
{
mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem)
as Outlook.MailItem;
mail.Subject = "A programatically generated e-mail";
mailRecipients = mail.Recipients;
mailRecipient = mailRecipients.Add("Eugene Astafiev");
mailRecipient.Resolve();
if (mailRecipient.Resolved)
{
mail.Send();
}
else
{
System.Windows.Forms.MessageBox.Show(
"There is no such record in your address book.");
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message,
"An exception is occured in the code of add-in.");
}
finally
{
if (mailRecipient != null) Marshal.ReleaseComObject(mailRecipient);
if (mailRecipients != null) Marshal.ReleaseComObject(mailRecipients);
if (mail != null) Marshal.ReleaseComObject(mail);
}
}
You may find the How To: Create and send an Outlook message programmatically article helpful.
I am developing an outlook plugin in C#.
I want to be able to detect when outlook has finished the "send/receive" option after startup, so that I can then run operations on the received mail items.
What I have tried so far:
Manually calling Application.Session.SendAndReceive() on startup.
This runs fine, but the method returns before the send/receive is complete, which is the opposite of what I want
Overriding Application.NewMail and Application.NewMailEx - neither of these trigger as one might hope at startup (NewMailEx doesn't fire at all, NewMail is unreliable)
Calling NameSpace.SyncObjects.AppFolders.Start(); and registering the SyncObjects.AppFolders.SyncEnd event - this event fires before outlook has finished downloading mail
Iterating through NameSpace.SyncObjects, calling Start(), and registering SyncEnd - this method doesn't fire at all.
What is a solution here which will work depenably?
It seems that there is a hack to detect when syncing has finished; namely to override Application.Reminders.BeforeReminderShow as DWE suggests in this SO answer here
This event (in my testing) always fires after outlook syncing has finished.
Then, in order to make sure the reminder window fires, you add a new reminder at startup, and then hide the reminder again within Reminders_BeforeReminderShow
The code then being something like:
public partial class ThisAddIn
{
private ReminderCollectionEvents_Event reminders; //don't delete, or else the GC will break things
AppointmentItem hiddenReminder;
private void ThisAddIn_Startup(object sender, EventArgs e)
{
//other stuff
hiddenReminder = (AppointmentItem)Application.CreateItem(OlItemType.olAppointmentItem); //add a new silent reminder to trigger Reminders_BeforeReminderShow.This method will be triggered after send/receive is finished
hiddenReminder.Start = DateTime.Now;
hiddenReminder.Subject = "Autogenerated Outlook Plugin Reminder";
hiddenReminder.Save();
reminders = Application.Reminders;
reminders.BeforeReminderShow += Reminders_BeforeReminderShow;
}
private void Reminders_BeforeReminderShow(ref bool Cancel)
{
if (hiddenReminder == null) return;
bool anyVisibleReminders = false;
for (int i = Application.Reminders.Count; i >= 1; i--)
{
if (Application.Reminders[i].Caption == "Autogenerated Outlook Plugin Reminder") //|| Application.Reminders[i].Item == privateReminder
{
Application.Reminders[i].Dismiss();
}
else
{
if (Application.Reminders[i].IsVisible)
{
anyVisibleReminders = true;
}
}
}
Cancel = !anyVisibleReminders;
hiddenReminder?.Delete();
hiddenReminder = null;
//your custom code here
}
}
Yup, this is very kludgy, but that's the nature of working with outlook, and I haven't seen any free alternative which can actually claim to work reliably, whereas this works in all of the use cases I've tried it in. So that's a hit I'm willing to take to get a working solution.
For the case you have more accounts/stores in your Outlook and want that ItemAdd event fires e.g. for all sent items folder.
This is what I have so far but the event is not firing for all sent items folder:
foreach (Outlook.Store store in _outlookNameSpace.Stores)
{
// _SentItems = null;
// _items = null;
try
{
_SentItems = store.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
_items = _SentItems.Items;
_items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd); // BUGBUG: The problem is probably here, as the object needs to be alive which is firing the event?
}
catch
{
AppUtils.DoLog("Skipping this store.");
}
}
These guys are defined as global class variables:
Outlook.NameSpace _outlookNameSpace;
Outlook.MAPIFolder _SentItems;
Outlook.Items _items;
Create a wrapper class that takes Items object as a parameter in its constructor, saves it in a field, and sets up an ItemAdd event handler. You can then initialize a wrapper for each store and store then in a list to ensure the wrappers (and their Items objects) stay alive and can raise events.
I'm currently migrating a VSTO add in written in VB to C# for outlook.
The general idea, is to log every single email information into a database of my own.
I've searched thoroughly and it seems that NewMail / NewMailEX events(from the application object) are the best options to handle it.
However, both events won't trigger for emails received when outlook client is down.
I'm having problems while trying to process all mails that are downloaded on startup from the exchange server, so i thought that "Item-add" event from items collection, might address this issue.
I know for a fact that this can be addressed within "item-add" event because we are actually handling this issue in the VB code.
However, when a try suscribing to the "item-add" event for each Inbox folder in Outlook, nothing happens!
There is no error nor exception thrown whatsoever.
in our VB code,
we could managed to suscribe to the mentioned event with this code:
outlookNameSpace = Me.Application.GetNamespace("MAPI")
inbox = outlookNameSpace.Stores(account).GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
Mailitem = inbox.Items
Private Sub Items_ItemAdd(ByVal item As Object) Handles Mailitem.ItemAdd
Here is my failing C# code:
//looping to fetch all my inboxes
public static void InitialOutlookConfiguration(Outlook.Application myOutlookInstance)
{
Outlook.Accounts myAccounts = myOutlookInstance.GetNamespace("MAPI").Accounts;
foreach(Outlook.Account myAccount in myAccounts)
{
Outlook.MAPIFolder inbox = myAccount.DeliveryStore.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
string storeID = myAccount.DeliveryStore.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).StoreID;
myInboxes.Add(inbox, storeID);
foreach(Outlook.MAPIFolder inbox in myInboxes.Keys)
{
Outlook.Items myInboxItems = inbox.Items;
myInboxItems.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(OnNewItem);
}
}
}
The object raising the events (myInboxItems) must be alive - otherwise it gets released by the Garbage Collector and no events are raised.
The usual pattern is to introduce your own wrapper class that takes the COM object in question (Items) as a constructor parameter, stores it in a class member and sets up an event handler. You can then then create that wrapper class for each Inbox folder and store each wrapper in a list. That list must be declared on the class level to ensure it (and its items) stay alive when InitialOutlookConfiguration() completes.
public List<Outlook.Items> myInboxMailItems = new List<Outlook.Items>();
public Items InboxMails;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
//watch.Start();
//chequear el orden en que solicitamos la ejecucion de la configuracion
//this.Application.Startup += new Outlook.ApplicationEvents_11_StartupEventHandler(OnOutlookOutlookStartup);
Outlook.Accounts myAccounts = this.Application.GetNamespace("MAPI").Accounts;
foreach (Outlook.Account myAccount in myAccounts)
{
Outlook.MAPIFolder inbox = myAccount.DeliveryStore.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
myInboxMailItems.Add(inbox.Items);
foreach (Outlook.Items i in myInboxMailItems)
{
i.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(test);
}
}
}
public void test(object i)
{
System.Windows.Forms.MessageBox.Show("Eureka!");
}
Just in case anybody sticks with the same issue, thanks Dimitry for your garbage collector insight!
I am developing an Outlook AddIn. One part of it that I organize appointments in a specific folder. I want to capture if an element gets deleted (in this case moving out of "my" folder counts as deleted).
I found the article https://stackoverflow.com/questions/10579240/how-to-capture-a-c-sharp-outlook-addin-appointment-delete-event and his/her solution helped a lot, but I have a huge problem: the event only fires in that "session", where my folder was created, not when I get the folder object from outlook.
My code looks like this:
private Outlook.MAPIFolder _CalendarMAPIFolder = null;
private Outlook.MAPIFolderEvents_12_Event _CalendarFolder = null;
private Outlook.Items _CalendarItems = null;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Outlook.MAPIFolder calendarFolder =
this.Application.GetNamespace("mapi").GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
// get my-Folder (if not found, create it)
try
{
_CalendarMAPIFolder = calendarFolder.Folders["my-Folder"];
}
catch
{
_CalendarMAPIFolder = calendarFolder.Folders.Add("my-Folder");
}
_CalendarItems = _CalendarMAPIFolder.Items;
_CalendarFolder = _CalendarMAPIFolder as Outlook.MAPIFolderEvents_12_Event;
if (_CalendarFolder == null)
{
MessageBox.Show("can not cast MAPIFolder to Folder");
}
_CalendarFolder.BeforeItemMove += new Outlook.MAPIFolderEvents_12_BeforeItemMoveEventHandler(Folder_BeforeItemMove);
Debug.Print("events registered");
}
public void Folder_BeforeItemMove(
Object Item,
Outlook.MAPIFolder MoveTo,
ref bool Cancel)
{
Outlook.AppointmentItem aitem = Item as Outlook.AppointmentItem;
string s = "";
if (aitem != null) s = aitem.Subject;
//Cancel = false;
MessageBox.Show("Test! " + s);
}
Does anyone have a solution?
Thank you ;)
Edit: I still have no clue :(((((((
By definition, BeforeItemMove only fires when the user (Outlook client) initiates an Item be moved. It will not fire for synchronization events (i.e. Exchange sync).
If you are connecting Outlook to an Exchange Server, you should look at EWS (Exchange Web Services) if you wish to be notified of folder change events outside the client application (i.e. session). EWS offers push, pull, or streaming notification options. You would attach a notification to "Item deletion" operation.
It was all Microsofts fault! It was a Bug, I just needed to Update Outlook!