File: ReceiveActivity.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1736 lines) | stat: -rw-r--r-- 74,911 bytes parent folder | download | duplicates (7)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------

namespace System.Workflow.Activities
{
    using System;
    using System.Reflection;
    using System.Collections;
    using System.Collections.ObjectModel;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Drawing;
    using System.Globalization;
    using System.IdentityModel.Claims;
    using System.Security.Permissions;
    using System.ServiceModel;
    using System.ServiceModel.Description;
    using System.ServiceModel.Dispatcher;
    using System.Workflow.Activities;
    using System.Workflow.ComponentModel;
    using System.Workflow.ComponentModel.Compiler;
    using System.Workflow.ComponentModel.Design;
    using System.Workflow.ComponentModel.Serialization;
    using System.Workflow.Runtime;
    using System.Xml;

    [SR2Description(SR2DescriptionAttribute.ReceiveActivityDescription)]
    [SR2Category(SR2CategoryAttribute.Standard)]
    [Designer(typeof(ReceiveActivityDesigner), typeof(IDesigner))]
    [ToolboxBitmap(typeof(ReceiveActivity), "Design.Resources.ReceiveActivity.png")]
    [ActivityValidator(typeof(ReceiveActivityValidator))]
    [Serializable]
    [Obsolete("The System.Workflow.* types are deprecated.  Instead, please use the new types from System.Activities.*")]
    public sealed class ReceiveActivity : SequenceActivity,
        IEventActivity,
        IActivityEventListener<QueueEventArgs>,
        IServiceDescriptionBuilder
    {
        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        public static readonly DependencyProperty FaultMessageProperty =
            DependencyProperty.Register("FaultMessage",
            typeof(FaultException),
            typeof(ReceiveActivity),
            new PropertyMetadata(null));

        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        public static readonly DependencyProperty OperationValidationEvent =
            DependencyProperty.Register("OperationValidation",
            typeof(EventHandler<OperationValidationEventArgs>),
            typeof(ReceiveActivity));

        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        public static readonly DependencyProperty WorkflowServiceAttributesProperty =
            DependencyProperty.RegisterAttached("WorkflowServiceAttributes",
            typeof(WorkflowServiceAttributes), typeof(ReceiveActivity),
            new PropertyMetadata(null, DependencyPropertyOptions.Metadata,
            ReceiveActivity.GetWorkflowServiceAttributesValueOverride, null),
            typeof(WorkflowServiceAttributesDynamicPropertyValidator));

        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        internal static readonly DependencyProperty CanCreateInstanceProperty =
            DependencyProperty.Register("CanCreateInstance",
            typeof(bool),
            typeof(ReceiveActivity),
            new PropertyMetadata(false, DependencyPropertyOptions.Metadata));

        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        internal static readonly DependencyProperty ContextTokenProperty =
            DependencyProperty.Register("ContextToken",
            typeof(ContextToken),
            typeof(ReceiveActivity),
            new PropertyMetadata(null, DependencyPropertyOptions.Metadata));

        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        internal static readonly DependencyProperty ParameterBindingsProperty =
            DependencyProperty.Register("ParameterBindings",
            typeof(WorkflowParameterBindingCollection),
            typeof(ReceiveActivity),
            new PropertyMetadata(DependencyPropertyOptions.Metadata | DependencyPropertyOptions.ReadOnly));

        [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
        internal static readonly DependencyProperty ServiceOperationInfoProperty =
            DependencyProperty.Register("ServiceOperationInfo",
            typeof(OperationInfoBase),
            typeof(ReceiveActivity),
            new PropertyMetadata(DependencyPropertyOptions.Metadata));

        private static readonly DependencyProperty QueueNameProperty =
            DependencyProperty.Register("QueueName",
            typeof(string),
            typeof(ReceiveActivity));

        private static readonly DependencyProperty RequestContextProperty =
            DependencyProperty.Register("RequestContext",
            typeof(WorkflowRequestContext),
            typeof(ReceiveActivity));

        static DependencyProperty QueueInitializationModeProperty =
            DependencyProperty.Register("QueueInitializationMode",
            typeof(QueueInitializationMode),
            typeof(ReceiveActivity),
            new PropertyMetadata(QueueInitializationMode.Standalone));

        [NonSerialized]
        private ReceiveOperationInfoHelper operationHelper;

        private IActivityEventListener<QueueEventArgs> securityShim;
        private IActivityEventListener<QueueEventArgs> validationShim;

        [NonSerialized]
        private static Hashtable requestContextsCache = Hashtable.Synchronized(new Hashtable());
        private bool isContextCached;

        public ReceiveActivity()
        {
            base.SetReadOnlyPropertyValue(ReceiveActivity.ParameterBindingsProperty,
                new WorkflowParameterBindingCollection(this));
        }

        public ReceiveActivity(string name)
            : base(name)
        {
            base.SetReadOnlyPropertyValue(ReceiveActivity.ParameterBindingsProperty,
                new WorkflowParameterBindingCollection(this));
        }

        [SRCategory(SR2CategoryAttribute.Handlers)]
        [SR2Description(SR2DescriptionAttribute.Receive_OperationValidation_Description)]
        [MergableProperty(false)]
        public event EventHandler<OperationValidationEventArgs> OperationValidation
        {
            add
            {
                base.AddHandler(OperationValidationEvent, value);
            }
            remove
            {
                base.RemoveHandler(OperationValidationEvent, value);
            }
        }

        [Browsable(true)]
        [DefaultValue(false)]
        [SR2Category(SR2CategoryAttribute.Activity)]
        [SR2Description(SR2DescriptionAttribute.Receive_CanCreateInstance_Description)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public bool CanCreateInstance
        {
            get
            {
                return ((bool)(base.GetValue(ReceiveActivity.CanCreateInstanceProperty)));
            }
            set
            {
                base.SetValue(ReceiveActivity.CanCreateInstanceProperty, value);
            }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public IDictionary<string, string> Context
        {
            get
            {
                if (this.ContextToken == null)
                {
                    return ReceiveActivity.GetRootContext(this);
                }
                return ReceiveActivity.GetContext(this, this.ContextToken);
            }
        }

        [DefaultValue(null)]
        [MergableProperty(false)]
        [RefreshProperties(RefreshProperties.All)]
        [SR2Category(SR2CategoryAttribute.Activity)]
        [SR2Description(SR2DescriptionAttribute.Receive_ContextToken_Description)]
        [TypeConverter(typeof(ContextTokenTypeConverter))]
        public ContextToken ContextToken
        {
            get
            {
                return base.GetValue(ContextTokenProperty) as ContextToken;
            }
            set
            {
                base.SetValue(ContextTokenProperty, value);
            }
        }

        [Browsable(true)]
        [DefaultValue(null)]
        [SR2Category(SR2CategoryAttribute.Activity)]
        [SR2Description(SR2DescriptionAttribute.Receive_FaultMessage_Description)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public FaultException FaultMessage
        {
            get
            {
                return ((FaultException)base.GetValue(ReceiveActivity.FaultMessageProperty));
            }

            set
            {
                base.SetValue(ReceiveActivity.FaultMessageProperty, value);
            }
        }


        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public WorkflowParameterBindingCollection ParameterBindings
        {
            get
            {
                return ((WorkflowParameterBindingCollection)(base.GetValue(ReceiveActivity.ParameterBindingsProperty)));
            }
        }


        [Browsable(true)]
        [SR2Category(SR2CategoryAttribute.Activity)]
        [SR2Description(SR2DescriptionAttribute.Receive_OperationInfo_Description)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public OperationInfoBase ServiceOperationInfo
        {
            get
            {
                return ((OperationInfoBase)(base.GetValue(ReceiveActivity.ServiceOperationInfoProperty)));
            }
            set
            {
                OperationInfoBase currentValue = ((OperationInfoBase)(base.GetValue(ReceiveActivity.ServiceOperationInfoProperty)));
                if (value != null && currentValue != value)
                {
                    DependencyProperty ParentDependencyObjectProperty =
                        DependencyProperty.FromName("ParentDependencyObject", typeof(DependencyObject));

                    Activity currentParent = value.GetValue(ParentDependencyObjectProperty) as Activity;

                    if (currentParent != null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
                            "value",
                            SR2.GetString(SR2.Error_OperationIsAlreadyAssociatedWithActivity,
                            value,
                            currentParent.QualifiedName));
                    }

                    if (currentValue != null)
                    {
                        currentValue.SetValue(ParentDependencyObjectProperty, null);
                    }

                    value.SetValue(ParentDependencyObjectProperty, this);
                }

                if (this.DesignMode && value is OperationInfo)
                {
                    Activity rootActivity = this.RootActivity;
                    rootActivity.RemoveProperty(DynamicContractTypeBuilder.DynamicContractTypesProperty);
                }

                base.SetValue(ReceiveActivity.ServiceOperationInfoProperty, value);
            }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        internal WorkflowRequestContext RequestContext
        {
            get
            {
                return ((WorkflowRequestContext)(base.GetValue(ReceiveActivity.RequestContextProperty)));
            }
            set
            {
                base.SetValue(ReceiveActivity.RequestContextProperty, value);
            }
        }

        IComparable IEventActivity.QueueName
        {
            get { return this.GetValue(ReceiveActivity.QueueNameProperty) as string; }
        }

        ReceiveOperationInfoHelper OperationHelper
        {
            get
            {
                if (this.operationHelper == null)
                {
                    if (this.UserData.Contains(typeof(ReceiveOperationInfoHelper)))
                    {
                        this.operationHelper = this.UserData[typeof(ReceiveOperationInfoHelper)] as ReceiveOperationInfoHelper;
                    }
                }

                if (this.operationHelper == null)
                {
                    this.operationHelper = new ReceiveOperationInfoHelper(this.Site, this);
                    this.UserData[typeof(ReceiveOperationInfoHelper)] = this.operationHelper;
                }

                return this.operationHelper;
            }
        }

        private QueueInitializationMode QueueInitializationMode
        {
            get
            {
                return (QueueInitializationMode)base.GetValue(ReceiveActivity.QueueInitializationModeProperty);
            }
            set
            {
                base.SetValue(ReceiveActivity.QueueInitializationModeProperty, value);
            }
        }

        public static IDictionary<string, string> GetContext(Activity activity,
            ContextToken contextToken)
        {
            if (activity == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity");
            }
            if (contextToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contextToken");
            }

            if (contextToken.IsRootContext)
            {
                return GetRootContext(activity);
            }

            return GetContext(activity, contextToken.Name, contextToken.OwnerActivityName);
        }

        public static IDictionary<string, string> GetContext(Activity activity,
            string contextName,
            string ownerActivityName)
        {
            if (activity == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity");
            }
            if (string.IsNullOrEmpty(contextName))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("contextName",
                    SR2.GetString(SR2.Error_ArgumentValueNullOrEmptyString));
            }

            ReceiveContext receiveContext = ContextToken.GetReceiveContext(activity, contextName, ownerActivityName);
            if (receiveContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_CannotFindReceiveContext, contextName)));
            }

            return receiveContext.Properties;
        }

        public static IDictionary<string, string> GetRootContext(Activity activity)
        {
            if (activity == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity");
            }

            ReceiveContext receiveContext = ContextToken.GetRootReceiveContext(activity);
            if (receiveContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_CannotFindReceiveContext, ContextToken.RootContextName)));
            }

