/// <summary> /// Pull notifications specific folders /// </summary> /// <param name="folderId">The email folder id</param> /// <param name="eventTypes">The notification event type</param> /// <returns>The Event Result</returns> public GetEventsResults PullNotifications(IEnumerable <FolderId> folderId, params EventType[] eventTypes) { PullSubscription subscription = _exchangeService.SubscribeToPullNotifications(folderId, lifeTime, null, eventTypes); GetEventsResults events = subscription.GetEvents(); return(events); }
static void SetPullNotifications(ExchangeService service) { // Initiate the subscription object, specifying the folder and events. PullSubscription subscription = service.SubscribeToPullNotifications( new FolderId[] { WellKnownFolderName.Inbox }, 5, null, EventType.NewMail, EventType.Created, EventType.Deleted); // Initiate the GetEvents method for the new subscription. GetEventsResults events = subscription.GetEvents(); // Handle the results of the GetEvents method. foreach (ItemEvent itemEvent in events.ItemEvents) { switch (itemEvent.EventType) { case EventType.NewMail: EmailMessage message = EmailMessage.Bind(service, itemEvent.ItemId); break; case EventType.Created: Item item = Item.Bind(service, itemEvent.ItemId); break; case EventType.Deleted: Console.WriteLine("Item deleted: " + itemEvent.ItemId.UniqueId); break; } } }
/// <summary> /// Pull notifications for all folders /// </summary> /// <param name="eventTypes">The notification event type</param> /// <returns>The Event Result</returns> public GetEventsResults PullNotifications(params EventType[] eventTypes) { PullSubscription subscription = _exchangeService.SubscribeToPullNotificationsOnAllFolders(lifeTime, null, eventTypes); GetEventsResults events = subscription.GetEvents(); return(events); }
static ExchangeService GetBinding(ExchangeService service) { //Subscribe to Inbox newmail/modified events. subscriptionInbox = service.SubscribeToPullNotifications( new FolderId[] { WellKnownFolderName.Inbox }, //Inbox 5, //TimeOut null, EventType.NewMail, EventType.Modified); //NewMail or Modified // Display the service URL. return service; }
/// <summary> /// Call Unsubscribe() and reset the form. /// </summary> private void btnUnsubscribe_Click(object sender, EventArgs e) { this.CurrentSubscription.Unsubscribe(); this.CurrentSubscription = null; // Enable/Disable form controls for no active subscription this.btnUnsubscribe.Enabled = false; this.btnSubscribe.Enabled = true; this.btnGetEvents.Enabled = false; // Reset form elements this.lstEvents.Items.Clear(); this.lblEventsHeader.Text = string.Empty; }
private void btnPullSubscribe_Click(object sender, RoutedEventArgs e) { ExchangeService service = _context.GetService(); _pullSubscription = service.SubscribeToPullNotifications(new FolderId[] { WellKnownFolderName.Inbox }, 10, null, EventType.NewMail); txtSubscriptionActivity.Text += "Pull Subscription Created" + Environment.NewLine; //set up polling _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromSeconds(10); _timer.Tick += timer_Tick; _timer.Start(); btnPullSubscribe.IsEnabled = false; btnPullUnsubscribe.IsEnabled = true; }
/// <summary> /// Creates pull subscriptions for all rooms and waits on timer delay to pull subscriptions /// </summary> /// <param name="mailboxOwner"></param> /// <returns></returns> private async System.Threading.Tasks.Task PullSubscriptionChangesAsync(string mailboxOwner) { _traceListener.Trace("SyncProgram", $"PullSubscriptionChangesAsync({mailboxOwner}) starting"); var service = new EWService(EwsToken); service.SetImpersonation(ConnectingIdType.SmtpAddress, mailboxOwner); if (_subscriptions == null) { _subscriptions = new List <SubscriptionCollection>(); } var EwsService = new EWService(EwsToken); EwsService.SetImpersonation(ConnectingIdType.SmtpAddress, mailboxOwner); // Retreive and Store PullSubscription Details using (var _context = new EWSDbContext(EWSConstants.Config.Database)) { foreach (var room in _context.RoomListRoomEntities.Where(w => !string.IsNullOrEmpty(w.Identity))) { EntitySubscription dbSubscription = null; string watermark = null; if (_context.SubscriptionEntities.Any(rs => rs.SmtpAddress == room.SmtpAddress)) { dbSubscription = _context.SubscriptionEntities.FirstOrDefault(rs => rs.SmtpAddress == room.SmtpAddress); watermark = dbSubscription.Watermark; } else { // newup a subscription to track the watermark dbSubscription = new EntitySubscription() { LastRunTime = DateTime.UtcNow, SmtpAddress = room.SmtpAddress }; _context.SubscriptionEntities.Add(dbSubscription); } try { var roomService = new EWService(EwsToken); var subscription = roomService.CreatePullSubscription(ConnectingIdType.SmtpAddress, room.SmtpAddress, pollingTimeout, watermark); // close out the old subscription dbSubscription.PreviousWatermark = (!string.IsNullOrEmpty(watermark)) ? watermark : null; dbSubscription.Watermark = subscription.Watermark; _traceListener.Trace("SyncProgram", $"ListenToRoomReservationChangesAsync.Subscribed to room {room.SmtpAddress}"); _subscriptions.Add(new SubscriptionCollection() { Pulling = subscription, SmtpAddress = room.SmtpAddress }); var rowChanged = _context.SaveChanges(); _traceListener.Trace("SyncProgram", $"Pull subscription persisted {rowChanged} rows"); } catch (Microsoft.Exchange.WebServices.Data.ServiceRequestException srex) { _traceListener.Trace("SyncProgram", $"Failed to provision subscription {srex.Message}"); throw new Exception($"Subscription could not be created for {room.SmtpAddress} with MSG:{srex.Message}"); } } } try { var waitTimer = new TimeSpan(0, 5, 0); while (!CancellationTokenSource.IsCancellationRequested) { var milliseconds = (int)waitTimer.TotalMilliseconds; using (var _context = new EWSDbContext(EWSConstants.Config.Database)) { foreach (var item in _subscriptions) { bool?ismore = default(bool); do { PullSubscription subscription = item.Pulling; var events = subscription.GetEvents(); var watermark = subscription.Watermark; ismore = subscription.MoreEventsAvailable; var email = item.SmtpAddress; var databaseItem = _context.SubscriptionEntities.FirstOrDefault(rs => rs.SmtpAddress == email); // pull last event from stack TODO: need heuristic for how meetings can be stored var filteredEvents = events.ItemEvents.OrderBy(x => x.TimeStamp); foreach (ItemEvent ev in filteredEvents) { var itemId = ev.ItemId; try { // Send an item event you can bind to await Messenger.SendQueueO365ChangesAsync(queueSubscription, email, ev); } catch (ServiceResponseException ex) { _traceListener.Trace("SyncProgram", $"ServiceException: {ex.Message}"); continue; } } databaseItem.Watermark = watermark; databaseItem.LastRunTime = DateTime.UtcNow; // Save Database changes await _context.SaveChangesAsync(); }while (ismore == true); } } _traceListener.Trace("SyncProgram", $"Sleeping at {DateTime.UtcNow} for {milliseconds} milliseconds..."); System.Threading.Thread.Sleep(milliseconds); } } catch (Exception ex) { Console.WriteLine(ex.Message); } _traceListener.Trace("SyncProgram", $"PullSubscriptionChangesAsync({mailboxOwner}) exiting"); }
public User(string id, string password, string watermark) { Id = id; Service = ExchangeServiceFactory.CreateByNetworkCredential(id, password); Subscription = PullSubscriptionFactory.Create(Service, watermark); }
//pull notifications static void startPullNotification(object param) { ews _ews = (ews)param; //need an instance _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "Pullnotification: started")); int iTimeoutMinutes = 5; // Subscribe to pull notifications in the Inbox folder, and get notified when // a new mail is received, when an item or folder is created, or when an item // or folder is deleted. PullSubscription subscription = null; try { subscription = _ews._service.SubscribeToPullNotifications(new FolderId[] { WellKnownFolderName.Inbox }, iTimeoutMinutes /* timeOut: the subscription will end if the server is not polled within 5 minutes. */, null /* watermark: null to start a new subscription. */, EventType.NewMail);//, EventType.Created, EventType.Deleted); } catch (Exception ex) { _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "Pullnotification: PullSubscription FAILED: " + ex.Message)); } if (subscription == null) { _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "Pullnotification: END with no subscription")); return; } try { while (_ews._bRunPullThread) { _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "Pull sleeping " + (iTimeoutMinutes - 1).ToString() + " minutes...")); int iCount = 0; do { _ews.OnStateChanged(new StatusEventArgs(StatusType.ews_pulse, "ews lives")); iCount += 5000; Thread.Sleep(5000); //Thread.Sleep((iTimeoutMinutes - 1) * 60000); } while (iCount < 60000);//do not sleep longer than iTimeout or you loose the subscription // Wait a couple minutes, then poll the server for new events. _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "Pull looking for new mails")); GetEventsResults events = subscription.GetEvents(); _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "Pull processing")); //to get plain text body only PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties); itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body // Loop through all item-related events. foreach (ItemEvent itemEvent in events.ItemEvents) { switch (itemEvent.EventType) { case EventType.NewMail: utils.helpers.addLog("PullNotification: " + "EventType.NewMail"); _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "check eMail ...")); // A new mail has been received. Bind to it EmailMessage message = EmailMessage.Bind(_ews._service, itemEvent.ItemId, itempropertyset); bool bDoProcessMail = false; if (message.Subject.Contains(helpers.filterSubject) && (!message.Subject.Contains("[processed]"))) { if (message.HasAttachments) { //check for endings of attachements foreach (Attachment att in message.Attachments) { if (att.Name.EndsWith(helpers.filterAttachement)) { bDoProcessMail = true; continue; } } } if (bDoProcessMail) { _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: processMail")); //create a new IMailMessage from the EmailMessage MailMsg myMailMsg = new MailMsg(message, _ews._userData.sUser); _ews._licenseMail.processMail(myMailMsg); //change subject? // Bind to the existing item, using the ItemId. This method call results in a GetItem call to EWS. Item myItem = Item.Bind(_ews._service, itemEvent.ItemId); myItem.Load(); // Update the Subject of the email. myItem.Subject += "[processed]"; // Save the updated email. This method call results in an UpdateItem call to EWS. myItem.Update(ConflictResolutionMode.AlwaysOverwrite); _ews.OnStateChanged(new StatusEventArgs(StatusType.license_mail, "Pullnotification: email marked")); } else { _ews.OnStateChanged(new StatusEventArgs(StatusType.other_mail, "PullNotification: mail does not match")); } } break; case EventType.Created: // An item was created in the folder. Bind to it. Item item = Item.Bind(_ews._service, itemEvent.ItemId); utils.helpers.addLog("PullNotification: " + "EventType.Created " + item.ToString()); break; case EventType.Deleted: // An item has been deleted. Output its ID to the console. utils.helpers.addLog("Item deleted: " + itemEvent.ItemId.UniqueId); break; default: utils.helpers.addLog("PullNotification: " + itemEvent.EventType.ToString()); break; } } // Loop through all folder-related events. foreach (FolderEvent folderEvent in events.FolderEvents) { switch (folderEvent.EventType) { case EventType.Created: // An folder was created. Bind to it. Folder folder = Folder.Bind(_ews._service, folderEvent.FolderId); break; case EventType.Deleted: // A folder has been deleted. Output its Id to the console. utils.helpers.addLog("PullNotification: " + folderEvent.FolderId.UniqueId); break; default: utils.helpers.addLog("PullNotification: " + folderEvent.EventType.ToString()); break; } } /* * // As an alternative, you can also loop through all the events. * foreach (NotificationEvent notificationEvent in events.AllEvents) * { * if (notificationEvent is ItemEvent) * { * ItemEvent itemEvent = notificationEvent as ItemEvent; * * switch (itemEvent.EventType) * { * ... * } * } * else * { * FolderEvent folderEvent = notificationEvent as FolderEvent; * * switch (folderEvent.EventType) * { * ... * } * } * } */ }//end while } catch (ThreadAbortException) { _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: ThreadAbortException")); _ews._bRunPullThread = false; } catch (Exception ex) { _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: Pull Thread Exception:" + ex.Message)); _ews._bRunPullThread = false; } try { subscription.Unsubscribe(); } catch (Exception ex) { utils.helpers.addExceptionLog("subscriptions unsubscribe exception"); _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: subscriptions unsubscribe exception " + ex.Message)); } subscription = null; _ews.OnStateChanged(new StatusEventArgs(StatusType.ews_stopped, "ews pull ended")); _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "PullNotification: Pull ended")); }
public EWSMailFolder(Folder folder) { _folder = folder; subscription = _folder.Service.SubscribeToPullNotifications(new FolderId[] { folder.Id }, 30, null, EventType.NewMail); }
/// <summary> /// Gather form input and create PullSubscription /// </summary> private void btnSubscribe_Click(object sender, EventArgs e) { //const int DEFAULT_NOTIFICATION_TIMEOUT = 5; // Convert the check box settings into an array of EventTypes List <EventType> eventTypes = new List <EventType>(); if (this.chkCopiedEvent.Checked) { eventTypes.Add(EventType.Copied); } if (this.chkCreatedEvent.Checked) { eventTypes.Add(EventType.Created); } if (this.chkDeletedEvent.Checked) { eventTypes.Add(EventType.Deleted); } if (this.chkModifiedEvent.Checked) { eventTypes.Add(EventType.Modified); } if (this.chkMovedEvent.Checked) { eventTypes.Add(EventType.Moved); } if (this.chkNewMailEvent.Checked) { eventTypes.Add(EventType.NewMail); } int TimeOutMinutes = Convert.ToInt32(numMinutes.Value); if (chkAllFoldes.Checked == false) { // Create the subscription based on the form settings this.CurrentSubscription = this.CurrentService.SubscribeToPullNotifications( new FolderId[] { this.CurrentFolderId }, TimeOutMinutes, string.Empty, eventTypes.ToArray()); } else { // Create the subscription based on the form settings this.CurrentSubscription = this.CurrentService.SubscribeToPullNotificationsOnAllFolders( TimeOutMinutes, string.Empty, eventTypes.ToArray()); } // Enable/Disable form controls for an active subscription this.btnUnsubscribe.Enabled = true; this.btnSubscribe.Enabled = false; this.btnGetEvents.Enabled = true; }