/// <summary>
 /// Manages the connection for multiple <see cref="StreamingSubscription"/> items. Attention: Use only for subscriptions on the same CAS.
 /// </summary>
 /// <param name="exchangeService">The ExchangeService instance this collection uses to connect to the server.</param>
 public StreamingSubscriptionCollection(ExchangeService exchangeService, Action<SubscriptionNotificationEventCollection> EventProcessor, GroupIdentifier groupIdentifier)
 {
     this._exchangeService = exchangeService;
     this._EventProcessor = EventProcessor;
     this._groupIdentifier = groupIdentifier;
     _connection = CreateConnection();
 }
        public void EndListening()
        {
            Console.WriteLine("Stopping listening for new emails");
            _continueListening = false;

            //dispose all items.
            if (_connection != null && _connection.IsOpen)
            {
                _connection.Close();
            }

            if (_connection != null)
            {
                _connection.Dispose();
                _connection = null;
            }

            Console.WriteLine("Connection closed");
        }
        public override void OnMessage(string value)
        {
            try
            {
                // クライアントからメッセージが来た場合
                JsonObject jsonValue = (JsonObject)JsonValue.Parse(value);
                this.EmailAddress = (string)((JsonPrimitive)jsonValue["address"]).Value;
                this.Password = (string)((JsonPrimitive)jsonValue["password"]).Value;

                // Exchange Online に接続 (今回はデモなので、Address は決めうち !)
                ExchangeVersion ver = new ExchangeVersion();
                ver = ExchangeVersion.Exchange2010_SP1;
                sv = new ExchangeService(ver, TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"));
                //sv.TraceEnabled = true; // デバッグ用
                sv.Credentials = new System.Net.NetworkCredential(
                    this.EmailAddress, this.Password);
                sv.EnableScpLookup = false;
                sv.AutodiscoverUrl(this.EmailAddress, AutodiscoverCallback);

                // Streaming Notification の開始 (今回はデモなので、15 分で終わり !)
                StreamingSubscription sub = sv.SubscribeToStreamingNotifications(
                    new FolderId[] { new FolderId(WellKnownFolderName.Calendar) }, EventType.Created, EventType.Modified, EventType.Deleted);
                subcon = new StreamingSubscriptionConnection(sv, 15); // only 15 minutes !
                subcon.AddSubscription(sub);
                subcon.OnNotificationEvent += new StreamingSubscriptionConnection.NotificationEventDelegate(subcon_OnNotificationEvent);
                subcon.Open();

                // 準備完了の送信 !
                JsonObject jsonObj = new JsonObject(
                    new KeyValuePair<string, JsonValue>("MessageType", "Ready"),
                    new KeyValuePair<string, JsonValue>("ServerUrl", sv.Url.ToString()));
                this.SendMessage(jsonObj.ToString());
            }
            catch (Exception ex)
            {
                this.SendInternalError(ex);
            }

            base.OnMessage(value);
        }
        private StreamingSubscriptionConnection CreateConnection()
        {
            var con = new StreamingSubscriptionConnection(this._exchangeService, 30);
            con.OnSubscriptionError += OnSubscriptionError;
            con.OnDisconnect += OnDisconnect;

            con.OnNotificationEvent += OnNotificationEvent;

            return con;
        }
        private void ConnectToEws()
        {
            if (_service == null)
            {
                Console.WriteLine("Creating EWS Service");
                _service = new ExchangeService();
                _service.Credentials = new NetworkCredential(_settings.UserEmailAddress, _settings.Password);
                if (!string.IsNullOrWhiteSpace(_settings.SharedEmailAddress))
                {
                    _service.HttpHeaders.Add("X-AnchorMailbox", _settings.SharedEmailAddress);
                }

                // Look up the user's EWS endpoint by using Autodiscover.
                _service.AutodiscoverUrl(_settings.UserEmailAddress, RedirectionCallback);

                Console.WriteLine("EWS Endpoint: {0}", _service.Url);
            }

            Console.WriteLine("attempting to open connection to {0}", _settings.UserEmailAddress);

            // Subscribe to streaming notifications in the Inbox.
            StreamingSubscription streamingSubscription =
                _service.SubscribeToStreamingNotifications(string.IsNullOrWhiteSpace(_settings.SharedEmailAddress)
                ? new FolderId[] { WellKnownFolderName.Inbox }
                : new[] { new FolderId(WellKnownFolderName.Inbox, new Mailbox(_settings.SharedEmailAddress)) }, EventType.NewMail);

            // Create a streaming connection to the service object, over which events are returned to the client.
            // Keep the streaming connection open for 30 minutes.
            _connection = new StreamingSubscriptionConnection(_service, 30);
            _connection.AddSubscription(streamingSubscription);
            _connection.OnNotificationEvent += OnNotificationEvent;
            _connection.OnDisconnect += OnDisconnect;
            _connection.Open();

            Console.WriteLine("Connected to {0}", _settings.UserEmailAddress);
            Console.WriteLine("Listening for new emails");
        }
示例#6
0
        static void SetStreamingNotifications(ExchangeService service,IUserData ud)
        {
            // Subscribe to streaming notifications on the Inbox folder, and listen
            // for "NewMail", "Created", and "Deleted" events.
            try
            {
                StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications(
                    new FolderId[] { WellKnownFolderName.Inbox },
                    EventType.NewMail,
                    EventType.Created,
                    EventType.Deleted);

                StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 1);

                connection.AddSubscription(streamingsubscription);
                // Delegate event handlers.
                connection.OnNotificationEvent +=
                    new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent);
                connection.OnSubscriptionError +=
                    new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError);
                connection.OnDisconnect +=
                    new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect);
                connection.Open();

                Log(string.Format("Zasubskrybowano konto: {0}", ud.EmailAddress));

            }
            catch (Exception e)
            {
                Log("Błąd w trakcie próby podłączenia subskrypcji." + e.InnerException.ToString());

            }
        }
 private void UpdateConnection()
 {
     try
     {
         lock (_connectionLock)
         {
             if (null != _connection)
             {
                 if (_connection.IsOpen)
                 {
                     _connection.Close();
                 }
             }
             _connection = StartNewConnection();
         }
     }
     catch (Exception ex)
     {
         log.WarnFormat("Error setting up connection: {0}", ex);
         _startConnectionTimer.Start(); // retry
     }
 }
            private StreamingSubscriptionConnection StartNewConnection()
            {
                var svc = _exchangeServiceBuilder();
                var useImpersonation = bool.Parse(ConfigurationManager.AppSettings["useImpersonation"] ?? "false");
                if (useImpersonation)
                {
                    svc.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, _roomAddress);
                }
                log.DebugFormat("Opening subscription to {0}, impersonation: {1}", _roomAddress, useImpersonation);
                var calId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(_roomAddress));
                var sub = svc.SubscribeToStreamingNotifications(
                    new[] { calId },
                    EventType.Created,
                    EventType.Deleted,
                    EventType.Modified,
                    EventType.Moved,
                    EventType.Copied,
                    EventType.FreeBusyChanged);

                // Create a streaming connection to the service object, over which events are returned to the client.
                // Keep the streaming connection open for 30 minutes.
                var connection = new StreamingSubscriptionConnection(svc, 30);
                connection.AddSubscription(sub);
                connection.OnNotificationEvent += OnNotificationEvent;
                connection.OnDisconnect += OnDisconnect;
                connection.Open();
                _meetingCacheService.ClearUpcomingAppointmentsForRoom(_roomAddress);
                log.DebugFormat("Opened subscription to {0} via {1} with {2}", _roomAddress, svc.GetHashCode(), svc.CookieContainer.GetCookieHeader(svc.Url));
                IsActive = true;
                return connection;
            }