            return receiveContext.Properties;
        }

        public static object GetWorkflowServiceAttributes(object dependencyObject)
        {
            if (dependencyObject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dependencyObject");
            }
            if (!(dependencyObject is Activity))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
                    "dependencyObject",
                    SR2.GetString(SR2.Error_UnexpectedArgumentType, typeof(Activity).FullName));
            }

            return (dependencyObject as DependencyObject).GetValue(ReceiveActivity.WorkflowServiceAttributesProperty);
        }

        public static void SetWorkflowServiceAttributes(object dependencyObject,
            object value)
        {
            if (dependencyObject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dependencyObject");
            }
            if (!(dependencyObject is Activity))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
                    "dependencyObject",
                    SR2.GetString(SR2.Error_UnexpectedArgumentType, typeof(Activity).FullName));
            }

            (dependencyObject as DependencyObject).SetValue(ReceiveActivity.WorkflowServiceAttributesProperty, value);
        }

        void IActivityEventListener<QueueEventArgs>.OnEvent(object sender,
            QueueEventArgs e)
        {
            if (sender == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sender");
            }

            if (e == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("e");
            }

            ActivityExecutionContext executionContext = sender as ActivityExecutionContext;
            if (executionContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new ArgumentException(SR2.GetString(SR2.Error_ArgumentTypeInvalid,
                    "sender",
                    typeof(ActivityExecutionContext))));
            }

            WorkflowQueuingService queuingService = executionContext.GetService<WorkflowQueuingService>();
            if (queuingService == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.General_MissingService,
                    typeof(WorkflowQueuingService))));
            }

            WorkflowQueue workflowQueue = queuingService.GetWorkflowQueue(e.QueueName);
            if (workflowQueue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_QueueNotFound, e.QueueName)));
            }

            if (workflowQueue.Count != 0)
            {
                WorkflowRequestContext requestContext = workflowQueue.Peek() as WorkflowRequestContext;
                if (requestContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.Error_RequestContextUnavailable,
                        this.QualifiedName)));
                }
                if (ValidationShim.EvaluateSecurityConstraints(executionContext, this, requestContext))
                {
                    workflowQueue.UnregisterForQueueItemAvailable(this);
                    this.RequestContext = workflowQueue.Dequeue() as WorkflowRequestContext;
                    CacheRequestContext(this.RequestContext);

                    if (this.QueueInitializationMode == QueueInitializationMode.Standalone)
                    {
                        if (this.securityShim != null)
                        {
                            workflowQueue.UnregisterForQueueItemArrived(this.securityShim);
                            this.securityShim = null;
                        }
                        workflowQueue.Enabled = false;
                    }

                    if (this.RequestContext == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException(SR2.GetString(SR2.Error_RequestContextUnavailable, this.QualifiedName)));
                    }

                    if (ExecuteActivity(this.RequestContext, executionContext) == ActivityExecutionStatus.Closed)
                    {
                        try
                        {
                            executionContext.CloseActivity();
                        }
                        finally
                        {
                            RemoveRequestContext();
                        }
                    }
                }
                else
                {
                    workflowQueue.Dequeue();

                    try
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Verbose, 0,
                            "Workflow Instance {0}, receive activity {1} - message validation failed. Message will be discarded.",
                            this.WorkflowInstanceId, this.QualifiedName);

                        requestContext.SendFault(new FaultException(SR2.GetString(SR2.SecurityCheckFailed)), null);
                    }
                    catch (CommunicationException cex)
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                            "Workflow Instance {0}, receive activity {1} - failed to send fault for rejected message. Error: {2}",
                            this.WorkflowInstanceId, this.QualifiedName, cex);
                    }
                    catch (TimeoutException tex)
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                            "Workflow Instance {0}, receive activity {1} - failed to send fault for rejected message. Error: {2}",
                            this.WorkflowInstanceId, this.QualifiedName, tex);
                    }

                    if (requestContext.ContextProperties == null ||
                        !(requestContext.ContextProperties.Keys.Contains(WellKnownContextProperties.InstanceId)))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new FaultException(SR2.GetString(SR2.Error_FailedToValidateActivatingMessage, this.WorkflowInstanceId)));
                    }
                }
            }
        }

        void IEventActivity.Subscribe(ActivityExecutionContext parentContext,
            IActivityEventListener<QueueEventArgs> parentEventHandler)
        {
            if (parentContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parentContext");
            }

            if (parentEventHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parentEventHandler");
            }

            if (this.QueueInitializationMode == QueueInitializationMode.Standalone)
            {
                this.QueueInitializationMode = QueueInitializationMode.EventDriven;
            }

            // make sure that we are getting the proper queue
            // even if that means creating a new queue
            // given our conversation context and execution context.
            //
            WorkflowQueue workflowQueue = GetWorkflowQueue(parentContext);
            if (workflowQueue != null)
            {
                if (this.QueueInitializationMode == QueueInitializationMode.EventDriven)
                {
                    workflowQueue.Enabled = true;
                }

                if (this.validationShim == null)
                {
                    this.validationShim = new ValidationShim(this, parentEventHandler);
                }
                if (this.securityShim == null)
                {
                    this.securityShim = new SecurityShim(this);
                }

                workflowQueue.RegisterForQueueItemArrived(this.securityShim);
                workflowQueue.RegisterForQueueItemAvailable(this.validationShim, this.QualifiedName);
            }

            return;
        }

        void IEventActivity.Unsubscribe(ActivityExecutionContext parentContext,
            IActivityEventListener<QueueEventArgs> parentEventHandler)
        {
            if (parentContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parentContext");
            }

            if (parentEventHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parentEventHandler");
            }

            WorkflowQueuingService queuingService = parentContext.GetService<WorkflowQueuingService>();
            if (queuingService == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.General_MissingService,
                    typeof(WorkflowQueuingService))));
            }

            // get the queue using the queue name
            // at this point the conversation context should have been re-initialized if necessary
            //            
            WorkflowQueue workflowQueue = queuingService.GetWorkflowQueue(((IEventActivity)this).QueueName);
            if (workflowQueue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_QueueNotFound,
                    ((IEventActivity)this).QueueName)));
            }

            if (this.securityShim != null)
            {
                workflowQueue.UnregisterForQueueItemArrived(this.securityShim);
                this.securityShim = null;
            }
            if (this.validationShim != null)
            {
                workflowQueue.UnregisterForQueueItemAvailable(this.validationShim);
            }

            if (this.QueueInitializationMode == QueueInitializationMode.EventDriven)
            {
                workflowQueue.Enabled = false;
            }

            return;
        }

        [SuppressMessage("Microsoft.Security", "CA2103")] // Review imperative security, because constructing PrincipalPermission
        void IServiceDescriptionBuilder.BuildServiceDescription(ServiceDescriptionContext context)
        {
            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (!this.Enabled)
            {
                return;
            }

            OperationInfoBase serviceOperationInfo = this.ServiceOperationInfo;
            if (serviceOperationInfo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_ServiceOperationInfoNotSpecified, this.Name)));
            }

            // set the workflow service behavior
            //
            IServiceDescriptionBuilder serviceAttributes =
                GetWorkflowServiceAttributes(this.RootActivity) as IServiceDescriptionBuilder;

            if (serviceAttributes != null)
            {
                serviceAttributes.BuildServiceDescription(context);
            }

            if (context.ReflectedContracts == null || context.WorkflowOperationBehaviors == null)
            {
                return;
            }

            // add contract types and configure the operation behavior
            //
            Type contractType = serviceOperationInfo.GetContractType(((IComponent)this).Site);

            List<Type> interfaces = ServiceOperationHelpers.GetContracts(contractType);
            for (int i = 0; i < interfaces.Count; i++)
            {
                Type interfaceType = interfaces[i];
                ContractDescription contractDescription = null;

                if (!context.ReflectedContracts.Contains(interfaceType))
                {
                    contractDescription = ContractDescription.GetContract(interfaceType);
                    ServiceOperationHelpers.SetWorkflowOperationBehavior(contractDescription, context);

                    context.Contracts.Add(contractDescription.ConfigurationName, contractDescription);
                    context.ReflectedContracts.Add(contractDescription.ContractType);
                }
                else
                {
                    contractDescription = context.Contracts[ContractDescription.GetContract(interfaceType).ConfigurationName];
                }

                Collection<ContractDescription> inheritedContractDescriptions = contractDescription.GetInheritedContracts();
                for (int j = 0; j < inheritedContractDescriptions.Count; j++)
                {
                    ContractDescription inheritedContractDescription = inheritedContractDescriptions[j];
                    if (!context.ReflectedContracts.Contains(inheritedContractDescription.ContractType))
                    {
                        ServiceOperationHelpers.SetWorkflowOperationBehavior(inheritedContractDescription, context);

                        context.Contracts.Add(inheritedContractDescription.ConfigurationName, inheritedContractDescription);
                        context.ReflectedContracts.Add(inheritedContractDescription.ContractType);
                    }
                }
            }

            Type operationDeclaringType = null;
            MethodInfo methodInfo = serviceOperationInfo.GetMethodInfo(((IComponent)this).Site);
            if (methodInfo != null)
            {
                operationDeclaringType = methodInfo.DeclaringType;
            }

            if (operationDeclaringType != null)
            {
                WorkflowOperationBehavior behavior = null;
                KeyValuePair<Type, string> operationKey =
                    new KeyValuePair<Type, string>(operationDeclaringType, serviceOperationInfo.Name);

                if (context.WorkflowOperationBehaviors.TryGetValue(operationKey, out behavior) && behavior != null)
                {
                    if (!behavior.CanCreateInstance && this.CanCreateInstance)
                    {
                        behavior.CanCreateInstance = true;
                    }

                    if (!string.IsNullOrEmpty(serviceOperationInfo.PrincipalPermissionRole)
                        || !string.IsNullOrEmpty(serviceOperationInfo.PrincipalPermissionName))
                    {
                        if (behavior.ServiceAuthorizationManager == null)
                        {
                            PrincipalPermission permission =
                                new PrincipalPermission(serviceOperationInfo.PrincipalPermissionName,
                                serviceOperationInfo.PrincipalPermissionRole, true);

                            PrincipalPermissionServiceAuthorizationManager authManager
                                = new PrincipalPermissionServiceAuthorizationManager(permission);

                            behavior.ServiceAuthorizationManager = authManager;
                        }
                    }
                }
            }
        }

        protected internal override void Initialize(IServiceProvider provider)
        {
            if (provider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("provider");
            }

            ContextToken.Register(this, this.WorkflowInstanceId);

            SetQueueInitializationMode();

            // make sure that we are getting the proper queue
            // even if that means creating a new queue
            // given our conversation context and execution context.
            //
            WorkflowQueue workflowQueue = GetWorkflowQueue(provider);
            if (workflowQueue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_QueueNotFound,
                    ((IEventActivity)this).QueueName)));
            }

            if (this.QueueInitializationMode == QueueInitializationMode.StateMachine)
            {
                workflowQueue.Enabled = true;
            }

            base.Initialize(provider);
        }

        internal void GetParameterPropertyDescriptors(IDictionary properties)
        {
            if (properties == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("properties");
            }

            if (((IComponent)this).Site == null)
            {
                return;
            }

            OperationInfoBase serviceOperationInfo = this.ServiceOperationInfo;
            if (serviceOperationInfo != null)
            {
                MethodInfo methodInfo = serviceOperationInfo.GetMethodInfo(((IComponent)this).Site);
                if (methodInfo != null)
                {
                    ArrayList paramInfo = new ArrayList(methodInfo.GetParameters());
                    if (!(methodInfo.ReturnType == typeof(void)))
                    {
                        paramInfo.Add(methodInfo.ReturnParameter);
                    }

                    foreach (ParameterInfo param in paramInfo)
                    {
                        if (param.ParameterType != null)
                        {
                            PropertyDescriptor prop =
                                new ParameterInfoBasedPropertyDescriptor(typeof(ReceiveActivity),
                                param, true, DesignOnlyAttribute.Yes);

                            properties[prop.Name] = prop;
                        }
                    }
                }
            }
        }

        protected override ActivityExecutionStatus Cancel(ActivityExecutionContext executionContext)
        {
            try
            {
                if (executionContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("executionContext");
                }

                WorkflowQueuingService queuingService = executionContext.GetService<WorkflowQueuingService>();
                if (queuingService == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.General_MissingService,
                        typeof(WorkflowQueuingService))));
                }

                WorkflowQueue workflowQueue = GetWorkflowQueue(executionContext);
                if (workflowQueue == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.Error_QueueNotFound,
                        ((IEventActivity)this).QueueName)));
                }

                workflowQueue.UnregisterForQueueItemAvailable(this);

                if (this.QueueInitializationMode == QueueInitializationMode.Standalone)
                {
                    if (this.securityShim != null)
                    {
                        workflowQueue.UnregisterForQueueItemArrived(this.securityShim);
                        this.securityShim = null;
                    }
                    workflowQueue.Enabled = false;
                }
            }
            finally
            {
                RemoveRequestContext();
            }

            return base.Cancel(executionContext);
        }

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            if (executionContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("executionContext");
            }

            WorkflowQueuingService queuingService = executionContext.GetService<WorkflowQueuingService>();
            if (queuingService == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.General_MissingService,
                    typeof(WorkflowQueuingService))));
            }

            // make sure that we are getting the proper queue
            // even if that means creating a new queue
            // given our conversation context and execution context.
            //
            WorkflowQueue workflowQueue = GetWorkflowQueue(executionContext);
            if (workflowQueue == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_QueueNotFound,
                    ((IEventActivity)this).QueueName)));
            }

            if (this.QueueInitializationMode == QueueInitializationMode.Standalone && workflowQueue.Count == 0)
            {
                workflowQueue.Enabled = true;

                if (this.securityShim == null)
                {
                    this.securityShim = new SecurityShim(this);
                }
                workflowQueue.RegisterForQueueItemArrived(this.securityShim);
                workflowQueue.RegisterForQueueItemAvailable(this, this.QualifiedName);
                return ActivityExecutionStatus.Executing;
            }
            else if (workflowQueue.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_RequestContextUnavailable,
                    this.QualifiedName)));
            }

            WorkflowRequestContext requestContext = workflowQueue.Dequeue() as WorkflowRequestContext;

            if (requestContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_RequestContextUnavailable,
                    this.QualifiedName)));
            }
            else
            {
                if (this.validationShim != null)
                {
                    this.RequestContext = requestContext;
                    CacheRequestContext(requestContext);
                }
                else if (ValidationShim.EvaluateSecurityConstraints(executionContext, this, requestContext) == true)
                {
                    this.RequestContext = requestContext;
                    CacheRequestContext(requestContext);

                    if (this.QueueInitializationMode == QueueInitializationMode.Standalone)
                    {
                        workflowQueue.Enabled = false;
                    }
                }
                else
                {
                    try
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Verbose, 0,
                            "Workflow Instance {0}, receive activity {1} - message validation failed. Message will be discarded.",
                            this.WorkflowInstanceId, this.QualifiedName);

                        requestContext.SendFault(new FaultException(SR2.GetString(SR2.SecurityCheckFailed)), null);
                    }
                    catch (CommunicationException cex)
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                            "Workflow Instance {0}, receive activity {1} - failed to send fault for rejected message. Error: {2}",
                            this.WorkflowInstanceId, this.QualifiedName, cex);
                    }
                    catch (TimeoutException tex)
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                            "Workflow Instance {0}, receive activity {1} - failed to send fault for rejected message. Error: {2}",
                            this.WorkflowInstanceId, this.QualifiedName, tex);
                    }

                    if (requestContext.ContextProperties == null ||
                        !(requestContext.ContextProperties.Keys.Contains(WellKnownContextProperties.InstanceId)))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new FaultException(SR2.GetString(SR2.Error_FailedToValidateActivatingMessage, this.WorkflowInstanceId)));
                    }

                    if (this.QueueInitializationMode == QueueInitializationMode.Standalone)
                    {
                        if (this.securityShim == null)
                        {
                            this.securityShim = new SecurityShim(this);
                        }
                        workflowQueue.RegisterForQueueItemArrived(this.securityShim);
                    }

                    workflowQueue.RegisterForQueueItemAvailable(this, this.QualifiedName);
                    return ActivityExecutionStatus.Executing;
                }
            }

            return ExecuteActivity(this.RequestContext, executionContext);
        }

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
            Justification = "Supress any exceptions thrown by SendFault to avoid calling HandleFault infinitely.")]
        protected override ActivityExecutionStatus HandleFault(ActivityExecutionContext executionContext,
            Exception exception)
        {
            try
            {
                if (executionContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("executionContext");
                }

                if (exception == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exception");
                }

                if (executionContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("executionContext");
                }

                WorkflowQueuingService queuingService = executionContext.GetService<WorkflowQueuingService>();
                if (queuingService == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.General_MissingService,
                        typeof(WorkflowQueuingService))));
                }

                WorkflowQueue workflowQueue = GetWorkflowQueue(executionContext);
                if (workflowQueue == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.Error_QueueNotFound,
                        ((IEventActivity)this).QueueName)));
                }

                workflowQueue.UnregisterForQueueItemAvailable(this);

                if (this.QueueInitializationMode == QueueInitializationMode.Standalone)
                {
                    if (this.securityShim != null)
                    {
                        workflowQueue.UnregisterForQueueItemArrived(this.securityShim);
                        this.securityShim = null;
                    }
                    workflowQueue.Enabled = false;
                }

                RestoreRequestContext();

                if (this.RequestContext != null)
                {
                    System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Verbose, 0,
                         "Workflow Instance {0}, receive activity {1} - sending fault response message",
                         this.WorkflowInstanceId, this.QualifiedName);

                    if (this.FaultMessage != null)
                    {
                        try
                        {
                            this.RequestContext.SendFault(this.FaultMessage, null);
                        }
                        catch
                        {
                            System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                                "Workflow Instance {0}, receive activity {1} - failed to send response fault message.",
                                this.WorkflowInstanceId, this.QualifiedName);
                        }
                    }
                    else
                    {
                        try
                        {
                            this.RequestContext.SendFault(exception, null);
                        }
                        catch
                        {
                            System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                                "Workflow Instance {0}, receive activity {1} - failed to send response fault message.",
                                this.WorkflowInstanceId, this.QualifiedName);
                        }
                    }
                }
            }
            finally
            {
                RemoveRequestContext();
            }

            return base.HandleFault(executionContext, exception);
        }

        protected override void InitializeProperties()
        {
            OperationInfoBase serviceOperationInfo = this.ServiceOperationInfo;

            if (serviceOperationInfo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_ServiceOperationInfoNotSpecified, this.Name)));
            }

            OperationParameterInfoCollection parameters = null;

            Activity definitionRoot = base.RootActivity.GetValue(Activity.WorkflowDefinitionProperty) as Activity;
            if (definitionRoot != null)
            {
                ReceiveActivity definition = definitionRoot.GetActivityByName(this.QualifiedName, true) as ReceiveActivity;
                if ((definition != null) && definition.UserData.Contains(typeof(OperationParameterInfoCollection)))
                {
                    parameters = definition.UserData[typeof(OperationParameterInfoCollection)] as OperationParameterInfoCollection;
                }
            }

            if (parameters == null)
            {
                parameters = serviceOperationInfo.GetParameters(this.Site);
                this.UserData[typeof(OperationParameterInfoCollection)] = parameters;
            }

            WorkflowParameterBindingCollection bindings = this.ParameterBindings;

            foreach (OperationParameterInfo parameter in parameters)
            {
                if (!bindings.Contains(parameter.Name))
                {
                    bindings.Add(new WorkflowParameterBinding(parameter.Name));
                }
            }

            base.InitializeProperties();
        }

        protected override void OnSequenceComplete(ActivityExecutionContext executionContext)
        {
            if (executionContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("executionContext");
            }

            try
            {
                RestoreRequestContext();
                if (this.RequestContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.Error_RequestContextUnavailable,
                        this.QualifiedName)));
                }

                object returnValue;
                object[] outputValues;

                if (this.FaultMessage != null)
                {
                    System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Verbose, 0,
                        "Workflow Instance {0}, receive activity {1} - sending fault response message",
                        this.WorkflowInstanceId, this.QualifiedName);

                    try
                    {
                        this.RequestContext.SendFault(this.FaultMessage, null);
                    }
                    catch (CommunicationException cex)
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                            "Workflow Instance {0}, receive activity {1} - failed to send fault response message. Error: {2}",
                            this.WorkflowInstanceId, this.QualifiedName, cex);
                        throw;
                    }
                    catch (TimeoutException tex)
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                            "Workflow Instance {0}, receive activity {1} - failed to send fault response message. Error: {2}",
                            this.WorkflowInstanceId, this.QualifiedName, tex);
                        throw;
                    }
                }
                else if (!this.OperationHelper.IsOneWay)
                {
                    returnValue = this.OperationHelper.GetOutputs(this, out outputValues);

                    System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Verbose, 0,
                        "Workflow Instance {0}, receive activity {1} - sending response message",
                        this.WorkflowInstanceId, this.QualifiedName);

                    try
                    {
                        this.RequestContext.SendReply(returnValue, outputValues, null);
                    }
                    catch (CommunicationException cex)
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                            "Workflow Instance {0}, receive activity {1} - failed to send response message. Error: {2}",
                            this.WorkflowInstanceId, this.QualifiedName, cex);
                        throw;
                    }
                    catch (TimeoutException tex)
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                            "Workflow Instance {0}, receive activity {1} - failed to send response message. Error: {2}",
                            this.WorkflowInstanceId, this.QualifiedName, tex);
                        throw;
                    }
                }
                else
                {
                    System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Verbose, 0,
                        "Workflow Instance {0}, receive activity {1} - completing one way operation",
                        this.WorkflowInstanceId, this.QualifiedName);

                    this.RequestContext.SetOperationCompleted();
                }

                base.OnSequenceComplete(executionContext);

                // Null out the request context to reduce serialization size of the activity.
                this.RequestContext = null;
            }
            finally
            {
                RemoveRequestContext();
            }
        }

        static object GetWorkflowServiceAttributesValueOverride(object dependencyObject)
        {
            if (dependencyObject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dependencyObject");
            }

            if (!(dependencyObject is Activity))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
                    "dependencyObject",
                    SR2.GetString(SR2.Error_UnexpectedArgumentType, typeof(Activity).FullName));
            }

            Activity activity = dependencyObject as Activity;

            if (activity.GetValueBase(ReceiveActivity.WorkflowServiceAttributesProperty) == null)
            {
                if (activity.DesignMode)
                {
                    WorkflowServiceAttributes workflowServiceAttribsValue = new WorkflowServiceAttributes();
                    Activity rootActivity = activity.RootActivity;
                    if (rootActivity != null)
                    {
                        string fullClassName = (String)rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty);
                        if (!String.IsNullOrEmpty(fullClassName))
                        {
                            string namespaceName;
                            string className;
                            Helpers.GetNamespaceAndClassName(fullClassName, out namespaceName, out className);
                            workflowServiceAttribsValue.ConfigurationName = fullClassName;
                            workflowServiceAttribsValue.Name = className;
                        }
                    }
                    activity.SetValue(ReceiveActivity.WorkflowServiceAttributesProperty, workflowServiceAttribsValue);
                    return workflowServiceAttribsValue;
                }
            }
            return activity.GetValueBase(ReceiveActivity.WorkflowServiceAttributesProperty);
        }

        private ActivityExecutionStatus ExecuteActivity(WorkflowRequestContext requestContext,
            ActivityExecutionContext executionContext)
        {
            if (requestContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestContext");
            }

            if (executionContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("executionContext");
            }

            System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Verbose, 0,
                "Workflow Instance {0}, receive activity {1} - received message",
                this.WorkflowInstanceId, this.QualifiedName);

            this.OperationHelper.PopulateInputs(this, requestContext.Inputs);

            return base.Execute(executionContext);
        }

        private WorkflowQueue GetWorkflowQueue(IServiceProvider provider)
        {
            if (provider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("provider");
            }

            if (this.ServiceOperationInfo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.Error_ServiceOperationInfoNotSpecified, this.Name)));
            }

            WorkflowQueuingService queuingService =
                provider.GetService(typeof(WorkflowQueuingService)) as WorkflowQueuingService;

            if (queuingService == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidOperationException(SR2.GetString(SR2.General_MissingService,
                    typeof(WorkflowQueuingService))));
            }

            WorkflowQueue workflowQueue = null;
            string queueName = this.OperationHelper.GetWorkflowQueueName(this.Context);
            this.SetValue(QueueNameProperty, queueName);

            if (!queuingService.Exists(queueName))
            {
                workflowQueue = queuingService.CreateWorkflowQueue(queueName, false);
                workflowQueue.Enabled = false;
            }
            else
            {
                workflowQueue = queuingService.GetWorkflowQueue(queueName);
            }

            return workflowQueue;
        }

        private void SetQueueInitializationMode()
        {
            if (this.parent != null && this.parent is EventDrivenActivity)
            {
                if (this.parent.parent != null && this.parent.parent is StateActivity)
                {
                    this.QueueInitializationMode = QueueInitializationMode.StateMachine;
                }
            }
        }

        private void CacheRequestContext(WorkflowRequestContext requestContext)
        {
            string keyValue = WorkflowEnvironment.WorkflowInstanceId.ToString() + ":" +
                this.GetValue(ReceiveActivity.QueueNameProperty) as string;
            requestContextsCache[keyValue] = requestContext;
            this.isContextCached = true;
        }

        private void RestoreRequestContext()
        {
            string keyValue = WorkflowEnvironment.WorkflowInstanceId.ToString() + ":"
                + this.GetValue(ReceiveActivity.QueueNameProperty) as string;
            if (requestContextsCache.ContainsKey(keyValue))
            {
                this.RequestContext = requestContextsCache[keyValue] as WorkflowRequestContext;
            }
        }

        private void RemoveRequestContext()
        {
            requestContextsCache.Remove(WorkflowEnvironment.WorkflowInstanceId.ToString() + ":" +
                this.GetValue(ReceiveActivity.QueueNameProperty) as string);
        }

        protected override void Dispose(bool disposing)
        {
            try
            {
                if (disposing && this.isContextCached)
                {
                    RemoveRequestContext();
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }

        [Serializable]
        class ReceiveOperationInfoHelper
        {
            string baseQueueName;
            bool hasReturnValue = false;
            IList<KeyValuePair<int, string>> inputParameters;
            bool isOneWay = false;
            IDictionary<int, Type> notNullableParameters;
            bool nullableReturnValue = true;
            string operationName;
            IList<KeyValuePair<int, string>> outputParameters;
            string returnTypeName;

            public ReceiveOperationInfoHelper(IServiceProvider serviceProvider, ReceiveActivity activity)
            {
                outputParameters = new List<KeyValuePair<int, string>>();
                inputParameters = new List<KeyValuePair<int, string>>();
                notNullableParameters = new Dictionary<int, Type>();
                hasReturnValue = false;
                nullableReturnValue = true;

                if (activity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity");
                }

                OperationInfoBase serviceOperationInfo = activity.ServiceOperationInfo;
                if (serviceOperationInfo == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.Error_ServiceOperationInfoNotSpecified, activity.Name)));
                }

                MethodInfo methodInfo = serviceOperationInfo.GetMethodInfo(serviceProvider);
                if (methodInfo == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.Error_MethodInfoNotAvailable, activity.Name)));
                }

                if (methodInfo.ReturnType != null && methodInfo.ReturnType != typeof(void))
                {
                    hasReturnValue = true;
                    this.returnTypeName = methodInfo.ReturnType.FullName;
                    nullableReturnValue =
                        !((methodInfo.ReturnType.IsPrimitive || methodInfo.ReturnType.IsEnum || methodInfo.ReturnType.IsValueType) && !ServiceOperationHelpers.IsNullableType(methodInfo.ReturnType));
                }

                foreach (ParameterInfo parameter in methodInfo.GetParameters())
                {
                    if (parameter.ParameterType.IsByRef ||
                        parameter.IsOut || (parameter.IsIn && parameter.IsOut))
                    {
                        outputParameters.Add(new KeyValuePair<int, string>(parameter.Position, parameter.Name));

                        if (parameter.ParameterType.IsByRef &&
                            parameter.ParameterType.GetElementType().IsValueType &&
                            !ServiceOperationHelpers.IsNullableType(parameter.ParameterType))
                        {
                            notNullableParameters.Add(parameter.Position, parameter.ParameterType);
                        }
                    }

                    if (!parameter.IsOut || (parameter.IsIn && parameter.IsOut))
                    {
                        inputParameters.Add(new KeyValuePair<int, string>(parameter.Position, parameter.Name));
                    }
                }

                this.operationName = serviceOperationInfo.Name;

                this.baseQueueName = QueueNameHelper.Create(methodInfo.DeclaringType, this.operationName);

                object[] operationContractAttribs = methodInfo.GetCustomAttributes(typeof(OperationContractAttribute), true);

                if (operationContractAttribs != null && operationContractAttribs.Length > 0)
                {
                    if (operationContractAttribs[0] is OperationContractAttribute)
                    {
                        this.isOneWay = ((OperationContractAttribute)operationContractAttribs[0]).IsOneWay;
                    }
                }

            }

            public bool IsOneWay
            {
                get
                {
                    return this.isOneWay;
                }
            }

            public object GetOutputs(ReceiveActivity activity, out object[] outputs)
            {
                if (activity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity");
                }

                outputs = new object[outputParameters.Count];
                object returnValue = null;

                WorkflowParameterBindingCollection bindings = activity.ParameterBindings;

                for (int index = 0; index < outputParameters.Count; ++index)
                {
                    KeyValuePair<int, string> parameterInfo = outputParameters[index];
                    if (bindings[parameterInfo.Value].Value == null &&
                        this.notNullableParameters.Keys.Contains(parameterInfo.Key))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException(SR2.GetString(SR2.Error_ReceiveActivityInvalidParameterValue,
                            activity.Name, parameterInfo.Value, this.notNullableParameters[parameterInfo.Key])));
                    }

                    outputs[index] = bindings[parameterInfo.Value].Value;
                }

                if (hasReturnValue)
                {
                    if (bindings["(ReturnValue)"].Value == null &&
                        !this.nullableReturnValue)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException(SR2.GetString(SR2.Error_ReceiveActivityInvalidReturnValue,
                            activity.Name, this.returnTypeName)));
                    }

                    returnValue = bindings["(ReturnValue)"].Value;
                }

                return returnValue;
            }

            public string GetWorkflowQueueName(IDictionary<string, string> context)
            {
                return QueueNameHelper.Create(this.baseQueueName, context);
            }

            public void PopulateInputs(ReceiveActivity activity, ReadOnlyCollection<object> inputs)
            {
                if (activity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activity");
                }

                if (inputs == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("inputs");
                }

                WorkflowParameterBindingCollection bindings = activity.ParameterBindings;

                for (int index = 0; index < inputParameters.Count; index++)
                {
                    KeyValuePair<int, string> parameterInfo = inputParameters[index];

                    if (!bindings.Contains(parameterInfo.Value))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException(SR2.GetString(SR2.Error_ParameterBindingMissing,
                            parameterInfo.Value,
                            this.operationName,
                            activity.Name)));
                    }
                    if (index >= inputs.Count)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException(SR2.GetString(SR2.Error_InputValueUnavailable,
                            parameterInfo.Value,
                            this.operationName,
                            activity.Name)));
                    }

                    WorkflowParameterBinding parameterBinding = bindings[parameterInfo.Value];
                    parameterBinding.Value = inputs[index];
                }
            }
        }

        [Serializable]
        class SecurityShim : IActivityEventListener<QueueEventArgs>, IDisposable
        {
            ReceiveActivity receiveActivity;

            internal SecurityShim(ReceiveActivity receiveActivity)
            {
                if (receiveActivity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("receiveActivity");
                }

                this.receiveActivity = receiveActivity;
            }

            void IActivityEventListener<QueueEventArgs>.OnEvent(object sender, QueueEventArgs queueEventArgs)
            {
                if (sender == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sender");
                }

                if (queueEventArgs == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("queueEventArgs");
                }

                WorkflowQueue workflowQueue = sender as WorkflowQueue;
                if (workflowQueue == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new ArgumentException(SR2.GetString(SR2.Error_ArgumentTypeInvalid, "sender", typeof(WorkflowQueue))));
                }

                WorkflowRequestContext requestContext = workflowQueue.Peek() as WorkflowRequestContext;
                if (requestContext != null)
                {
                    IDependencyObjectAccessor doa = (IDependencyObjectAccessor)receiveActivity;
                    EventHandler<OperationValidationEventArgs>[] eventHandlers =
                        doa.GetInvocationList<EventHandler<OperationValidationEventArgs>>(
                        ReceiveActivity.OperationValidationEvent);

                    if (eventHandlers != null && eventHandlers.Length > 0)
                    {
                        requestContext.PopulateAuthorizationState();
                    }
                }
            }

            void IDisposable.Dispose()
            {
                this.receiveActivity.Dispose();
                GC.SuppressFinalize(this);
            }
        }

        [Serializable]
        class ValidationShim : IActivityEventListener<QueueEventArgs>, IDisposable
        {
            IActivityEventListener<QueueEventArgs> activityEventListener;
            ReceiveActivity receiveActivity;

            internal ValidationShim(ReceiveActivity receiveActivity, IActivityEventListener<QueueEventArgs> activityEventListener)
            {
                if (receiveActivity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("receiveActivity");
                }

                if (activityEventListener == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("activityEventListener");
                }

                this.receiveActivity = receiveActivity;
                this.activityEventListener = activityEventListener;
            }

            void IActivityEventListener<QueueEventArgs>.OnEvent(object sender, QueueEventArgs queueEventArgs)
            {
                if (sender == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("sender");
                }

                if (queueEventArgs == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("queueEventArgs");
                }

                ActivityExecutionContext executionContext = sender as ActivityExecutionContext;
                if (executionContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new ArgumentException(SR2.GetString(SR2.Error_ArgumentTypeInvalid, "sender", typeof(ActivityExecutionContext))));
                }

                WorkflowQueuingService queuingService = executionContext.GetService<WorkflowQueuingService>();
                if (queuingService == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.General_MissingService, typeof(WorkflowQueuingService))));
                }

                WorkflowQueue workflowQueue = queuingService.GetWorkflowQueue(queueEventArgs.QueueName);
                if (workflowQueue == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.Error_QueueNotFound, queueEventArgs.QueueName)));
                }

                WorkflowRequestContext requestContext = workflowQueue.Peek() as WorkflowRequestContext;
                if (requestContext != null)
                {
                    if (EvaluateSecurityConstraints(executionContext, this.receiveActivity, requestContext) == true)
                    {
                        this.activityEventListener.OnEvent(sender, queueEventArgs);
                    }
                    else
                    {
                        System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Verbose, 0,
                            "Workflow Instance {0}, receive activity {1} - message validation failed. Message will be discarded.",
                            this.receiveActivity.WorkflowInstanceId, this.receiveActivity.QualifiedName);

                        workflowQueue.Dequeue();
                        try
                        {
                            requestContext.SendFault(new FaultException(SR2.GetString(SR2.SecurityCheckFailed)), null);
                        }
                        catch (CommunicationException cex)
                        {
                            System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                                "Workflow Instance {0}, receive activity {1} - failed to send fault for rejected message. Error: {2}",
                                this.receiveActivity.WorkflowInstanceId, this.receiveActivity.QualifiedName, cex);
                        }
                        catch (TimeoutException tex)
                        {
                            System.Workflow.Runtime.WorkflowTrace.Runtime.TraceEvent(TraceEventType.Error, 0,
                                "Workflow Instance {0}, receive activity {1} - failed to send fault for rejected message. Error: {2}",
                                this.receiveActivity.WorkflowInstanceId, this.receiveActivity.QualifiedName, tex);
                        }

                        if (requestContext.ContextProperties == null ||
                            !(requestContext.ContextProperties.Keys.Contains(WellKnownContextProperties.InstanceId)))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                new FaultException(SR2.GetString(SR2.Error_FailedToValidateActivatingMessage, this.receiveActivity.WorkflowInstanceId)));
                        }
                    }
                }
                else
                {
                    this.activityEventListener.OnEvent(sender, queueEventArgs);
                }
            }

            void IDisposable.Dispose()
            {
                this.receiveActivity.Dispose();
                GC.SuppressFinalize(this);
            }

            internal static bool EvaluateSecurityConstraints(IServiceProvider serviceProvider, ReceiveActivity receiveActivity, WorkflowRequestContext requestContext)
            {
                bool retVal = true;

                if (serviceProvider == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceProvider");
                }

                if (receiveActivity == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("receiveActivity");
                }

                if (requestContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestContext");
                }

                IDependencyObjectAccessor doa = (IDependencyObjectAccessor)receiveActivity;
                EventHandler<OperationValidationEventArgs>[] eventHandlers =
                    doa.GetInvocationList<EventHandler<OperationValidationEventArgs>>(
                    ReceiveActivity.OperationValidationEvent);

                if (eventHandlers != null && eventHandlers.Length > 0)
                {
                    ReadOnlyCollection<ClaimSet> claims = requestContext.AuthorizationContext == null ?
                        new ReadOnlyCollection<ClaimSet>(new List<ClaimSet>()) :
                        requestContext.AuthorizationContext.ClaimSets;
                    OperationValidationEventArgs e = new OperationValidationEventArgs(claims);
                    receiveActivity.RaiseGenericEvent(ReceiveActivity.OperationValidationEvent,
                        receiveActivity, e);
                    retVal = e.IsValid;
                }

                return retVal;
            }
        }
    }
}