Monday, May 28, 2012

EWS Managed API and Powershell How-To Series Part 9 EWS Notifications

In this installment of the how-to series I'm going to cover EWS notifications which are a mechanism you can use to find out when changes occur in an Exchange Folder. One critical point when thinking about notifications is you need to think of them as notifications and not the programmatic equivalent of events which event sinks where (kind of). Exchange is a mail system that caters to many clients and applications and from a client sense (not a throttling sense) all of these clients are even. So when your building a notification application that is going to affect a message in some way(eg say your just moving it to another folder) you need to understand that by the time your application has received the notification another application may have taken an action on that message. The other issue you may have is because there can be so many clients involved and different synchronization methods in use is you may get multiple notifications for one item which is an issue you just need to make sure you cater for in your code. A good idea can be to look at combining notification operations with synchronization operations which I'll cover in a another post.

Event Notification Types

Before looking at the Types of notifications its a good idea to look at what type of events you can get notifications for.
  • NewMail - This notification fires when a new email is delivered to the Inbox
  • Modified - This notification fires when in Item is modified
  • Copy - This notification fires when an Item is copied
  • Created - This notification fires when a new Item is created in a folder (useful for monitoring the creation of Contacts,Task or Appointments)
  • Deleted - This notification fires when an Item is deleted (accessing the deleted Item is not trivial through)
  • Moved - This notification fires when an Item is moved.
  • FreeBusyChanged - This notification fires when FreeBusy status changes

Types of Notification's

Pull Notifications 

Pull notifications are client initiated notifications eg the way this would generally work is your client would first register for notifications at 10:00 AM on the Inbox, In the next hour 5 new emails arrive, your client then sends a request to the Exchange Server for new notifications on the Inbox at 11:00 AM and you receive back 5 notifications for the newly received messages. Pull notifications are good if your application isn't time critical and you just want to track changes at a regular interval. Here's an example of creating a pull notification on the Inbox folder for NewMail events and a simple update loop that will check for updates and bind to any updated items from the notification event when you press a key.

  1. $InboxId = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)  
  2. $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1  
  3. $fldArray[0] = $InboxId  
  4. $pullSubscription = $service.SubscribeToPullNotifications($fldArray,60,$null,[Microsoft.Exchange.WebServices.Data.EventType]::NewMail)  
  5. $events = $pullSubscription.GetEvents();  
  6. foreach ($notificationEvent in $events.AllEvents)  
  7. {    
  8.     switch ($notificationEvent.EventType)  
  9.       {  
  10.         "NewMail" {"New Mail"  
  11.                     $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  12.                     "Subject : " + $item.Subject  
  13.         }  
  14.       }  
  15. }  
  16. do{  
  17.     $response = read-host "Press key to check next events or Q to exits"  
  18.     $events = $pullSubscription.GetEvents();  
  19.     foreach ($notificationEvent in $events.AllEvents)  
  20.     {  
  21.         switch ($notificationEvent.EventType)  
  22.           {  
  23.             "NewMail" {"New Mail" 
  24.                     $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  25.                     "Subject : " + $item.Subject  
  26.                      }  
  28.           }  
  29.     }  
  30. }while($response -ne "Q")  
Subscribing to Notification events on all folders

In Exchange 2010 you can also subscribe to notifications on all folders in the EWS Managed API for pull notifications this is exposed as SubscribeToPullNotificationsOnAllFolders. The following is a sample of creating pull notifications on all folders in a mailbox this looks at the Modification events on Items.

  1. $pullSubscription = $service.SubscribeToPullNotificationsOnAllFolders(60,$null,[Microsoft.Exchange.WebServices.Data.EventType]::Modified)  
  2. $events = $pullSubscription.GetEvents();  
  3. foreach ($notificationEvent in $events.AllEvents)  
  4. {    
  5.     switch ($notificationEvent.EventType)  
  6.       {  
  7.             "Modified" {"Modified"  
  8.                     if($notificationEvent.ItemId -ne $null){  
  9.                         $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  10.                         "Subject : " + $item.Subject  
  11.                          }                     
  12.                         }  
  13.       }  
  14. }  
  15. do{  
  16.     $response = read-host "Press key to check next events or Q to exits"  
  17.     $events = $pullSubscription.GetEvents();  
  18.     foreach ($notificationEvent in $events.AllEvents)  
  19.     { 
  20.           {  
  21.             "Modified" {  
  22.                     if($notificationEvent.ItemId -ne $null){  
  23.                         $item = [Microsoft.Exchange.WebServices.Data.Item]::Bind($service,$notificationEvent.ItemId)  
  24.                         "Subject : " + $item.Subject  
  25.                          }  
  26.                      }  
  28.           }  
  29.     }  
  30. }while($response -ne "Q")  
