forked from OfficeDev/ews-managed-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamingSubscriptionConnection.cs
More file actions
522 lines (454 loc) · 19.8 KB
/
StreamingSubscriptionConnection.cs
File metadata and controls
522 lines (454 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
/// <summary>
/// Represents a connection to an ongoing stream of events.
/// </summary>
public sealed class StreamingSubscriptionConnection : IDisposable
{
/// <summary>
/// Mapping of streaming id to subscriptions currently on the connection.
/// </summary>
private Dictionary<string, StreamingSubscription> subscriptions;
/// <summary>
/// connection lifetime, in minutes
/// </summary>
private int connectionTimeout;
/// <summary>
/// ExchangeService instance used to make the EWS call.
/// </summary>
private ExchangeService session;
/// <summary>
/// Value indicating whether the class is disposed.
/// </summary>
private bool isDisposed;
/// <summary>
/// Currently used instance of a GetStreamingEventsRequest connected to EWS.
/// </summary>
private GetStreamingEventsRequest currentHangingRequest;
/// <summary>
/// Whether OnConnectionCompleted has been fired since last connect
/// </summary>
private bool hasFiredConnectionCompleted;
/// <summary>
/// Lock object
/// </summary>
private object lockObject = new object();
/// <summary>
/// Represents a delegate that is invoked when notifications are received from the server
/// </summary>
/// <param name="sender">The StreamingSubscriptionConnection instance that received the events.</param>
/// <param name="args">The event data.</param>
public delegate void NotificationEventDelegate(object sender, NotificationEventArgs args);
/// <summary>
/// Represents a delegate that is invoked when an error occurs within a streaming subscription connection.
/// </summary>
/// <param name="sender">The StreamingSubscriptionConnection instance within which the error occurred.</param>
/// <param name="args">The event data.</param>
public delegate void SubscriptionErrorDelegate(object sender, SubscriptionErrorEventArgs args);
/// <summary>
/// Occurs when notifications are received from the server.
/// </summary>
public event NotificationEventDelegate OnNotificationEvent;
/// <summary>
/// Occurs when a subscription encounters an error.
/// </summary>
public event SubscriptionErrorDelegate OnSubscriptionError;
/// <summary>
/// Occurs on the first response from the server, successfull or not.
/// </summary>
public event EventHandler OnConnectionCompleted;
/// <summary>
/// Occurs when a streaming subscription connection is disconnected from the server.
/// </summary>
public event SubscriptionErrorDelegate OnDisconnect;
/// <summary>
/// Initializes a new instance of the <see cref="StreamingSubscriptionConnection"/> class.
/// </summary>
/// <param name="service">The ExchangeService instance this connection uses to connect to the server.</param>
/// <param name="lifetime">The maximum time, in minutes, the connection will remain open. Lifetime must be between 1 and 30.</param>
public StreamingSubscriptionConnection(
ExchangeService service,
int lifetime)
{
EwsUtilities.ValidateParam(service, "service");
EwsUtilities.ValidateClassVersion(
service,
ExchangeVersion.Exchange2010_SP1,
this.GetType().Name);
if (lifetime < 1 || lifetime > 30)
{
throw new ArgumentOutOfRangeException("lifetime");
}
this.session = service;
this.subscriptions = new Dictionary<string, StreamingSubscription>();
this.connectionTimeout = lifetime;
}
/// <summary>
/// Initializes a new instance of the <see cref="StreamingSubscriptionConnection"/> class.
/// </summary>
/// <param name="service">The ExchangeService instance this connection uses to connect to the server.</param>
/// <param name="subscriptions">The streaming subscriptions this connection is receiving events for.</param>
/// <param name="lifetime">The maximum time, in minutes, the connection will remain open. Lifetime must be between 1 and 30.</param>
public StreamingSubscriptionConnection(
ExchangeService service,
IEnumerable<StreamingSubscription> subscriptions,
int lifetime) :
this(service, lifetime)
{
EwsUtilities.ValidateParamCollection(subscriptions, "subscriptions");
foreach (StreamingSubscription subscription in subscriptions)
{
this.subscriptions.Add(subscription.Id, subscription);
}
}
/// <summary>
/// Getting the current subscriptions in this connection.
/// </summary>
public IEnumerable<StreamingSubscription> CurrentSubscriptions
{
get
{
List<StreamingSubscription> result = new List<StreamingSubscription>();
lock (this.lockObject)
{
result.AddRange(this.subscriptions.Values);
}
return result;
}
}
/// <summary>
/// Adds a subscription to this connection.
/// </summary>
/// <param name="subscription">The subscription to add.</param>
/// <exception cref="InvalidOperationException">Thrown when AddSubscription is called while connected.</exception>
public void AddSubscription(StreamingSubscription subscription)
{
this.ThrowIfDisposed();
EwsUtilities.ValidateParam(subscription, "subscription");
this.ValidateConnectionState(false, Strings.CannotAddSubscriptionToLiveConnection);
lock (this.lockObject)
{
if (this.subscriptions.ContainsKey(subscription.Id))
{
return;
}
this.subscriptions.Add(subscription.Id, subscription);
}
}
/// <summary>
/// Removes the specified streaming subscription from the connection.
/// </summary>
/// <param name="subscription">The subscription to remove.</param>
/// <exception cref="InvalidOperationException">Thrown when RemoveSubscription is called while connected.</exception>
public void RemoveSubscription(StreamingSubscription subscription)
{
this.ThrowIfDisposed();
EwsUtilities.ValidateParam(subscription, "subscription");
this.ValidateConnectionState(false, Strings.CannotRemoveSubscriptionFromLiveConnection);
lock (this.lockObject)
{
this.subscriptions.Remove(subscription.Id);
}
}
/// <summary>
/// Opens this connection so it starts receiving events from the server.
/// This results in a long-standing call to EWS.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when Open is called while connected.</exception>
public void Open()
{
lock (this.lockObject)
{
this.ThrowIfDisposed();
this.ValidateConnectionState(false, Strings.CannotCallConnectDuringLiveConnection);
if (this.subscriptions.Count == 0)
{
throw new ServiceLocalException(Strings.NoSubscriptionsOnConnection);
}
this.hasFiredConnectionCompleted = false;
this.currentHangingRequest = new GetStreamingEventsRequest(
this.session,
this.HandleServiceResponseObject,
this.subscriptions.Keys,
this.connectionTimeout);
this.currentHangingRequest.OnDisconnect += new HangingServiceRequestBase.HangingRequestDisconnectHandler(this.OnRequestDisconnect);
this.currentHangingRequest.InternalExecute();
}
}
/// <summary>
/// Called when the request is disconnected.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="Microsoft.Exchange.WebServices.Data.HangingRequestDisconnectEventArgs"/> instance containing the event data.</param>
private void OnRequestDisconnect(object sender, HangingRequestDisconnectEventArgs args)
{
this.InternalOnDisconnect(args.Exception);
}
/// <summary>
/// Closes this connection so it stops receiving events from the server.
/// This terminates a long-standing call to EWS.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when Close is called while not connected.</exception>
public void Close()
{
lock (this.lockObject)
{
this.ThrowIfDisposed();
this.ValidateConnectionState(true, Strings.CannotCallDisconnectWithNoLiveConnection);
// Further down in the stack, this will result in a call to our OnRequestDisconnect event handler,
// doing the necessary cleanup.
this.currentHangingRequest.Disconnect();
}
}
/// <summary>
/// Internal helper method called when the request disconnects.
/// </summary>
/// <param name="ex">The exception that caused the disconnection. May be null.</param>
private void InternalOnDisconnect(Exception ex)
{
this.currentHangingRequest = null;
if (this.OnDisconnect != null)
{
this.OnDisconnect(this, new SubscriptionErrorEventArgs(null, ex));
}
}
/// <summary>
/// Gets a value indicating whether this connection is opened
/// </summary>
public bool IsOpen
{
get
{
this.ThrowIfDisposed();
if (this.currentHangingRequest == null)
{
return false;
}
else
{
return this.currentHangingRequest.IsConnected;
}
}
}
/// <summary>
/// Validates the state of the connection.
/// </summary>
/// <param name="isConnectedExpected">Value indicating whether we expect to be currently connected.</param>
/// <param name="errorMessage">The error message.</param>
private void ValidateConnectionState(bool isConnectedExpected, string errorMessage)
{
if ((isConnectedExpected && !this.IsOpen) ||
(!isConnectedExpected && this.IsOpen))
{
throw new ServiceLocalException(errorMessage);
}
}
/// <summary>
/// Handles the service response object.
/// </summary>
/// <param name="response">The response.</param>
private void HandleServiceResponseObject(object response)
{
GetStreamingEventsResponse gseResponse = response as GetStreamingEventsResponse;
if (gseResponse == null)
{
throw new ArgumentException();
}
else
{
if (!hasFiredConnectionCompleted)
{
OnConnectionCompleted?.Invoke(this, new EventArgs());
hasFiredConnectionCompleted = true;
}
if (gseResponse.Result == ServiceResult.Success || gseResponse.Result == ServiceResult.Warning)
{
if (gseResponse.Results.Notifications.Count > 0)
{
// We got notifications; dole them out.
this.IssueNotificationEvents(gseResponse);
}
else
{
//// This was just a heartbeat, nothing to do here.
}
}
else if (gseResponse.Result == ServiceResult.Error)
{
if (gseResponse.ErrorSubscriptionIds == null ||
gseResponse.ErrorSubscriptionIds.Count == 0)
{
// General error
this.IssueGeneralFailure(gseResponse);
}
else
{
// subscription-specific errors
this.IssueSubscriptionFailures(gseResponse);
}
}
}
}
/// <summary>
/// Issues the subscription failures.
/// </summary>
/// <param name="gseResponse">The GetStreamingEvents response.</param>
private void IssueSubscriptionFailures(GetStreamingEventsResponse gseResponse)
{
ServiceResponseException exception = new ServiceResponseException(gseResponse);
foreach (string id in gseResponse.ErrorSubscriptionIds)
{
StreamingSubscription subscription = null;
lock (this.lockObject)
{
// Client can do any good or bad things in the below event handler
if (this.subscriptions != null && this.subscriptions.ContainsKey(id))
{
subscription = this.subscriptions[id];
}
}
if (subscription != null)
{
SubscriptionErrorEventArgs eventArgs = new SubscriptionErrorEventArgs(
subscription,
exception);
if (this.OnSubscriptionError != null)
{
this.OnSubscriptionError(this, eventArgs);
}
}
if (gseResponse.ErrorCode != ServiceError.ErrorMissedNotificationEvents)
{
// Client can do any good or bad things in the above event handler
lock (this.lockObject)
{
if (this.subscriptions != null && this.subscriptions.ContainsKey(id))
{
// We are no longer servicing the subscription.
this.subscriptions.Remove(id);
}
}
}
}
}
/// <summary>
/// Issues the general failure.
/// </summary>
/// <param name="gseResponse">The GetStreamingEvents response.</param>
private void IssueGeneralFailure(GetStreamingEventsResponse gseResponse)
{
SubscriptionErrorEventArgs eventArgs = new SubscriptionErrorEventArgs(
null,
new ServiceResponseException(gseResponse));
if (this.OnSubscriptionError != null)
{
this.OnSubscriptionError(this, eventArgs);
}
}
/// <summary>
/// Issues the notification events.
/// </summary>
/// <param name="gseResponse">The GetStreamingEvents response.</param>
private void IssueNotificationEvents(GetStreamingEventsResponse gseResponse)
{
foreach (GetStreamingEventsResults.NotificationGroup events in gseResponse.Results.Notifications)
{
StreamingSubscription subscription = null;
lock (this.lockObject)
{
// Client can do any good or bad things in the below event handler
if (this.subscriptions != null && this.subscriptions.ContainsKey(events.SubscriptionId))
{
subscription = this.subscriptions[events.SubscriptionId];
}
}
if (subscription != null)
{
NotificationEventArgs eventArgs = new NotificationEventArgs(
subscription,
events.Events);
if (this.OnNotificationEvent != null)
{
this.OnNotificationEvent(this, eventArgs);
}
}
}
}
#region IDisposable Members
/// <summary>
/// Finalizes an instance of the StreamingSubscriptionConnection class.
/// </summary>
~StreamingSubscriptionConnection()
{
this.Dispose(false);
}
/// <summary>
/// Frees resources associated with this StreamingSubscriptionConnection.
/// </summary>
public void Dispose()
{
this.Dispose(true);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <param name="suppressFinalizer">Value indicating whether to suppress the garbage collector's finalizer..</param>
private void Dispose(bool suppressFinalizer)
{
if (suppressFinalizer)
{
GC.SuppressFinalize(this);
}
lock (this.lockObject)
{
if (!this.isDisposed)
{
if (this.currentHangingRequest != null)
{
this.currentHangingRequest = null;
}
this.subscriptions = null;
this.session = null;
this.isDisposed = true;
}
}
}
/// <summary>
/// Throws if disposed.
/// </summary>
private void ThrowIfDisposed()
{
if (this.isDisposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
#endregion
}
}