This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
SqlDependencyListener.cs
1478 lines (1322 loc) · 62.3 KB
/
SqlDependencyListener.cs
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Threading;
using System.Xml;
using System.Runtime.Versioning;
using System.Diagnostics.CodeAnalysis;
// This class is the process wide dependency dispatcher. It contains all connection listeners for the entire process and
// receives notifications on those connections to dispatch to the corresponding AppDomain dispatcher to notify the
// appropriate dependencies.
internal class SqlDependencyProcessDispatcher : MarshalByRefObject
{
// Class to contain/store all relevant information about a connection that waits on the SSB queue.
private class SqlConnectionContainer
{
private SqlConnection _con;
private SqlCommand _com;
private SqlParameter _conversationGuidParam;
private SqlParameter _timeoutParam;
private SqlConnectionContainerHashHelper _hashHelper;
private string _queue;
private string _receiveQuery;
private string _beginConversationQuery;
private string _endConversationQuery;
private string _concatQuery;
private readonly int _defaultWaitforTimeout = 60000; // Waitfor(Receive) timeout (milleseconds)
private string _escapedQueueName;
private string _sprocName;
private string _dialogHandle;
private string _cachedServer;
private string _cachedDatabase;
private volatile bool _errorState = false;
private volatile bool _stop = false; // Can probably simplify this slightly - one bool instead of two.
private volatile bool _stopped = false;
private volatile bool _serviceQueueCreated = false;
private int _startCount = 0; // Each container class is called once per Start() - we refCount
// to track when we can dispose.
private Timer _retryTimer = null;
private Dictionary<string, int> _appDomainKeyHash = null; // AppDomainKey->Open RefCount
// Constructor
internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults)
{
bool setupCompleted = false;
try
{
_hashHelper = hashHelper;
string guid = null;
// If default, queue name is not present on hashHelper at this point - so we need to
// generate one and complete initialization.
if (useDefaults)
{
guid = Guid.NewGuid().ToString();
_queue = SQL.SqlNotificationServiceDefault + "-" + guid;
_hashHelper.ConnectionStringBuilder.ApplicationName = _queue; // Used by cleanup sproc.
}
else
{
_queue = _hashHelper.Queue;
}
// Always use ConnectionStringBuilder since in default case it is different from the
// connection string used in the hashHelper.
_con = new SqlConnection(_hashHelper.ConnectionStringBuilder.ConnectionString); // Create connection and open.
// Assert permission for this particular connection string since it differs from the user passed string
// which we have already demanded upon.
SqlConnectionString connStringObj = (SqlConnectionString)_con.ConnectionOptions;
_con.Open();
_cachedServer = _con.DataSource;
_escapedQueueName = SqlConnection.FixupDatabaseTransactionName(_queue); // Properly escape to prevent SQL Injection.
_appDomainKeyHash = new Dictionary<string, int>(); // Dictionary stores the Start/Stop refcount per AppDomain for this container.
_com = new SqlCommand()
{
Connection = _con,
// Determine if broker is enabled on current database.
CommandText = "select is_broker_enabled from sys.databases where database_id=db_id()"
};
if (!(bool)_com.ExecuteScalar())
{
throw SQL.SqlDependencyDatabaseBrokerDisabled();
}
_conversationGuidParam = new SqlParameter("@p1", SqlDbType.UniqueIdentifier);
_timeoutParam = new SqlParameter("@p2", SqlDbType.Int)
{
Value = 0 // Timeout set to 0 for initial sync query.
};
_com.Parameters.Add(_timeoutParam);
setupCompleted = true;
// connection with the server has been setup - from this point use TearDownAndDispose() in case of error
// Create standard query.
_receiveQuery = "WAITFOR(RECEIVE TOP (1) message_type_name, conversation_handle, cast(message_body AS XML) as message_body from " + _escapedQueueName + "), TIMEOUT @p2;";
// Create queue, service, sync query, and async query on user thread to ensure proper
// init prior to return.
if (useDefaults)
{ // Only create if user did not specify service & database.
_sprocName = SqlConnection.FixupDatabaseTransactionName(SQL.SqlNotificationStoredProcedureDefault + "-" + guid);
CreateQueueAndService(false); // Fail if we cannot create service, queue, etc.
}
else
{
// Continue query setup.
_com.CommandText = _receiveQuery;
_endConversationQuery = "END CONVERSATION @p1; ";
_concatQuery = _endConversationQuery + _receiveQuery;
}
IncrementStartCount(appDomainKey, out bool ignored);
// Query synchronously once to ensure everything is working correctly.
// We want the exception to occur on start to immediately inform caller.
SynchronouslyQueryServiceBrokerQueue();
_timeoutParam.Value = _defaultWaitforTimeout; // Sync successful, extend timeout to 60 seconds.
AsynchronouslyQueryServiceBrokerQueue();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
if (setupCompleted)
{
// Be sure to drop service & queue. This may fail if create service & queue failed.
// This method will not drop unless we created or service & queue ref-count is 0.
TearDownAndDispose();
}
else
{
// connection has not been fully setup yet - cannot use TearDownAndDispose();
// we have to dispose the command and the connection to avoid connection leaks (until GC collects them).
if (_com != null)
{
_com.Dispose();
_com = null;
}
if (_con != null)
{
_con.Dispose();
_con = null;
}
}
throw;
}
}
// Properties
internal string Database
{
get
{
if (_cachedDatabase == null)
{
_cachedDatabase = _con.Database;
}
return _cachedDatabase;
}
}
internal SqlConnectionContainerHashHelper HashHelper => _hashHelper;
internal bool InErrorState => _errorState;
internal string Queue => _queue;
internal string Server => _cachedServer;
// Methods
// This function is called by a ThreadPool thread as a result of an AppDomain calling
// SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload.
internal bool AppDomainUnload(string appDomainKey)
{
Debug.Assert(!string.IsNullOrEmpty(appDomainKey), "Unexpected empty appDomainKey!");
// Dictionary used to track how many times start has been called per app domain.
// For each decrement, subtract from count, and delete if we reach 0.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{ // Do nothing if AppDomain did not call Start!
int value = _appDomainKeyHash[appDomainKey];
Debug.Assert(value > 0, "Why is value 0 or less?");
bool ignored = false;
while (value > 0)
{
Debug.Assert(!_stopped, "We should not yet be stopped!");
Stop(appDomainKey, out ignored); // Stop will decrement value and remove if necessary from _appDomainKeyHash.
value--;
}
// Stop will remove key when decremented to 0 for this AppDomain, which should now be the case.
Debug.Assert(0 == value, "We did not reach 0 at end of loop in AppDomainUnload!");
Debug.Assert(!_appDomainKeyHash.ContainsKey(appDomainKey), "Key not removed after AppDomainUnload!");
}
}
return _stopped;
}
private void AsynchronouslyQueryServiceBrokerQueue()
{
AsyncCallback callback = new AsyncCallback(AsyncResultCallback);
_com.BeginExecuteReader(CommandBehavior.Default, callback, null); // NO LOCK NEEDED
}
private void AsyncResultCallback(IAsyncResult asyncResult)
{
try
{
using (SqlDataReader reader = _com.EndExecuteReader(asyncResult))
{
ProcessNotificationResults(reader);
}
// Successfull completion of query - no errors.
if (!_stop)
{
AsynchronouslyQueryServiceBrokerQueue(); // Requeue...
}
else
{
TearDownAndDispose();
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
// Let the waiting thread detect the error and exit (otherwise, the Stop call loops forever)
_errorState = true;
throw;
}
if (!_stop)
{ // Only assert if not in cancel path.
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
}
// Failure - likely due to cancelled command. Check _stop state.
if (_stop)
{
TearDownAndDispose();
}
else
{
_errorState = true;
Restart(null); // Error code path. Will Invalidate based on server if 1st retry fails.
}
}
}
private void CreateQueueAndService(bool restart)
{
SqlCommand com = new SqlCommand()
{
Connection = _con
};
SqlTransaction trans = null;
try
{
trans = _con.BeginTransaction(); // Since we cannot batch proc creation, start transaction.
com.Transaction = trans;
string nameLiteral = SqlServerEscapeHelper.MakeStringLiteral(_queue);
com.CommandText =
"CREATE PROCEDURE " + _sprocName + " AS"
+ " BEGIN"
+ " BEGIN TRANSACTION;"
+ " RECEIVE TOP(0) conversation_handle FROM " + _escapedQueueName + ";"
+ " IF (SELECT COUNT(*) FROM " + _escapedQueueName + " WHERE message_type_name = 'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer') > 0"
+ " BEGIN"
+ " if ((SELECT COUNT(*) FROM sys.services WHERE name = " + nameLiteral + ") > 0)"
+ " DROP SERVICE " + _escapedQueueName + ";"
+ " if (OBJECT_ID(" + nameLiteral + ", 'SQ') IS NOT NULL)"
+ " DROP QUEUE " + _escapedQueueName + ";"
+ " DROP PROCEDURE " + _sprocName + ";" // Don't need conditional because this is self
+ " END"
+ " COMMIT TRANSACTION;"
+ " END";
if (!restart)
{
com.ExecuteNonQuery();
}
else
{ // Upon restart, be resilient to the user dropping queue, service, or procedure.
try
{
com.ExecuteNonQuery(); // Cannot add 'IF OBJECT_ID' to create procedure query - wrap and discard failure.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
try
{ // Since the failure will result in a rollback, rollback our object.
if (null != trans)
{
trans.Rollback();
trans = null;
}
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard failure, but trace for now.
}
}
if (null == trans)
{ // Create a new transaction for next operations.
trans = _con.BeginTransaction();
com.Transaction = trans;
}
}
com.CommandText =
"IF OBJECT_ID(" + nameLiteral + ", 'SQ') IS NULL"
+ " BEGIN"
+ " CREATE QUEUE " + _escapedQueueName + " WITH ACTIVATION (PROCEDURE_NAME=" + _sprocName + ", MAX_QUEUE_READERS=1, EXECUTE AS OWNER);"
+ " END;"
+ " IF (SELECT COUNT(*) FROM sys.services WHERE NAME=" + nameLiteral + ") = 0"
+ " BEGIN"
+ " CREATE SERVICE " + _escapedQueueName + " ON QUEUE " + _escapedQueueName + " ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);"
+ " IF (SELECT COUNT(*) FROM sys.database_principals WHERE name='sql_dependency_subscriber' AND type='R') <> 0"
+ " BEGIN"
+ " GRANT SEND ON SERVICE::" + _escapedQueueName + " TO sql_dependency_subscriber;"
+ " END; "
+ " END;"
+ " BEGIN DIALOG @dialog_handle FROM SERVICE " + _escapedQueueName + " TO SERVICE " + nameLiteral;
SqlParameter param = new SqlParameter()
{
ParameterName = "@dialog_handle",
DbType = DbType.Guid,
Direction = ParameterDirection.Output
};
com.Parameters.Add(param);
com.ExecuteNonQuery();
// Finish setting up queries and state. For re-start, we need to ensure we begin a new dialog above and reset
// our queries to use the new dialogHandle.
_dialogHandle = ((Guid)param.Value).ToString();
_beginConversationQuery = "BEGIN CONVERSATION TIMER ('" + _dialogHandle + "') TIMEOUT = 120; " + _receiveQuery;
_com.CommandText = _beginConversationQuery;
_endConversationQuery = "END CONVERSATION @p1; ";
_concatQuery = _endConversationQuery + _com.CommandText;
trans.Commit();
trans = null;
_serviceQueueCreated = true;
}
finally
{
if (null != trans)
{
try
{
trans.Rollback();
trans = null;
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
}
}
}
}
internal void IncrementStartCount(string appDomainKey, out bool appDomainStart)
{
appDomainStart = false; // Reset out param.
int result = Interlocked.Increment(ref _startCount); // Add to refCount.
// Dictionary used to track how many times start has been called per app domain.
// For each increment, add to count, and create entry if not present.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{
_appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1;
}
else
{
_appDomainKeyHash[appDomainKey] = 1;
appDomainStart = true;
}
}
}
private void ProcessNotificationResults(SqlDataReader reader)
{
Guid handle = Guid.Empty; // Conversation_handle. Always close this!
try
{
if (!_stop)
{
while (reader.Read())
{
string msgType = reader.GetString(0);
handle = reader.GetGuid(1);
// Only process QueryNotification messages.
if (0 == string.Compare(msgType, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase))
{
SqlXml payload = reader.GetSqlXml(2);
if (null != payload)
{
SqlNotification notification = SqlNotificationParser.ProcessMessage(payload);
if (null != notification)
{
string key = notification.Key;
int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash"
if (index >= 0)
{ // Ensure ';' present.
string appDomainKey = key.Substring(0, index);
SqlDependencyPerAppDomainDispatcher dispatcher;
lock (s_staticInstance._sqlDependencyPerAppDomainDispatchers)
{
dispatcher = s_staticInstance._sqlDependencyPerAppDomainDispatchers[appDomainKey];
}
if (null != dispatcher)
{
try
{
dispatcher.InvalidateCommandID(notification); // CROSS APP-DOMAIN CALL!
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure. User event could throw exception.
}
}
else
{
Debug.Fail("Received notification but do not have an associated PerAppDomainDispatcher!");
}
}
else
{
Debug.Fail("Unexpected ID format received!");
}
}
else
{
Debug.Fail("Null notification returned from ProcessMessage!");
}
}
else
{
Debug.Fail("Null payload for QN notification type!");
}
}
else
{
handle = Guid.Empty;
}
}
}
}
finally
{
// Since we do not want to make a separate round trip just for the end conversation call, we need to
// batch it with the next command.
if (handle == Guid.Empty)
{ // This should only happen if failure occurred, or if non-QN format received.
_com.CommandText = _beginConversationQuery ?? _receiveQuery; // If we're doing the initial query, we won't have a conversation Guid to begin yet.
if (_com.Parameters.Count > 1)
{ // Remove conversation param since next execute is only query.
_com.Parameters.Remove(_conversationGuidParam);
}
Debug.Assert(_com.Parameters.Count == 1, "Unexpected number of parameters!");
}
else
{
_com.CommandText = _concatQuery; // END query + WAITFOR RECEIVE query.
_conversationGuidParam.Value = handle; // Set value for conversation handle.
if (_com.Parameters.Count == 1)
{ // Add parameter if previous execute was only query.
_com.Parameters.Add(_conversationGuidParam);
}
Debug.Assert(_com.Parameters.Count == 2, "Unexpected number of parameters!");
}
}
}
// SxS: this method uses WindowsIdentity.Impersonate to impersonate the current thread with the
// credentials used to create this SqlConnectionContainer.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
private void Restart(object unused)
{ // Unused arg required by TimerCallback.
try
{
lock (this)
{
if (!_stop)
{ // Only execute if we are still in running state.
try
{
_con.Close();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard close failure, if it occurs. Only trace it.
}
}
}
// Rather than one long lock - take lock 3 times for shorter periods.
lock (this)
{
if (!_stop)
{
_con.Open();
}
}
lock (this)
{
if (!_stop)
{
if (_serviceQueueCreated)
{
bool failure = false;
try
{
CreateQueueAndService(true); // Ensure service, queue, etc is present, if we created it.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
failure = true;
}
if (failure)
{
// If we failed to re-created queue, service, sproc - invalidate!
s_staticInstance.Invalidate(Server,
new SqlNotification(SqlNotificationInfo.Error,
SqlNotificationSource.Client,
SqlNotificationType.Change,
null));
}
}
}
}
lock (this)
{
if (!_stop)
{
_timeoutParam.Value = 0; // Reset timeout to zero - we do not want to block.
SynchronouslyQueryServiceBrokerQueue();
// If the above succeeds, we are back in success case - requeue for async call.
_timeoutParam.Value = _defaultWaitforTimeout; // If success, reset to default for re-queue.
AsynchronouslyQueryServiceBrokerQueue();
_errorState = false;
Timer retryTimer = _retryTimer;
if (retryTimer != null)
{
_retryTimer = null;
retryTimer.Dispose();
}
}
}
if (_stop)
{
TearDownAndDispose(); // Function will lock(this).
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
try
{
// If unexpected query or connection failure, invalidate all dependencies against this server.
// We may over-notify if only some of the connections to a particular database were affected,
// but this should not be frequent enough to be a concern.
// NOTE - we invalidate after failure first occurs and then retry fails. We will then continue
// to invalidate every time the retry fails.
s_staticInstance.Invalidate(Server,
new SqlNotification(SqlNotificationInfo.Error,
SqlNotificationSource.Client,
SqlNotificationType.Change,
null));
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard exception from Invalidate. User events can throw.
}
try
{
_con.Close();
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard close failure, if it occurs. Only trace it.
}
if (!_stop)
{
// Create a timer to callback in one minute, retrying the call to Restart().
_retryTimer = new Timer(new TimerCallback(Restart), null, _defaultWaitforTimeout, Timeout.Infinite);
// We will retry this indefinitely, until success - or Stop();
}
}
}
internal bool Stop(string appDomainKey, out bool appDomainStop)
{
appDomainStop = false;
// Dictionary used to track how many times start has been called per app domain.
// For each decrement, subtract from count, and delete if we reach 0.
if (null != appDomainKey)
{
// If null, then this was called from SqlDependencyProcessDispatcher, we ignore appDomainKeyHash.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{ // Do nothing if AppDomain did not call Start!
int value = _appDomainKeyHash[appDomainKey];
Debug.Assert(value > 0, "Unexpected count for appDomainKey");
if (value > 0)
{
_appDomainKeyHash[appDomainKey] = value - 1;
}
else
{
Debug.Fail("Unexpected AppDomainKey count in Stop()");
}
if (1 == value)
{ // Remove from dictionary if pre-decrement count was one.
_appDomainKeyHash.Remove(appDomainKey);
appDomainStop = true;
}
}
else
{
Debug.Fail("Unexpected state on Stop() - no AppDomainKey entry in hashtable!");
}
}
}
Debug.Assert(_startCount > 0, "About to decrement _startCount less than 0!");
int result = Interlocked.Decrement(ref _startCount);
if (0 == result)
{ // If we've reached refCount 0, destroy.
// Lock to ensure Cancel() complete prior to other thread calling TearDown.
lock (this)
{
try
{
// Race condition with executing thread - will throw if connection is closed due to failure.
// Rather than fighting the race condition, just call it and discard any potential failure.
_com.Cancel(); // Cancel the pending command. No-op if connection closed.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
_stop = true;
}
// Wait until stopped and service & queue are dropped.
Stopwatch retryStopwatch = Stopwatch.StartNew();
while (true)
{
lock (this)
{
if (_stopped)
{
break;
}
// If we are in error state (_errorState is true), force a tear down.
// Likewise, if we have exceeded the maximum retry period (30 seconds) waiting for cleanup, force a tear down.
// In rare cases during app domain unload, the async cleanup performed by AsyncResultCallback
// may fail to execute TearDownAndDispose, leaving this method in an infinite loop.
// To avoid the infinite loop, we force the cleanup here after 30 seconds. Since we have reached
// refcount of 0, either this method call or the thread running AsyncResultCallback is responsible for calling
// TearDownAndDispose when transitioning to the _stopped state. Failing to call TearDownAndDispose means we leak
// the service broker objects created by this SqlDependency instance, so we make a best effort here to call
// TearDownAndDispose in the maximum retry period case as well as in the _errorState case.
if (_errorState || retryStopwatch.Elapsed.Seconds >= 30)
{
Timer retryTimer = _retryTimer;
_retryTimer = null;
if (retryTimer != null)
{
retryTimer.Dispose(); // Dispose timer - stop retry loop!
}
TearDownAndDispose(); // Will not hit server unless connection open!
break;
}
}
// Yield the thread since the stop has not yet completed.
// To avoid CPU spikes while waiting, yield and wait for at least one millisecond
Thread.Sleep(1);
}
}
Debug.Assert(0 <= _startCount, "Invalid start count state");
return _stopped;
}
private void SynchronouslyQueryServiceBrokerQueue()
{
using (SqlDataReader reader = _com.ExecuteReader())
{
ProcessNotificationResults(reader);
}
}
[SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")]
private void TearDownAndDispose()
{
lock (this)
{ // Lock to ensure Stop() (with Cancel()) complete prior to TearDown.
try
{
// Only execute if connection is still up and open.
if (ConnectionState.Closed != _con.State && ConnectionState.Broken != _con.State)
{
if (_com.Parameters.Count > 1)
{ // Need to close dialog before completing.
// In the normal case, the "End Conversation" query is executed before a
// receive query and upon return we will clear the state. However, unless
// a non notification query result is returned, we will not clear it. That
// means a query is generally always executing with an "end conversation" on
// the wire. Rather than synchronize for success of the other "end conversation",
// simply re-execute.
try
{
_com.CommandText = _endConversationQuery;
_com.Parameters.Remove(_timeoutParam);
_com.ExecuteNonQuery();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure.
}
}
if (_serviceQueueCreated && !_errorState)
{
/*
BEGIN TRANSACTION;
DROP SERVICE "+_escapedQueueName+";
DROP QUEUE "+_escapedQueueName+";
DROP PROCEDURE "+_sprocName+";
COMMIT TRANSACTION;
*/
_com.CommandText = "BEGIN TRANSACTION; DROP SERVICE " + _escapedQueueName + "; DROP QUEUE " + _escapedQueueName + "; DROP PROCEDURE " + _sprocName + "; COMMIT TRANSACTION;";
try
{
_com.ExecuteNonQuery();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure.
}
}
}
}
finally
{
_stopped = true;
_con.Dispose(); // Close and dispose connection.
}
}
}
}
// Private class encapsulating the notification payload parsing logic.
private class SqlNotificationParser
{
[Flags]
private enum MessageAttributes
{
None = 0,
Type = 1,
Source = 2,
Info = 4,
All = Type + Source + Info,
}
// node names in the payload
private const string RootNode = "QueryNotification";
private const string MessageNode = "Message";
// attribute names (on the QueryNotification element)
private const string InfoAttribute = "info";
private const string SourceAttribute = "source";
private const string TypeAttribute = "type";
internal static SqlNotification ProcessMessage(SqlXml xmlMessage)
{
using (XmlReader xmlReader = xmlMessage.CreateReader())
{
string keyvalue = string.Empty;
MessageAttributes messageAttributes = MessageAttributes.None;
SqlNotificationType type = SqlNotificationType.Unknown;
SqlNotificationInfo info = SqlNotificationInfo.Unknown;
SqlNotificationSource source = SqlNotificationSource.Unknown;
string key = string.Empty;
// Move to main node, expecting "QueryNotification".
xmlReader.Read();
if ((XmlNodeType.Element == xmlReader.NodeType) &&
(RootNode == xmlReader.LocalName) &&
(3 <= xmlReader.AttributeCount))
{
// Loop until we've processed all the attributes.
while ((MessageAttributes.All != messageAttributes) && (xmlReader.MoveToNextAttribute()))
{
try
{
switch (xmlReader.LocalName)
{
case TypeAttribute:
try
{
SqlNotificationType temp = (SqlNotificationType)Enum.Parse(typeof(SqlNotificationType), xmlReader.Value, true);
if (Enum.IsDefined(typeof(SqlNotificationType), temp))
{
type = temp;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Type;
break;
case SourceAttribute:
try
{
SqlNotificationSource temp = (SqlNotificationSource)Enum.Parse(typeof(SqlNotificationSource), xmlReader.Value, true);
if (Enum.IsDefined(typeof(SqlNotificationSource), temp))
{
source = temp;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Source;
break;
case InfoAttribute:
try
{
string value = xmlReader.Value;
// 3 of the server info values do not match client values - map.
switch (value)
{
case "set options":
info = SqlNotificationInfo.Options;
break;
case "previous invalid":
info = SqlNotificationInfo.PreviousFire;
break;
case "query template limit":
info = SqlNotificationInfo.TemplateLimit;
break;
default:
SqlNotificationInfo temp = (SqlNotificationInfo)Enum.Parse(typeof(SqlNotificationInfo), value, true);
if (Enum.IsDefined(typeof(SqlNotificationInfo), temp))
{
info = temp;
}
break;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Info;
break;
default:
break;
}
}
catch (ArgumentException e)
{
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace.
return null;
}
}
if (MessageAttributes.All != messageAttributes)