Push Notifications

Push notifications are server initiated Notifications eg the way these work is at 10:00 AM you register for Push notifications on the Inbox for your client application with IP address The next time an email arrives in the Inbox the Exchange server will then send a notification to your application. Push notifications are complex beasts in that you need to have a fairly complex application that listens for notifications and maintains the subscription. You also need to make sure you have a dedicated port and clear communication channels through firewalls etc. For this reason Push notifications aren't really practical to use with simple scripted type applications however the third type of notification Streaming Notification allow you to get all the benefits of Push notifications without the communication complexities.

Streaming Notifications

Streaming notifications work similar to push email in ActiveSync eg Your steaming notification application would register for streaming notifications at 10:00AM on the Inbox. The TCP connection used for the registration will then stay open and the Exchange Server will push notifications back to your application via this connection as new emails arrive in the Inbox. Which means you get push notifications without needing a dedicated listener application or the need to worry about firewalls etc. The only catch with streaming notification is that they have a maximum duration of 30 minutes so in the example I've been talking about at 10:30AM you would need to recreate the streaming notification subscription. The good thing is that there are events that are triggered by the Managed API's StreamingSubscriptionConnection class they we can hook in Powershell so we can have a self renewing subscription process. In Powershell the Register-ObjectEvent cmdlet allows you to subscribe to the events that are generated by the Microsoft .NET Framework. To use Streaming notifications in Powershell you need to register for events that are generated by the StreamingSubscriptionConnection class. An example of a Streaming Notification script that will listen for the NewMail Event on the Inbox looks like

  1. $fldArray = new-object Microsoft.Exchange.WebServices.Data.FolderId[] 1  
  2. $Inboxid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)  
  3. $fldArray[0] = $Inboxid  
  4. $stmsubscription = $service.SubscribeToStreamingNotifications($fldArray, [Microsoft.Exchange.WebServices.Data.EventType]::NewMail)  
  5. $stmConnection = new-object Microsoft.Exchange.WebServices.Data.StreamingSubscriptionConnection($service, 30);  
  6. $stmConnection.AddSubscription($stmsubscription)  
  7. Register-ObjectEvent -inputObject $stmConnection -eventName "OnNotificationEvent" -Action {  
  8.     foreach($notEvent in $event.SourceEventArgs.Events){      
  9.         [String]$itmId = $notEvent.ItemId.UniqueId.ToString()  
  10.         $message = [Microsoft.Exchange.WebServices.Data.EmailMessage]::Bind($event.MessageData,$itmId)  
  11.         "Subject : " + $message.Subject + " " + (Get-Date) | Out-File c:\temp\log2.txt -Append   
  12.     }   
  13. } -MessageData $service  
  14. Register-ObjectEvent -inputObject $stmConnection -eventName "OnDisconnect" -Action {$event.MessageData.Open()} -MessageData $stmConnection  
  15. $stmConnection.Open()  
To register for Streaming notifications on all folders you can use SubscribeToStreamingNotificationsOnAllFolders


Andrew McInnes said...

Hi Glen,

Great artical, I wonder if you have used this in any asp web applications and even more interestingly if you have hooked it up to a SignalR hub?

I am hoping to do this and use Telerik Notifications to make a real-time web based outlook client.

Any advice would be much appreciated.


Michael said...

Great Article!
What can i do if my application has closed from 10:00 AM until 12:00 AM and i received Messages in this time?
How would i collect These - i suppose the NewMail-Event won't work here anymore.