File: InternalSendMessage.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (3298 lines) | stat: -rw-r--r-- 140,930 bytes parent folder | download
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
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------

namespace System.ServiceModel.Activities
{
    using System;
    using System.Activities;
    using System.Activities.Statements;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Runtime;
    using System.Runtime.Collections;
    using System.Runtime.Diagnostics;
    using System.Security.Principal;
    using System.ServiceModel;
    using System.Runtime.Serialization;
    using System.ServiceModel.Activities.Description;
    using System.ServiceModel.Activities.Dispatcher;
    using System.ServiceModel.Activities.Tracking;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Diagnostics;
    using System.Transactions;
    using System.Xaml;
    using System.Xml.Linq;
    using System.Runtime.DurableInstancing;
    using System.Security;

    // InternalSendMessage encapsulates both the server and client send.  For the server
    // send it provides the ability to persist after correlations have been initialized
    // but before the send has actually been completed by the channel stack.  This is not
    // supported by client send.

    class InternalSendMessage : NativeActivity
    {
        static string runtimeTransactionHandlePropertyName = typeof(RuntimeTransactionHandle).FullName;

        // Explicit correlation OM
        Collection<CorrelationInitializer> correlationInitializers;
        Collection<CorrelationQuery> replyCorrelationQueries;

        ICollection<CorrelationQuery> correlationQueries;

        MessageVersion messageVersion;

        ContractDescription cachedContract;
        ServiceEndpoint cachedServiceEndpoint;
        AddressHeaderCollection cachedEndpointHeaderCollection;
        FactoryCacheKey cachedFactoryCacheKey;
        bool isConfigSettingsSecure;
        bool configVerified;

        KeyValuePair<ObjectCacheItem<ChannelFactoryReference>, SendMessageChannelCache> lastUsedFactoryCacheItem;


        // this will be scheduled if ShouldPersistBeforeSend is set to true
        Activity persist;

        WaitOnChannelCorrelation channelCorrelationCompletionWaiter;
        Variable<VolatileSendMessageInstance> sendMessageInstance;
        Variable<NoPersistHandle> noPersistHandle;
        Variable<Bookmark> extensionSendCompleteBookmark;
        Variable<Guid> e2eActivityId;

        OpenChannelFactory openChannelFactory;
        OpenChannelAndSendMessage openChannelAndSendMessage;

        FaultCallback onSendFailure;

        public InternalSendMessage()
        {
            this.TokenImpersonationLevel = TokenImpersonationLevel.Identification;

            this.sendMessageInstance = new Variable<VolatileSendMessageInstance>();
            this.channelCorrelationCompletionWaiter = new WaitOnChannelCorrelation { Instance = this.sendMessageInstance };

            this.noPersistHandle = new Variable<NoPersistHandle>();
            this.extensionSendCompleteBookmark = new Variable<Bookmark>();
            this.e2eActivityId = new Variable<Guid>();

            this.openChannelFactory = new OpenChannelFactory { Instance = this.sendMessageInstance };
            this.openChannelAndSendMessage = new OpenChannelAndSendMessage { Instance = this.sendMessageInstance, InternalSendMessage = this, };
        }

        public TokenImpersonationLevel TokenImpersonationLevel
        {
            get;
            set;
        }

        // Endpoint defines the service to talk to, and endpointAddress is used to set 
        // the Uri at the runtime, such as the duplex scenario.
        public Endpoint Endpoint
        {
            get;
            set;
        }

        public string EndpointConfigurationName
        {
            get;
            set;
        }

        // This is needed for the callback case
        public InArgument<Uri> EndpointAddress
        {
            get;
            set;
        }

        public InArgument<CorrelationHandle> CorrelatesWith
        {
            get;
            set;
        }
        
        public string OperationName
        {
            get;
            set;
        }

        public string Action
        {
            get;
            set;
        }

        // cache for internal implementation. This should be set by the Send<T>
        // Should only be used in initating send. 
        // Should use this instead of OperationContract.IsOneWay
        public bool IsOneWay
        {
            get;
            set;
        }

        protected override bool CanInduceIdle
        {
            get
            {
                return true;
            }
        }

        // this flag is for Send/SendReply to indicate if we are client-side send or receive-side sendreply
        // 
        internal bool IsSendReply
        {
            get;
            set;
        }

        // Used for cleaning up the Message variable
        internal OutArgument<Message> MessageOut
        {
            get;
            set;
        }

        // should be used to decide whether persist before sending the message
        internal bool ShouldPersistBeforeSend { get; set; }

        internal string OwnerDisplayName { get; set; }

        public Collection<CorrelationInitializer> CorrelationInitializers
        {
            get
            {
                if (this.correlationInitializers == null)
                {
                    this.correlationInitializers = new Collection<CorrelationInitializer>();
                }
                return this.correlationInitializers;
            }
        }

        // This will be passed in from the parent Send activity
        public CorrelationQuery CorrelationQuery
        {
            get;
            set;
        }

        // This needs to be set by the ReceiveReply, we assume that this is unique
        internal ICollection<CorrelationQuery> ReplyCorrelationQueries
        {
            get
            {
                if (this.replyCorrelationQueries == null)
                {
                    this.replyCorrelationQueries = new Collection<CorrelationQuery>();
                }

                return this.replyCorrelationQueries;
            }
        }

        // on the serverside, the ContractName is set during ContractInference and is used for retrieving the
        // correct CorrelationQueryBehavior. ContractName on the Serverside can thus be different from what is
        // set on the OM
        public XName ServiceContractName
        {
            get;
            set;
        }

        public InArgument<Message> Message
        {
            get;
            set;
        }

        internal Send Parent
        {
            get;
            set;
        }

        internal static Guid TraceCorrelationActivityId
        {
            [Fx.Tag.SecurityNote(Critical = "Critical because Trace.CorrelationManager has a Link demand for UnmanagedCode.",
                Safe = "Safe because we aren't leaking a critical resource.")]
            [SecuritySafeCritical]
            get
            {
                return Trace.CorrelationManager.ActivityId;
            }
        }

        // we cache the ServiceEndpoint for perf reasons so that we can retrieve endpointaddress, contract etc without
        // creating a new ServiceEndpoint each time
        // Note that we should not pass the cachedServiceEndpoint to the ChannelFactory, as we need to have a 
        // distinct instance per-Factory.
        ServiceEndpoint GetCachedServiceEndpoint()
        {
            if (this.cachedServiceEndpoint == null)
            {
                this.cachedServiceEndpoint = CreateServiceEndpoint();
            }
            return this.cachedServiceEndpoint;
        }

        AddressHeaderCollection GetCachedEndpointHeaders()
        {
            Fx.Assert(this.Endpoint != null, "Endpoint should not be null");
            if (this.cachedEndpointHeaderCollection == null)
            {
                this.cachedEndpointHeaderCollection = new AddressHeaderCollection(this.Endpoint.Headers);
            }
            return this.cachedEndpointHeaderCollection;
        }

        void InitializeEndpoint(ref ServiceEndpoint serviceEndpoint, string configurationName)
        {
            ServiceEndpoint serviceEndpointFromConfig = null;

            if (configurationName != null)
            {
                // load the standard endpoint from the config
                serviceEndpointFromConfig = ConfigLoader.LookupEndpoint(configurationName, null, serviceEndpoint.Contract);
            }

            if (serviceEndpointFromConfig != null)
            {
                // standard endpoint case: it can completely override the endpoint
                serviceEndpoint = serviceEndpointFromConfig;
            }
            else
            {
                // normal endpoint case
                if (!serviceEndpoint.IsFullyConfigured)
                {
                    new ConfigLoader().LoadChannelBehaviors(serviceEndpoint, configurationName);
                }
            }
        }

        // used to create ChannelFactoryReference instances. We don't cache the serviceEndpoint 
        // directly, as we need to have a distinct instance per-Factory. So it's cached behind the 
        // scenes as part of the ChannelFactoryReference
        ServiceEndpoint CreateServiceEndpoint()
        {
            ContractDescription contract = null;
            bool ensureTransactionFlow = false;
            if (this.cachedContract == null)
            {
                contract = this.GetContractDescription();
                ensureTransactionFlow = true;
            }
            else
            {
                contract = this.cachedContract;
            }
            ServiceEndpoint result = new ServiceEndpoint(contract);
            if (this.Endpoint != null)
            {
                result.Binding = this.Endpoint.Binding;
                if (this.Endpoint.AddressUri != null)
                {
                    result.Address = new EndpointAddress(this.Endpoint.AddressUri, this.Endpoint.Identity, this.GetCachedEndpointHeaders());
                }
            }
            // Get ServiceEndpoint will be called only on the client side, hence if endpoint is null, we will try to load the config with 
            // endpointConfigurationName. 
            // endpointConfigurationName = null will be translated to endpointConfigurationName = String.Empty
            else
            {
                // we are loading the binding & the behaviors from config
                if (this.ServiceContractName != null)
                {
                    result.Contract.ConfigurationName = this.ServiceContractName.LocalName;
                }
                InitializeEndpoint(ref result, this.EndpointConfigurationName ?? string.Empty);
            }

            // if the cachedContract is null, verify if TransactionFlow is accounted for in the contract
            // if cachedContract is not null, we can skip this since the contract should be fixed for the workflow definition 
            if (ensureTransactionFlow)
            {
                EnsureTransactionFlowOnContract(ref result);
                this.cachedContract = result.Contract;
            }
            EnsureCorrelationQueryBehavior(result);

            return result;
        }

        void EnsureCorrelationQueryBehavior(ServiceEndpoint serviceEndpoint)
        {
            CorrelationQueryBehavior correlationQueryBehavior = serviceEndpoint.Behaviors.Find<CorrelationQueryBehavior>();
            if (correlationQueryBehavior == null)
            {
                // Add CorrelationQueryBehavior if either Binding has queries or if either Send or ReceiveReplies 
                // have correlation query associated with them
                if (CorrelationQueryBehavior.BindingHasDefaultQueries(serviceEndpoint.Binding)
                    || this.CorrelationQuery != null
                    || this.ReplyCorrelationQueries.Count > 0)
                {
                    correlationQueryBehavior = new CorrelationQueryBehavior(new Collection<CorrelationQuery>());
                    serviceEndpoint.Behaviors.Add(correlationQueryBehavior);
                }
            }
            if (correlationQueryBehavior != null)
            {
                // add CorrelationQuery from Send
                if (this.CorrelationQuery != null && !correlationQueryBehavior.CorrelationQueries.Contains(this.CorrelationQuery))
                {
                    correlationQueryBehavior.CorrelationQueries.Add(this.CorrelationQuery);
                }

                //add ReplyCorrelationQueries from ReceiveReply (there could be multiple ReceiveReplies for a Send and hence the collection
                foreach (CorrelationQuery query in this.ReplyCorrelationQueries)
                {
                    // Filter out duplicate CorrelationQueries in the collection.
                    // Currently, we only do reference comparison and Where message filter comparison.
                    if (!correlationQueryBehavior.CorrelationQueries.Contains(query))
                    {
                        correlationQueryBehavior.CorrelationQueries.Add(query);
                    }
                    else
                    {
                        if (TD.DuplicateCorrelationQueryIsEnabled())
                        {
                            TD.DuplicateCorrelationQuery(query.Where.ToString());
                        }
                    }
                }

                this.correlationQueries = correlationQueryBehavior.CorrelationQueries;
            }
        }

        static void EnsureCorrelationBehaviorScopeName(ActivityContext context, CorrelationQueryBehavior correlationBehavior)
        {
            Fx.Assert(correlationBehavior != null, "caller must verify");
            if (correlationBehavior.ScopeName == null)
            {
                CorrelationExtension extension = context.GetExtension<CorrelationExtension>();
                if (extension != null)
                {
                    correlationBehavior.ScopeName = extension.ScopeName;
                }
            }
        }

        void EnsureTransactionFlowOnContract(ref ServiceEndpoint serviceEndpoint)
        {
            if (!this.IsOneWay)
            {
                BindingElementCollection elementCollection = serviceEndpoint.Binding.CreateBindingElements();
                TransactionFlowBindingElement bindingElement = elementCollection.Find<TransactionFlowBindingElement>();
                bool flowTransaction = ((bindingElement != null) && (bindingElement.Transactions));
                if (flowTransaction)
                {
                    ContractInferenceHelper.EnsureTransactionFlowOnContract(ref serviceEndpoint,
                        this.ServiceContractName, this.OperationName, this.Action, this.Parent.ProtectionLevel);
                }
            }
        }

        internal MessageVersion GetMessageVersion()
        {
            if (this.messageVersion == null)
            {
                ServiceEndpoint endpoint = this.GetCachedServiceEndpoint();
                this.messageVersion = (endpoint != null && endpoint.Binding != null) ? endpoint.Binding.MessageVersion : null;
            }
            return this.messageVersion;
        }

        ContractDescription GetContractDescription()
        {
            ContractDescription cd;

            // When channel cache is disabled or when operation uses message contract,
            // we use the fully inferred description; otherwise, we use a fixed description to increase channel cache hits

            if (!this.Parent.ChannelCacheEnabled || this.Parent.OperationUsesMessageContract)
            {
                // If this is one-way send untyped message, this.OperationDescription would still be null
                if (this.Parent.OperationDescription == null)
                {
                    Fx.Assert(this.IsOneWay, "We can only reach here when we are one-way send Message!");
                    this.Parent.OperationDescription = ContractInferenceHelper.CreateOneWayOperationDescription(this.Parent);
                }

                cd = ContractInferenceHelper.CreateContractFromOperation(this.ServiceContractName, this.Parent.OperationDescription);
            }
            else
            {
                // Create ContractDescription using Fixed MessageIn/MessageOut contract
                // If IOutputChannel, we create a Contract with name IOutputChannel and OperationDescription "Send"
                // else, Contract name is IRequestChannel with OperationDescription "Request"

                if (this.IsOneWay)
                {
                    cd = ContractInferenceHelper.CreateOutputChannelContractDescription(this.ServiceContractName, this.Parent.ProtectionLevel);
                }
                else
                {
                    cd = ContractInferenceHelper.CreateRequestChannelContractDescription(this.ServiceContractName, this.Parent.ProtectionLevel);
                }
            }

            if (this.ServiceContractName != null)
            {
                cd.ConfigurationName = this.ServiceContractName.LocalName;
            }
            return cd;
        }

        EndpointAddress CreateEndpointAddress(NativeActivityContext context)
        {
            ServiceEndpoint endpoint = this.GetCachedServiceEndpoint();
            Uri endpointAddressUri = (this.EndpointAddress != null) ? this.EndpointAddress.Get(context) : null;

            if (endpoint != null && endpoint.Address != null)
            {
                return endpointAddressUri == null ?
                    endpoint.Address :
                    (new EndpointAddressBuilder(endpoint.Address) { Uri = endpointAddressUri }).ToEndpointAddress();
            }
            else if (this.Endpoint != null)
            {
                return endpointAddressUri == null ?
                    this.Endpoint.GetAddress() :
                    new EndpointAddress(endpointAddressUri, this.Endpoint.Identity, this.GetCachedEndpointHeaders());
            }
            else
            {
                return null;
            }
        }

        EndpointAddress CreateEndpointAddressFromCallback(EndpointAddress CallbackAddress)
        {
            Fx.Assert(CallbackAddress != null, "CallbackAddress cannot be null");

            EndpointIdentity endpointIdentity = null;
            AddressHeaderCollection headers = null;
            EndpointAddress endpointAddress;

            if (this.Endpoint != null)
            {
                // we honor Identity and Headers on the Endpoint OM even when the AddressUri is null
                endpointIdentity = this.Endpoint.Identity;
                headers = this.GetCachedEndpointHeaders();
            }
            else
            {
                // this could be from config
                ServiceEndpoint endpoint = this.GetCachedServiceEndpoint();
                Fx.Assert(endpoint != null, " endpoint cannot be null");
                if (endpoint.Address != null)
                {
                    endpointIdentity = endpoint.Address.Identity;
                    headers = endpoint.Address.Headers;
                }
            }

            if (endpointIdentity != null || headers != null)
            {
                Uri callbackUri = CallbackAddress.Uri;
                endpointAddress = new EndpointAddress(callbackUri, endpointIdentity, headers);
            }
            else
            {
                endpointAddress = CallbackAddress;
            }
            return endpointAddress;
        }


        bool IsEndpointSettingsSafeForCache()
        {
            if (!this.configVerified)
            {

                // let's set isConfigSettingsSecure flag to false if we use endpointConfiguration, 
                // this is used to decide if we cache factory or not

                this.isConfigSettingsSecure = this.Endpoint != null ? true : false;
                this.configVerified = true;
            }
            return this.isConfigSettingsSecure;
        }

        protected override void CacheMetadata(NativeActivityMetadata metadata)
        {
            if (ShouldPersistBeforeSend)
            {
                if (this.persist == null)
                {
                    this.persist = new Persist();
                }
                metadata.AddImplementationChild(this.persist);
            }

            RuntimeArgument endpointAddressArgument = new RuntimeArgument(Constants.EndpointAddress, Constants.UriType, ArgumentDirection.In);
            if (this.EndpointAddress == null)
            {
                this.EndpointAddress = new InArgument<Uri>();
            }
            metadata.Bind(this.EndpointAddress, endpointAddressArgument);
            metadata.AddArgument(endpointAddressArgument);

            RuntimeArgument correlatesWithArgument = new RuntimeArgument(Constants.CorrelatesWith, Constants.CorrelationHandleType, ArgumentDirection.In);
            if (this.CorrelatesWith == null)
            {
                this.CorrelatesWith = new InArgument<CorrelationHandle>();
            }
            metadata.Bind(this.CorrelatesWith, correlatesWithArgument);
            metadata.AddArgument(correlatesWithArgument);
            
            if (this.correlationInitializers != null)
            {
                int count = 0;
                foreach (CorrelationInitializer correlation in this.correlationInitializers)
                {
                    if (correlation.CorrelationHandle != null)
                    {
                        RuntimeArgument argument = new RuntimeArgument(Constants.Parameter + count,
                            correlation.CorrelationHandle.ArgumentType, correlation.CorrelationHandle.Direction, true);
                        metadata.Bind(correlation.CorrelationHandle, argument);
                        metadata.AddArgument(argument);
                        count++;
                    }
                }
            }

            RuntimeArgument requestMessageArgument = new RuntimeArgument(Constants.RequestMessage, Constants.MessageType, ArgumentDirection.In);
            if (this.Message == null)
            {
                this.Message = new InArgument<Message>();
            }
            metadata.Bind(this.Message, requestMessageArgument);
            metadata.AddArgument(requestMessageArgument);

            if (this.MessageOut != null)
            {
                RuntimeArgument requestMessageReference = new RuntimeArgument("MessageReference", Constants.MessageType, ArgumentDirection.Out);
                metadata.Bind(this.MessageOut, requestMessageReference);
                metadata.AddArgument(requestMessageReference);
            }

            metadata.AddImplementationVariable(this.sendMessageInstance);
            metadata.AddImplementationVariable(this.noPersistHandle);
            metadata.AddImplementationVariable(this.extensionSendCompleteBookmark);
            metadata.AddImplementationVariable(this.e2eActivityId);

            metadata.AddImplementationChild(this.channelCorrelationCompletionWaiter);
            metadata.AddImplementationChild(this.openChannelFactory);
            metadata.AddImplementationChild(this.openChannelAndSendMessage);

            metadata.AddDefaultExtensionProvider(SendMessageChannelCache.DefaultExtensionProvider);
        }

        protected override void Cancel(NativeActivityContext context)
        {
            SendReceiveExtension sendReceiveExtension = context.GetExtension<SendReceiveExtension>();
            if (sendReceiveExtension != null)
            {
                Bookmark pendingBookmark = this.extensionSendCompleteBookmark.Get(context);
                if (pendingBookmark != null)
                {
                    sendReceiveExtension.Cancel(pendingBookmark);
                    context.RemoveBookmark(pendingBookmark);
                }
                context.MarkCanceled();
            }
            else
            {
                // Do nothing.  InternalSendMessage cannot be canceled since
                // the individual parts of the process cannot be canceled.
            }
        }

        protected override void Abort(NativeActivityAbortContext context)
        {
            SendReceiveExtension sendReceiveExtension = context.GetExtension<SendReceiveExtension>();
            if (sendReceiveExtension != null)
            {
                Bookmark pendingBookmark = this.extensionSendCompleteBookmark.Get(context);
                if (pendingBookmark != null)
                {
                    sendReceiveExtension.Cancel(pendingBookmark);
                }
                base.Abort(context);
            }
            else
            {

                VolatileSendMessageInstance volatileInstance = this.sendMessageInstance.Get(context);

                if (volatileInstance != null)
                {
                    CleanupResources(volatileInstance.Instance);
                }
            }
        }

        void CleanupResources(SendMessageInstance instance)
        {
            if (instance != null)
            {
                instance.Dispose();
            }
        }

        // A separate code-path for extension based execution least impacts 
        // the existing workflow hosts. In the future we will add an extension from 
        // workflowservicehost and always use the extension.
        protected override void Execute(NativeActivityContext context)
        {
            SendReceiveExtension sendReceiveExtension = context.GetExtension<SendReceiveExtension>();
            if (sendReceiveExtension != null)
            {
                this.ExecuteUsingExtension(sendReceiveExtension, context);
            }
            else
            {
                // 



                // The entire InternalSendMessage runs in a no persist zone
                NoPersistHandle noPersistHandle = this.noPersistHandle.Get(context);
                noPersistHandle.Enter(context);

                // Set up the SendMessageInstance, which will 
                // setup an AsyncOperationBlock under the hood and thus block persistence 
                // until the message has been sent and we return to the workflow thread
                SendMessageInstance instance = new SendMessageInstance(this, context);
                SetSendMessageInstance(context, instance);

                if (instance.RequestContext != null)
                {
                    ExecuteClientRequest(context, instance);
                }
                else
                {
                    ExecuteServerResponse(context, instance);
                }
            }
        }

        void ExecuteUsingExtension(SendReceiveExtension sendReceiveExtension, NativeActivityContext context)
        {
            CorrelationHandle correlatesWith = null;
            if (this.TryGetCorrelatesWithHandle(context, out correlatesWith) && !correlatesWith.IsInitalized())
            {
                throw FxTrace.Exception.AsError(new ValidationException(SR.SendWithUninitializedCorrelatesWith(this.OperationName ?? string.Empty)));
            }

            CorrelationHandle ambientHandle = CorrelationHandle.GetAmbientCorrelation(context);
            if (correlatesWith == null)
            {
                correlatesWith = ambientHandle;
            }

            Guid e2eTracingId;
            SendSettings sendSettings;

            if (this.IsSendReply)
            {
                if (correlatesWith == null || !correlatesWith.IsInitalized())
                {
                    throw FxTrace.Exception.AsError(new ValidationException(SR.SendWithUninitializedCorrelatesWith(this.OperationName ?? string.Empty)));
                }

                e2eTracingId = correlatesWith.E2ETraceId;
                sendSettings = GetSettingsForSendReply();
            }
            else
            {
                CorrelationHandle requestReplyCorrelationHandle;
                this.correlationInitializers.TryGetRequestReplyCorrelationHandle(context, out requestReplyCorrelationHandle);

                // validate correlation configuration
                if (this.IsOneWay)
                {
                    if (requestReplyCorrelationHandle != null)
                    {
                        // this is a one-way send , we should not have a RequestReply Correlation initializer
                        throw FxTrace.Exception.AsError(new InvalidOperationException(SR.RequestReplyHandleShouldNotBePresentForOneWay));
                    }
                }
                else
                {
                    if (requestReplyCorrelationHandle == null && ambientHandle == null)
                    {
                        // we neither have a requestReply nor an ambientHandle
                        throw FxTrace.Exception.AsError(new InvalidOperationException(
                            SR.SendMessageNeedsToPairWithReceiveMessageForTwoWayContract(this.OperationName ?? string.Empty)));
                    }
                }

                e2eTracingId = InternalSendMessage.TraceCorrelationActivityId;
                if (e2eTracingId == Guid.Empty)
                {
                    e2eTracingId = Guid.NewGuid();
                }
                sendSettings = GetSettingsForSend(context);
            }

            this.SendToExtension(sendReceiveExtension, context, sendSettings, e2eTracingId, correlatesWith);
        }

        void SendToExtension(SendReceiveExtension sendReceiveExtension, NativeActivityContext context, SendSettings sendSettings, Guid e2eTracingId, CorrelationHandle correlatesWith)
        {
            Message message = this.Message.Get(context);

            // add a transient correlation if necessary
            if (!IsOneWay && !IsSendReply)
            {
                CorrelationMessageProperty correlationMessageProperty;
                if (!message.Properties.TryGetValue(CorrelationMessageProperty.Name, out correlationMessageProperty))
                {
                    InstanceKey requestReplyCorrelationKey = new InstanceKey(Guid.NewGuid(),
                            new Dictionary<XName, InstanceValue>
                            {
                                { WorkflowServiceNamespace.RequestReplyCorrelation, new InstanceValue(true) }
                            });

                    List<InstanceKey> transientCorrelations = new List<InstanceKey>();
                    transientCorrelations.Add(requestReplyCorrelationKey);
                    correlationMessageProperty = new CorrelationMessageProperty(InstanceKey.InvalidKey, new List<InstanceKey>(0), transientCorrelations);
                    message.Properties[CorrelationMessageProperty.Name] = correlationMessageProperty;
                }
                else
                {
                    InstanceKey requestReplyCorrelationKey;
                    // if requestReplyCorrelationKey does not exist, clone correlationMessageProperty and
                    // replace it in the message with one that has the key.
                    if (!this.TryGetRequestReplyCorrelationInstanceKey(correlationMessageProperty, out requestReplyCorrelationKey))
                    {
                        requestReplyCorrelationKey = new InstanceKey(Guid.NewGuid(),
                            new Dictionary<XName, InstanceValue>
                            {
                                { WorkflowServiceNamespace.RequestReplyCorrelation, new InstanceValue(true) }
                            });
                        List<InstanceKey> transientCorrelations = new List<InstanceKey>(correlationMessageProperty.TransientCorrelations);
                        transientCorrelations.Add(requestReplyCorrelationKey);
                        CorrelationMessageProperty newProperty = new CorrelationMessageProperty(
                                correlationMessageProperty.CorrelationKey,
                                correlationMessageProperty.AdditionalKeys,
                                transientCorrelations);
                        message.Properties[CorrelationMessageProperty.Name] = newProperty;
                    }
                }
            }

            MessageContext messageContext = new MessageContext(message) { EndToEndTracingId = e2eTracingId };
            Bookmark sendCompleteBookmark = context.CreateBookmark(SendCompleteOnExtension);
            this.extensionSendCompleteBookmark.Set(context, sendCompleteBookmark);
            this.e2eActivityId.Set(context, e2eTracingId);
            this.ProcessSendMessageTrace(context, e2eTracingId, true);
            sendReceiveExtension.Send(
                messageContext, 
                sendSettings, 
                (correlatesWith == null) ? null : correlatesWith.InstanceKey, 
                sendCompleteBookmark);

            if (this.MessageOut != null)
            {
                this.MessageOut.Set(context, null);
            }

            this.Message.Set(context, null);
        }

        SendSettings GetSettingsForSendReply()
        {
            return new SendSettings
            {
                RequirePersistBeforeSend = this.ShouldPersistBeforeSend,
                OwnerDisplayName = this.OwnerDisplayName
            };
        }

        SendSettings GetSettingsForSend(NativeActivityContext context)
        {
            SendSettings settings = new SendSettings
            {
                IsOneWay = this.IsOneWay,
                EndpointConfigurationName = this.EndpointConfigurationName,
                TokenImpersonationLevel = this.TokenImpersonationLevel,
                ProtectionLevel = this.Parent.ProtectionLevel,
                OwnerDisplayName = this.OwnerDisplayName
            };

            if (this.EndpointAddress != null)
            {
                settings.EndpointAddress = this.EndpointAddress.Get(context);
            }

            if (this.Endpoint != null)
            {
                settings.Endpoint = XamlServices.Parse(XamlServices.Save(this.Endpoint)) as Endpoint;
            }

            return settings;
        }

        void SendCompleteOnExtension(NativeActivityContext context, Bookmark bookmark, object state)
        {
            // Now that the bookmark has been resumed, clear out the workflow variable holding 
            // its value.
            this.extensionSendCompleteBookmark.Set(context, null);

            Exception fault = state as Exception;
            if (fault != null)
            {
                throw FxTrace.Exception.AsError(fault);
            }

            CorrelationMessageProperty correlationMessageProperty = state as CorrelationMessageProperty;

            if (state != null && correlationMessageProperty == null)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.InvalidDataFromSendBookmarkState(this.OperationName ?? string.Empty)));
            }

            if (correlationMessageProperty != null)
            {
                this.InitializeCorrelationHandles(context, correlationMessageProperty);
            }

            Guid e2eActivityId = this.e2eActivityId.Get(context);
            this.ProcessSendMessageCompleteTrace(context, e2eActivityId);
        }

        void InitializeCorrelationHandles(NativeActivityContext context, CorrelationMessageProperty correlationMessageProperty)
        {
            CorrelationHandle ambientCorrelationHandle = CorrelationHandle.GetAmbientCorrelation(context);

            if (this.IsSendReply)
            {
                // Check for ContextCorrelationInitializer handle
                CorrelationHandle contextCorrelationHandle = CorrelationHandle.GetExplicitContextCorrelation(context, this.correlationInitializers);
                MessagingActivityHelper.InitializeCorrelationHandles(context, contextCorrelationHandle, ambientCorrelationHandle, this.correlationInitializers, correlationMessageProperty.CorrelationKey, correlationMessageProperty.AdditionalKeys);
            }
            else
            {
                // Check for CallbackCorrelationInitializer handle
                CorrelationHandle callbackCorrelationHandle = CorrelationHandle.GetExplicitCallbackCorrelation(context, this.correlationInitializers);
                MessagingActivityHelper.InitializeCorrelationHandles(context, callbackCorrelationHandle, ambientCorrelationHandle, this.correlationInitializers, correlationMessageProperty.CorrelationKey, correlationMessageProperty.AdditionalKeys);

                InstanceKey requestReplyInstanceKey;
                if (this.TryGetRequestReplyCorrelationInstanceKey(correlationMessageProperty, out requestReplyInstanceKey))
                {
                    CorrelationHandle requestReplyCorrelationHandle = CorrelationHandle.GetExplicitRequestReplyCorrelation(context, this.correlationInitializers);
                    if (requestReplyCorrelationHandle != null)
                    {
                        requestReplyCorrelationHandle.TransientInstanceKey = requestReplyInstanceKey;
                    }
                    else if (ambientCorrelationHandle != null)
                    {
                        ambientCorrelationHandle.TransientInstanceKey = requestReplyInstanceKey;
                    }
                }
            }
        }

        bool TryGetRequestReplyCorrelationInstanceKey(CorrelationMessageProperty correlationMessageProperty, out InstanceKey instanceKey)
        {
            instanceKey = null;

            foreach (InstanceKey key in correlationMessageProperty.TransientCorrelations)
            {
                InstanceValue value;
                if (key.Metadata.TryGetValue(WorkflowServiceNamespace.RequestReplyCorrelation, out value))
                {
                    instanceKey = key;
                    break;
                }
            }

            return instanceKey != null;
        }

        bool TryGetCorrelatesWithHandle(NativeActivityContext context, out CorrelationHandle correlationHandle)
        {
            correlationHandle = null;
            if (this.CorrelatesWith != null)
            {
                correlationHandle = this.CorrelatesWith.Get(context);
            }

            return correlationHandle != null;
        }

        void SetSendMessageInstance(NativeActivityContext context, SendMessageInstance instance)
        {
            VolatileSendMessageInstance volatileInstance = new VolatileSendMessageInstance { Instance = instance };
            this.sendMessageInstance.Set(context, volatileInstance);
        }

        SendMessageInstance GetSendMessageInstance(ActivityContext context)
        {
            VolatileSendMessageInstance volatileInstance = this.sendMessageInstance.Get(context);

            Fx.Assert(volatileInstance != null, "This should never be null.");

            return volatileInstance.Instance;
        }

        // Used for server-side send (replies). We don't have any async code here since the
        // Dispatcher handles any completions
        void ExecuteServerResponse(NativeActivityContext context, SendMessageInstance instance)
        {
            Fx.Assert(instance.ResponseContext != null, "only valid for responses");
            Fx.Assert(instance.ResponseContext.WorkflowOperationContext != null, "The WorkflowOperationContext is required on the CorrelationResponseContext");
            instance.OperationContext = instance.ResponseContext.WorkflowOperationContext.OperationContext;

            // now that we have our op-context, invoke the callback that user might have added in the AEC in the previous activity 
            // e.g. distributed compensation activity will add this so that they can convert an execution property 
            // to an message properties, as will Transaction Flow
            instance.ProcessMessagePropertyCallbacks();

            ProcessSendMessageTrace(context, instance, false);

            // retrieve the correct CorrelationQueryBehavior from the ChannelExtensions collection
            CorrelationQueryBehavior correlationBehavior = null;
            Collection<CorrelationQueryBehavior> correlationQueryBehaviors = instance.OperationContext.Channel.Extensions.FindAll<CorrelationQueryBehavior>();
            foreach (CorrelationQueryBehavior cqb in correlationQueryBehaviors)
            {
                if (cqb.ServiceContractName == this.ServiceContractName)
                {
                    correlationBehavior = cqb;
                    break;
                }
            }

            //set the reply
            instance.RequestOrReply = this.Message.Get(context);

            if (correlationBehavior != null)
            {
                EnsureCorrelationBehaviorScopeName(context, correlationBehavior);
                instance.RegisterCorrelationBehavior(correlationBehavior);

                if (instance.CorrelationKeyCalculator != null)
                {
                    if (correlationBehavior.SendNames != null && correlationBehavior.SendNames.Count > 0)
                    {
                        if (correlationBehavior.SendNames.Count == 1 && (correlationBehavior.SendNames.Contains(ContextExchangeCorrelationHelper.CorrelationName)))
                        {
                            // Contextchannel is the only channel participating in correlation
                            // Since we already have the instance id, we don't have to wait for the context channel to call us back to initialize 
                            // the correlation - InstanceId can be retrieved directly from ContextMessageProperty through Operation context.
                            ContextMessageProperty contextProperties = null;
                            if (ContextMessageProperty.TryGet(instance.OperationContext.OutgoingMessageProperties, out contextProperties))
                            {
                                // 

                                CorrelationDataMessageProperty.AddData(instance.RequestOrReply, ContextExchangeCorrelationHelper.CorrelationName, () => ContextExchangeCorrelationHelper.GetContextCorrelationData(instance.OperationContext));
                            }
                            // Initialize correlations right away without waiting for the context channel to call us back
                            InitializeCorrelations(context, instance);
                        }
                        else
                        {
                            // Initialize correlations through channel callback
                            instance.OperationContext.OutgoingMessageProperties.Add(CorrelationCallbackMessageProperty.Name,
                                new MessageCorrelationCallbackMessageProperty(correlationBehavior.SendNames ?? new string[0], instance));
                            instance.CorrelationSynchronizer = new CorrelationSynchronizer();
                        }
                    }
                    else
                    {
                        // there are no channel based queries, we can initialize correlations right away
                        InitializeCorrelations(context, instance);
                    }
                }
            }

            // For exception case: Always call WorkflowOperationContext.SendFault to either send back the fault in the request/reply case 
            // or make sure the error handler extension gets a chance to handle this fault;
            if (instance.ResponseContext.Exception != null)
            {
                try
                {
                    instance.ResponseContext.WorkflowOperationContext.SendFault(instance.ResponseContext.Exception);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    instance.ResponseContext.Exception = e;
                }
            }
            else
            {
                try
                {
                    instance.ResponseContext.WorkflowOperationContext.SendReply(instance.RequestOrReply);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                    instance.ResponseContext.Exception = e;
                }
            }

            if (TraceUtility.ActivityTracing)
            {
                if (instance.AmbientActivityId != InternalSendMessage.TraceCorrelationActivityId)
                {
                    if (TD.StopSignpostEventIsEnabled())
                    {
                        TD.StopSignpostEvent(new DictionaryTraceRecord(new Dictionary<string, string>(3) {
                                                    { MessagingActivityHelper.ActivityName, this.DisplayName },
                                                    { MessagingActivityHelper.ActivityType, MessagingActivityHelper.MessagingActivityTypeActivityExecution },
                                                    { MessagingActivityHelper.ActivityInstanceId, context.ActivityInstanceId }
                            }));
                    }
                    FxTrace.Trace.SetAndTraceTransfer(instance.AmbientActivityId, true);
                    instance.AmbientActivityId = Guid.Empty;
                }
            }

            if (instance.CorrelationSynchronizer == null)
            {
                // We aren't doing any correlation work so we just
                // finalize the send.
                context.SetValue(this.Message, null);
                context.SetValue(this.MessageOut, null);

                if (ShouldPersistBeforeSend)
                {
                    // Need to allow persistence.
                    NoPersistHandle noPersistHandle = this.noPersistHandle.Get(context);
                    noPersistHandle.Exit(context);

                    // 
                    context.ScheduleActivity(this.persist, new CompletionCallback(OnPersistCompleted));
                }
                else
                {
                    FinalizeSendMessageCore(instance);
                }
            }
            else
            {
                // We're doing correlation.  Either the work is already
                // done or we need to synchronize with the channel stack.
                if (instance.CorrelationSynchronizer.IsChannelWorkComplete)
                {
                    // No need to schedule our completion waiter
                    OnChannelCorrelationCompleteCore(context, instance);
                }
                else
                {
                    context.ScheduleActivity(this.channelCorrelationCompletionWaiter, OnChannelCorrelationComplete, null);
                }

                // We notify that we're done with the send.  If the
                // correlation processing has already completed then
                // we'll finalize the send.
                if (instance.CorrelationSynchronizer.NotifySendComplete())
                {
                    FinalizeSendMessageCore(instance);
                }
            }
        }

        void ProcessSendMessageTrace(NativeActivityContext context, SendMessageInstance instance, bool isClient)
        {
            if (TraceUtility.MessageFlowTracing)
            {
                if (TraceUtility.ActivityTracing)
                {
                    instance.AmbientActivityId = InternalSendMessage.TraceCorrelationActivityId;
                }

                if (isClient)
                {
                    //We need to emit a transfer from WF instance ID to the id set in the TLS
                    instance.E2EActivityId = InternalSendMessage.TraceCorrelationActivityId;
                    if (instance.E2EActivityId == Guid.Empty)
                    {
                        instance.E2EActivityId = Guid.NewGuid();
                    }
                }
                else
                {
                    instance.E2EActivityId = instance.ResponseContext.WorkflowOperationContext.E2EActivityId;
                }

                this.ProcessSendMessageTrace(context, instance.E2EActivityId, isClient);
            }
        }

        void ProcessSendMessageTrace(NativeActivityContext context, Guid e2eActivityId, bool isClient)
        {
            if (TraceUtility.MessageFlowTracing)
            {
                try
                {
                    if (isClient)
                    {
                        if (context.WorkflowInstanceId != e2eActivityId)
                        {
                            DiagnosticTraceBase.ActivityId = context.WorkflowInstanceId;
                            FxTrace.Trace.SetAndTraceTransfer(e2eActivityId, true);
                        }
                    }
                    else
                    {
                        DiagnosticTraceBase.ActivityId = context.WorkflowInstanceId;
                    }

                    context.Track(
                        new SendMessageRecord(MessagingActivityHelper.MessageCorrelationSendRecord)
                        {
                            E2EActivityId = e2eActivityId
                        });

                    if (TraceUtility.ActivityTracing)
                    {
                        if (TD.StartSignpostEventIsEnabled())
                        {
                            TD.StartSignpostEvent(new DictionaryTraceRecord(new Dictionary<string, string>(3) {
                                                    { MessagingActivityHelper.ActivityName, this.DisplayName },
                                                    { MessagingActivityHelper.ActivityType, MessagingActivityHelper.MessagingActivityTypeActivityExecution },
                                                    { MessagingActivityHelper.ActivityInstanceId, context.ActivityInstanceId }
                            }));
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (Fx.IsFatal(ex))
                    {
                        throw;
                    }
                    FxTrace.Exception.AsInformation(ex);
                }
            }
        }

        void ProcessSendMessageCompleteTrace(NativeActivityContext context, Guid e2eActivityId)
        {
            Guid ambientActivityId = InternalSendMessage.TraceCorrelationActivityId;
            if (TraceUtility.ActivityTracing)
            {
                if (TD.StopSignpostEventIsEnabled())
                {
                    TD.StopSignpostEvent(new DictionaryTraceRecord(new Dictionary<string, string>(3) {
                                                    { MessagingActivityHelper.ActivityName, this.DisplayName },
                                                    { MessagingActivityHelper.ActivityType, MessagingActivityHelper.MessagingActivityTypeActivityExecution },
                                                    { MessagingActivityHelper.ActivityInstanceId, context.ActivityInstanceId }
                                }));
                }
                FxTrace.Trace.SetAndTraceTransfer(ambientActivityId, true);
            }
            if (TD.WfMessageSentIsEnabled())
            {
                // 
                EventTraceActivity eta = new EventTraceActivity();
                if (e2eActivityId != Guid.Empty)
                {
                    eta.SetActivityId(e2eActivityId);
                }
                TD.WfMessageSent(eta, ambientActivityId);
            }
        }

        void OnChannelCorrelationComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            SendMessageInstance instance = GetSendMessageInstance(context);
            Fx.Assert(instance != null, "The instance cannot be null here.");

            OnChannelCorrelationCompleteCore(context, instance);
        }

        void OnChannelCorrelationCompleteCore(NativeActivityContext context, SendMessageInstance instance)
        {
            Message message = InitializeCorrelations(context, instance);
            instance.CorrelationSynchronizer.NotifyMessageUpdatedByWorkflow(message);

            context.SetValue(this.Message, null);
            context.SetValue(this.MessageOut, null);

            if (this.ShouldPersistBeforeSend && instance.RequestContext == null)
            {
                // Need to allow persistence.
                NoPersistHandle noPersistHandle = this.noPersistHandle.Get(context);
                noPersistHandle.Exit(context);

                // 
                context.ScheduleActivity(this.persist, new CompletionCallback(OnPersistCompleted));
            }
            else
            {
                // Create a bookmark to complete the callback, this is to ensure that the InstanceKey does get saved in the PPD 
                // by the time the bookmark is resumed. The instancekey is not getting  saved in the PPD  till workflow gets to 
                // the next idle state. 
                // 
                Bookmark completeCorrelationBookmark = context.CreateBookmark(CompleteCorrelationCallback, BookmarkOptions.NonBlocking);
                context.ResumeBookmark(completeCorrelationBookmark, null);
            }
        }

        void CompleteCorrelationCallback(NativeActivityContext context, Bookmark bookmark, object value)
        {
            SendMessageInstance instance = GetSendMessageInstance(context);
            Fx.Assert(instance != null, "The instance cannot be null here.");

            if (instance.CorrelationSynchronizer.NotifyWorkflowCorrelationProcessingComplete())
            {
                // The send complete notification has already occurred
                // so it is up to us to finalize the send.
                FinalizeSendMessageCore(instance);
            }
        }

        void OnPersistCompleted(NativeActivityContext context, ActivityInstance completedInstance)
        {
            // We can reenter no persist now
            NoPersistHandle noPersistHandle = this.noPersistHandle.Get(context);
            noPersistHandle.Enter(context);

            // We might get back a null here because we've allowed persistence.
            // If that is the case we'll just ignore it ... we don't have any more
            // meaningful work to do.
            SendMessageInstance instance = GetSendMessageInstance(context);

            if (instance != null)
            {
                // Do it with or without correlation
                if (instance.CorrelationSynchronizer == null || instance.CorrelationSynchronizer.NotifyWorkflowCorrelationProcessingComplete())
                {
                    // The send complete notification has already occurred
                    // so it is up to us to finalize the send.
                    FinalizeSendMessageCore(instance);
                }
            }
        }

        void ExecuteClientRequest(NativeActivityContext context, SendMessageInstance instance)
        {
            // This is the client send request: we need to figure out the channel and request message first

            // Get the Extension for the ChannelSettings
            instance.CacheExtension = context.GetExtension<SendMessageChannelCache>();
            Fx.Assert(instance.CacheExtension != null, "channelCacheExtension must exist.");


            // Send.ChannelCacheEnabled must be set before we call CreateEndpointAddress
            // because CreateEndpointAddress will cache description and description resolution depends on the value of ChannelCacheEnabled
            this.Parent.InitializeChannelCacheEnabledSetting(instance.CacheExtension);

            // if there is a correlatesWith handle with callbackcontext(Durable Duplex case), use the callback address and context from
            // there. The handle could be an explicit 'CorrelatesWith' handle or an ambient handle.
            if (instance.CorrelatesWith != null)
            {
                if (instance.CorrelatesWith.CallbackContext != null)
                {
                    instance.CorrelationCallbackContext = instance.CorrelatesWith.CallbackContext;

                    // construct EndpointAdress based on the ListenAddress from callback and the identity and headers from Endpoint or from Config
                    instance.EndpointAddress = CreateEndpointAddressFromCallback(instance.CorrelationCallbackContext.ListenAddress.ToEndpointAddress());
                }

                if (instance.CorrelatesWith.Context != null)
                {
                    instance.CorrelationContext = instance.CorrelatesWith.Context;
                }
            }
            // Request  is always of Type Message. Message Argument will be set by Send<T> using the appropriate formatter
            instance.RequestOrReply = this.Message.Get(context);

            if (instance.EndpointAddress == null)
            {
                //try to get it from endpoint or config
                instance.EndpointAddress = CreateEndpointAddress(context);
            }

            if (instance.EndpointAddress == null)
            {
                throw FxTrace.Exception.AsError(new ValidationException(SR.EndpointAddressNotSetInEndpoint(this.OperationName)));
            }

            // Configname to be used for the FactoryCacheKey, 
            // if endpoint is defined, we use the settings from endpoint and ignore the endpointConfigurationName
            // if endpoint is not defined we use the endpointConfigurationName
            string configName = (this.Endpoint != null) ? null : this.EndpointConfigurationName;

            ProcessSendMessageTrace(context, instance, true);

            // Get ChannelFactory from the cache
            ObjectCache<FactoryCacheKey, ChannelFactoryReference> channelFactoryCache = null;
            ObjectCacheItem<ChannelFactoryReference> cacheItem = null;
            ChannelCacheSettings channelCacheSettings;                        
            
            // retrieve the FactoryCacheKey and cache it so that we could use it later.  
            if (this.cachedFactoryCacheKey == null)
            {
                ServiceEndpoint targetEndpoint = this.GetCachedServiceEndpoint();
                this.cachedFactoryCacheKey = new FactoryCacheKey(this.Endpoint, configName, this.IsOneWay, this.TokenImpersonationLevel,
                    targetEndpoint.Contract, this.correlationQueries);
            }
            
            // let's decide if we can share the cache from the extension
            // cache can be share if AllowUnsafeSharing is true or it is safe to share
            if (instance.CacheExtension.AllowUnsafeCaching || this.IsEndpointSettingsSafeForCache())
            {
                channelFactoryCache = instance.CacheExtension.GetFactoryCache();
                Fx.Assert(channelFactoryCache != null, "factory cache should be initialized either from the extension or from the globalcache");

                channelCacheSettings = instance.CacheExtension.ChannelSettings;

                // Get a ChannelFactoryReference (either cached or brand new)
                KeyValuePair<ObjectCacheItem<ChannelFactoryReference>, SendMessageChannelCache> localLastUsedCacheItem = this.lastUsedFactoryCacheItem;
                if (object.ReferenceEquals(localLastUsedCacheItem.Value, instance.CacheExtension))
                {
                    if (localLastUsedCacheItem.Key != null && localLastUsedCacheItem.Key.TryAddReference())
                    {
                        cacheItem = localLastUsedCacheItem.Key;
                    }
                    else
                    {
                        // the item is invalid
                        this.lastUsedFactoryCacheItem = new KeyValuePair<ObjectCacheItem<ChannelFactoryReference>, SendMessageChannelCache>(null, null);
                    }
                }

                if (cacheItem == null)
                {
                    // try retrieving the factoryreference directly from the factory cache 
                    cacheItem = channelFactoryCache.Take(this.cachedFactoryCacheKey);
                }
                if (cacheItem == null && TD.SendMessageChannelCacheMissIsEnabled())
                {
                    TD.SendMessageChannelCacheMiss();
                }
            }
            else
            {
                // not safe to share cache, do not cache anything
                channelCacheSettings = ChannelCacheSettings.EmptyCacheSettings;
            }

            ChannelFactoryReference newFactoryReference = null;
            if (cacheItem == null)
            {
                // nothing in our cache, we'll have to setup a new factory reference, which ClientSendAsyncResult will open asynchronously
                ServiceEndpoint targetEndpoint = this.CreateServiceEndpoint();
                // create a new ChannelFactoryReference that holds the channelfactory and a cache for its channels, 
                // cache settings are based on the channelcachesettings provided through the extension
                newFactoryReference = new ChannelFactoryReference(this.cachedFactoryCacheKey, targetEndpoint, channelCacheSettings);
            }

            instance.SetupFactoryReference(cacheItem, newFactoryReference, channelFactoryCache);

            if (this.onSendFailure == null)
            {
                this.onSendFailure = new FaultCallback(OnSendFailure);
            }

            if (instance.FactoryReference.NeedsOpen)
            {
                context.ScheduleActivity(this.openChannelFactory, OnChannelFactoryOpened, this.onSendFailure);
            }
            else
            {
                OnChannelFactoryOpenedCore(context, instance);
            }
        }

        void OnSendFailure(NativeActivityFaultContext context, Exception propagatedException, ActivityInstance propagatedFrom)
        {
            // We throw the exception because we want this activity to abort
            // as well.  The abort path will take care of performing resource
            // clean-up (see Abort(NativeActivityAbortContext)).
            throw FxTrace.Exception.AsError(propagatedException);
        }

        void OnChannelFactoryOpened(NativeActivityContext context, ActivityInstance completedInstance)
        {
            SendMessageInstance instance = GetSendMessageInstance(context);
            Fx.Assert(instance != null, "Must have a SendMessageInstance here.");

            OnChannelFactoryOpenedCore(context, instance);
        }

        void OnChannelFactoryOpenedCore(NativeActivityContext context, SendMessageInstance instance)
        {
            // now that we know the factory is open, setup our client channel and pool reference
            instance.PopulateClientChannel();

            IContextChannel contextChannel = instance.ClientSendChannel as IContextChannel;
            instance.OperationContext = (contextChannel == null) ? null : new OperationContext(contextChannel);
            
            // Retrieve the CorrelationQueryBehavior from the serviceEndpoint that we used for ChannelFactoryCreation
            // we later look for CorrelationQueryBehavior.SendNames which actually gets initialized during ChannelFactory creation
            // 
            CorrelationQueryBehavior correlationQueryBehavior = instance.FactoryReference.CorrelationQueryBehavior;

            if (correlationQueryBehavior != null)
            {
                EnsureCorrelationBehaviorScopeName(context, correlationQueryBehavior);
                instance.RegisterCorrelationBehavior(correlationQueryBehavior);
            }

            // now that we have our op-context, invoke the callback that user might have added in the AEC in the previous activity 
            // e.g. distributed compensation activity will add this so that they can convert an execution property 
            // to an message properties, as will Transaction Flow
            instance.ProcessMessagePropertyCallbacks();

            // Add the ContextMessage Property if either CallBackContextMessageProperty or ContextMessageProperty is set
            // if both are set validate that the context is the same in both of them
            ContextMessageProperty contextMessageProperty = null;
            if (instance.CorrelationCallbackContext != null && instance.CorrelationContext != null)
            {
                // validate if the context is equivalent
                if (MessagingActivityHelper.CompareContextEquality(instance.CorrelationCallbackContext.Context, instance.CorrelationContext.Context))
                {
                    contextMessageProperty = new ContextMessageProperty(instance.CorrelationCallbackContext.Context);
                }
                else
                {
                    throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ContextMismatchInContextAndCallBackContext));
                }
            }
            else if (instance.CorrelationCallbackContext != null)
            {
                contextMessageProperty = new ContextMessageProperty(instance.CorrelationCallbackContext.Context);
            }
            else if (instance.CorrelationContext != null)
            {
                contextMessageProperty = new ContextMessageProperty(instance.CorrelationContext.Context);
            }

            if (contextMessageProperty != null)
            {
                contextMessageProperty.AddOrReplaceInMessage(instance.RequestOrReply);
            }

            // Add callback context Message property with instance id.
            // If binding contains ContextBindingElement with listenaddress set, the callback context message property will flow on the wire

            // Pull the instanceId from the CorrelationHandle, if it is already initialized, else create a new GUID.
            // we want to send the callback context only for the first message and when there is a FollowingContextCorrelation defined ( i.e., we are expecting a 
            // receive message back) or when there is an ambienthandle and the handle is not initalized. We will never use CorrelatesWith handle to initialize 
            // FollowingContext, since CorrelatesWith on the client side should always be used for a following correlation
            String contextValue;
            CorrelationHandle followingContextHandle = instance.ContextBasedCorrelationHandle != null ? instance.ContextBasedCorrelationHandle : instance.AmbientHandle;

            if (followingContextHandle != null && (followingContextHandle.Scope == null || followingContextHandle.Scope.IsInitialized == false))
            {
                // we are creating a new GUID for the context. As a practice,we don't want to send the WorkflowInstanceId over the wire
                contextValue = Guid.NewGuid().ToString();
                Dictionary<string, string> contextValues = new Dictionary<string, string>(1)
                    {
                        { ContextMessageProperty.InstanceIdKey, contextValue }
                    };
                new CallbackContextMessageProperty(contextValues).AddOrReplaceInMessage(instance.RequestOrReply);
            }

            // verify if we can complete Correlation intialization now
            if (instance.CorrelationSendNames != null)
            {
                // we're going to initialize request correlations later
                instance.RequestOrReply.Properties.Add(CorrelationCallbackMessageProperty.Name,
                    new MessageCorrelationCallbackMessageProperty(instance.CorrelationSendNames, instance));

                instance.CorrelationSynchronizer = new CorrelationSynchronizer();
            }
            else
            {
                InitializeCorrelations(context, instance);
            }

            if (instance.CorrelationSynchronizer != null)
            {
                context.ScheduleActivity(this.channelCorrelationCompletionWaiter, OnChannelCorrelationComplete, this.onSendFailure);
            }

            context.ScheduleActivity(this.openChannelAndSendMessage, OnClientSendComplete, this.onSendFailure);
        }

        void OnClientSendComplete(NativeActivityContext context, ActivityInstance completedInstance)
        {
            SendMessageInstance instance = GetSendMessageInstance(context);

            if (instance.CorrelationSynchronizer == null || instance.CorrelationSynchronizer.NotifySendComplete())
            {
                // Either there was no correlation or the send completed
                // after the correlation processing so we need to do the
                // finalize
                FinalizeSendMessageCore(instance);
            }
        }

        Message InitializeCorrelations(NativeActivityContext context, SendMessageInstance instance)
        {
            if (instance.CorrelationKeyCalculator != null)
            {
                // first setup the key-based correlations, pass in the Correlation Initialiers and the AmbientHandle 
                // for associating the keys. 
                // For content based correlation, we will never initalize correlation with a selectHandle.It has to be either specified in a CorrelationInitalizer 
                // or should be an ambient handle
                // For contextbased correlation, selecthandle will be callbackHandle in case of Send and contextHandle in case of sendReply
                instance.RequestOrReply = MessagingActivityHelper.InitializeCorrelationHandles(context,
                    instance.ContextBasedCorrelationHandle, instance.AmbientHandle, this.correlationInitializers,
                    instance.CorrelationKeyCalculator, instance.RequestOrReply);
            }

            // then setup any channel based correlations as necessary
            // 
            if (instance.RequestContext != null)
            {
                // first check for an explicit association
                CorrelationHandle requestReplyCorrelationHandle = instance.GetExplicitRequestReplyCorrelationHandle(context, this.correlationInitializers);
                if (requestReplyCorrelationHandle != null)
                {
                    if (!requestReplyCorrelationHandle.TryRegisterRequestContext(context, instance.RequestContext))
                    {
                        throw FxTrace.Exception.AsError(new InvalidOperationException(SR.TryRegisterRequestContextFailed));
                    }
                }
                else // if that fails, use the ambient handle. We do not use the CorrelatesWith handle for RequestReply correlation
                {
                    if (!this.IsOneWay)
                    {
                        // we have already validated this in SendMessageInstanceConstructor, just assert here
                        Fx.Assert(instance.AmbientHandle != null, "For two way send we need to have either a RequestReply correlation handle or an ambient handle");
                        if (!instance.AmbientHandle.TryRegisterRequestContext(context, instance.RequestContext))
                        {
                            throw FxTrace.Exception.AsError(new InvalidOperationException(SR.TryRegisterRequestContextFailed));
                        }
                    }
                }
            }

            return instance.RequestOrReply;
        }

        void FinalizeSendMessageCore(SendMessageInstance instance)
        {
            Exception completionException = instance.GetCompletionException();

            if (completionException != null)
            {
                throw FxTrace.Exception.AsError(completionException);
            }
        }

        class OpenChannelFactory : AsyncCodeActivity
        {
            public OpenChannelFactory()
            {
            }

            public InArgument<VolatileSendMessageInstance> Instance
            {
                get;
                set;
            }

            protected override void CacheMetadata(CodeActivityMetadata metadata)
            {
                RuntimeArgument instanceArgument = new RuntimeArgument("Instance", typeof(VolatileSendMessageInstance), ArgumentDirection.In);
                if (this.Instance == null)
                {
                    this.Instance = new InArgument<VolatileSendMessageInstance>();
                }
                metadata.Bind(this.Instance, instanceArgument);

                metadata.SetArgumentsCollection(
                    new Collection<RuntimeArgument>
                {
                    instanceArgument
                });
            }

            protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
            {
                VolatileSendMessageInstance volatileInstance = this.Instance.Get(context);

                return new OpenChannelFactoryAsyncResult(volatileInstance.Instance, callback, state);
            }

            protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
            {
                OpenChannelFactoryAsyncResult.End(result);
            }

            class OpenChannelFactoryAsyncResult : AsyncResult
            {
                static AsyncCompletion channelFactoryOpenCompletion = new AsyncCompletion(ChannelFactoryOpenCompletion);

                SendMessageInstance instance;

                public OpenChannelFactoryAsyncResult(SendMessageInstance instance, AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    this.instance = instance;
                    bool completeSelf = false;

                    if (this.instance.FactoryReference.NeedsOpen)
                    {
                        IAsyncResult result = this.instance.FactoryReference.BeginOpen(PrepareAsyncCompletion(channelFactoryOpenCompletion), this);
                        if (result.CompletedSynchronously)
                        {
                            completeSelf = OnNewChannelFactoryOpened(result);
                        }
                    }
                    else
                    {
                        completeSelf = true;
                    }

                    if (completeSelf)
                    {
                        Complete(true);
                    }
                }

                public static void End(IAsyncResult result)
                {
                    AsyncResult.End<OpenChannelFactoryAsyncResult>(result);
                }

                static bool ChannelFactoryOpenCompletion(IAsyncResult result)
                {
                    OpenChannelFactoryAsyncResult thisPtr = (OpenChannelFactoryAsyncResult)result.AsyncState;
                    return thisPtr.OnNewChannelFactoryOpened(result);
                }

                bool OnNewChannelFactoryOpened(IAsyncResult result)
                {
                    ObjectCacheItem<ChannelFactoryReference> newCacheItem =
                        this.instance.FactoryReference.EndOpen(result, this.instance.FactoryCache);
                    this.instance.RegisterNewCacheItem(newCacheItem);

                    return true;
                }

            }
        }

        class OpenChannelAndSendMessage : AsyncCodeActivity
        {
            public OpenChannelAndSendMessage()
            {
            }

            public InArgument<VolatileSendMessageInstance> Instance
            {
                get;
                set;
            }

            public InternalSendMessage InternalSendMessage
            {
                get;
                set;
            }

            protected override void CacheMetadata(CodeActivityMetadata metadata)
            {
                RuntimeArgument instanceArgument = new RuntimeArgument("Instance", typeof(VolatileSendMessageInstance), ArgumentDirection.In);
                if (this.Instance == null)
                {
                    this.Instance = new InArgument<VolatileSendMessageInstance>();
                }
                metadata.Bind(this.Instance, instanceArgument);
                metadata.AddArgument(instanceArgument);
            }

            protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
            {
                VolatileSendMessageInstance volatileInstance = this.Instance.Get(context);
                Transaction transaction = null;

                RuntimeTransactionHandle handle = context.GetProperty<RuntimeTransactionHandle>();
                if (handle != null)
                {
                    transaction = handle.GetCurrentTransaction(context);
                }

                return new OpenChannelAndSendMessageAsyncResult(InternalSendMessage, volatileInstance.Instance, transaction, callback, state);
            }

            protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
            {
                OpenChannelAndSendMessageAsyncResult.End(result);
            }

            class OpenChannelAndSendMessageAsyncResult : TransactedAsyncResult
            {
                static AsyncCompletion onChannelOpened = new AsyncCompletion(OnChannelOpened);
                static AsyncCompletion onChannelSendComplete = new AsyncCompletion(OnChannelSendComplete);
                static AsyncCallback onChannelReceiveReplyCompleted = Fx.ThunkCallback(OnChannelReceiveReplyComplete);

                SendMessageInstance instance;
                InternalSendMessage internalSendMessage;
                IChannel channel;
                Transaction currentTransactionContext;
                Guid ambientActivityId;

                //This is used to create a blocking dependent clone to synchronize the transaction commit processing with the completion of the aborting clone
                //that is created in this async result.
                DependentTransaction dependentClone;

                public OpenChannelAndSendMessageAsyncResult(InternalSendMessage internalSendMessage, SendMessageInstance instance, Transaction currentTransactionContext, AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    this.internalSendMessage = internalSendMessage;
                    this.instance = instance;
                    this.channel = this.instance.ClientSendChannel;
                    this.currentTransactionContext = currentTransactionContext;
                    
                    bool completeSelf = false;

                    //channel is still in created state, we need to open it
                    if (this.channel.State == CommunicationState.Created)
                    {
                        // Disable ContextManager before channel is opened
                        IContextManager contextManager = this.channel.GetProperty<IContextManager>();
                        if (contextManager != null)
                        {
                            contextManager.Enabled = false;
                        }

                        IAsyncResult result = this.channel.BeginOpen(PrepareAsyncCompletion(onChannelOpened), this);
                        if (result.CompletedSynchronously)
                        {
                            completeSelf = OnChannelOpened(result);
                        }
                    }
                    else
                    {
                        // channel already opened & retrieved from cache
                        // we don't have to do anything with ChannelOpen
                        completeSelf = BeginSendMessage();
                    }

                    if (completeSelf)
                    {
                        Complete(true);
                    }
                }

                public static void End(IAsyncResult result)
                {
                    AsyncResult.End<OpenChannelAndSendMessageAsyncResult>(result);
                }

                static bool OnChannelOpened(IAsyncResult result)
                {
                    OpenChannelAndSendMessageAsyncResult thisPtr = (OpenChannelAndSendMessageAsyncResult)result.AsyncState;
                    thisPtr.channel.EndOpen(result);
                    return thisPtr.BeginSendMessage();
                }

                bool BeginSendMessage()
                {
                    IAsyncResult result = null;
                    bool requestSucceeded = false;
                    OperationContext oldContext = OperationContext.Current;
                    bool asyncSend = !this.internalSendMessage.IsOneWay;

                    try
                    {
                        OperationContext.Current = this.instance.OperationContext;

                        if (TraceUtility.MessageFlowTracingOnly)
                        {
                            //set the E2E activity ID
                            DiagnosticTraceBase.ActivityId = this.instance.E2EActivityId;
                        }

                        using (PrepareTransactionalCall(this.currentTransactionContext))
                        {
                            if (asyncSend)
                            {
                                //If there is a transaction that we could be flowing out then we create this blocking clone to [....] with the commit processing.
                                if (this.currentTransactionContext != null)
                                {
                                    this.dependentClone = this.currentTransactionContext.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
                                }

                                this.instance.RequestContext.EnsureAsyncWaitHandle();

                                result = ((IRequestChannel)this.channel).BeginRequest(this.instance.RequestOrReply, onChannelReceiveReplyCompleted, this);
                                if (result.CompletedSynchronously)
                                {
                                    Message reply = ((IRequestChannel)this.channel).EndRequest(result);
                                    this.instance.RequestContext.ReceiveReply(this.instance.OperationContext, reply);
                                }
                            }
                            else
                            {
                                result = ((IOutputChannel)this.channel).BeginSend(this.instance.RequestOrReply, PrepareAsyncCompletion(onChannelSendComplete), this);
                                if (result.CompletedSynchronously)
                                {
                                    ((IOutputChannel)this.channel).EndSend(result);
                                }
                            }

                            requestSucceeded = true;
                        }
                    }
                    finally
                    {
                        OperationContext.Current = oldContext;

                        if (!requestSucceeded)
                        {
                            //if we did not succeed, complete the blocking clone anyway if we created it
                            if (this.dependentClone != null)
                            {
                                this.dependentClone.Complete();
                                this.dependentClone = null;
                            }
                            this.channel.Abort();
                        }

                        if (result != null && result.CompletedSynchronously)
                        {
                            //if we are done synchronously, we need to complete a blocking dependent clone if we created one (asyncSend case)
                            if (this.dependentClone != null)
                            {
                                this.dependentClone.Complete();
                                this.dependentClone = null;
                            }
                            this.internalSendMessage.CleanupResources(this.instance);
                        }
                    }

                    if (asyncSend)
                    {
                        return true;
                    }
                    else
                    {
                        return SyncContinue(result);
                    }
                }

                static void OnChannelReceiveReplyComplete(IAsyncResult result)
                {
                    if (result.CompletedSynchronously)
                    {
                        return;
                    }

                    OpenChannelAndSendMessageAsyncResult thisPtr = (OpenChannelAndSendMessageAsyncResult)result.AsyncState;

                    OperationContext oldContext = OperationContext.Current;

                    Message reply = null;
                    bool requestSucceeded = false;

                    try
                    {
                        OperationContext.Current = thisPtr.instance.OperationContext;

                        thisPtr.TraceActivityData();

                        System.Transactions.TransactionScope scope = TransactionHelper.CreateTransactionScope(thisPtr.currentTransactionContext);
                        try
                        {
                            Fx.Assert(thisPtr.channel is IRequestChannel, "Channel must be of IRequestChannel type!");

                            reply = ((IRequestChannel)thisPtr.channel).EndRequest(result);

                            //
                            thisPtr.instance.RequestContext.ReceiveAsyncReply(thisPtr.instance.OperationContext, reply, null);

                            requestSucceeded = true;
                        }
                        finally
                        {
                            TransactionHelper.CompleteTransactionScope(ref scope);
                        }
                    }
                    catch (Exception exception)
                    {
                        if (Fx.IsFatal(exception))
                        {
                            throw;
                        }

                        thisPtr.instance.RequestContext.ReceiveAsyncReply(thisPtr.instance.OperationContext, null, exception);
                    }
                    finally
                    {
                        //Complete the blocking dependent clone created before the async call was made.
                        if (thisPtr.dependentClone != null)
                        {
                            thisPtr.dependentClone.Complete();
                            thisPtr.dependentClone = null;
                        }

                        OperationContext.Current = oldContext;

                        if (!requestSucceeded)
                        {
                            thisPtr.channel.Abort();
                        }

                        thisPtr.internalSendMessage.CleanupResources(thisPtr.instance);
                    }
                }

                static bool OnChannelSendComplete(IAsyncResult result)
                {
                    if (result.CompletedSynchronously)
                    {
                        return true;
                    }

                    OpenChannelAndSendMessageAsyncResult thisPtr = (OpenChannelAndSendMessageAsyncResult)result.AsyncState;

                    OperationContext oldContext = OperationContext.Current;

                    try
                    {
                        OperationContext.Current = thisPtr.instance.OperationContext;

                        thisPtr.TraceActivityData();

                        System.Transactions.TransactionScope scope = TransactionHelper.CreateTransactionScope(thisPtr.currentTransactionContext);
                        try
                        {
                            Fx.Assert(thisPtr.channel is IOutputChannel, "Channel must be of IOutputChannel type!");

                            ((IOutputChannel)thisPtr.channel).EndSend(result);
                        }
                        finally
                        {
                            TransactionHelper.CompleteTransactionScope(ref scope);
                        }
                    }
                    catch (Exception exception)
                    {
                        if (Fx.IsFatal(exception))
                        {
                            throw;
                        }

                        // stash away the exception to be retrieved in FinalizeSendMessageCore
                        thisPtr.instance.RequestContext.Exception = exception;
                    }
                    finally
                    {
                        OperationContext.Current = oldContext;
                        thisPtr.internalSendMessage.CleanupResources(thisPtr.instance);
                    }

                    return true;
                }

                void TraceActivityData()
                {
                    if (TraceUtility.ActivityTracing)
                    {
                        if (TD.StopSignpostEventIsEnabled())
                        {
                            TD.StopSignpostEvent(new DictionaryTraceRecord(new Dictionary<string, string>(3) {
                                                    { MessagingActivityHelper.ActivityName, this.instance.Activity.DisplayName },
                                                    { MessagingActivityHelper.ActivityType, MessagingActivityHelper.MessagingActivityTypeActivityExecution },
                                                    { MessagingActivityHelper.ActivityInstanceId, this.instance.ActivityInstanceId }
                                }));
                        }
                        FxTrace.Trace.SetAndTraceTransfer(this.ambientActivityId, true);
                        this.ambientActivityId = Guid.Empty;
                    }
                    if (TD.WfMessageSentIsEnabled())
                    {
                        // 
                        EventTraceActivity eta = new EventTraceActivity();
                        if (this.instance.E2EActivityId != Guid.Empty)
                        {
                            eta.SetActivityId(this.instance.E2EActivityId);
                        }
                        TD.WfMessageSent(eta, this.ambientActivityId);
                    }
                }
            }
        }

        class WaitOnChannelCorrelation : AsyncCodeActivity
        {
            public WaitOnChannelCorrelation()
            {
            }

            public InArgument<VolatileSendMessageInstance> Instance
            {
                get;
                set;
            }

            protected override void CacheMetadata(CodeActivityMetadata metadata)
            {
                RuntimeArgument instanceArgument = new RuntimeArgument("Instance", typeof(VolatileSendMessageInstance), ArgumentDirection.In);
                if (this.Instance == null)
                {
                    this.Instance = new InArgument<VolatileSendMessageInstance>();
                }
                metadata.Bind(this.Instance, instanceArgument);

                metadata.SetArgumentsCollection(
                    new Collection<RuntimeArgument>
                {
                    instanceArgument
                });
            }

            protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
            {
                VolatileSendMessageInstance volatileInstance = this.Instance.Get(context);

                Fx.Assert(volatileInstance.Instance != null, "This should not have gone through a persistence episode yet.");

                return new WaitOnChannelCorrelationAsyncResult(volatileInstance.Instance.CorrelationSynchronizer, callback, state);
            }

            protected override void EndExecute(AsyncCodeActivityContext context, IAsyncResult result)
            {
                WaitOnChannelCorrelationAsyncResult.End(result);
            }

            class WaitOnChannelCorrelationAsyncResult : AsyncResult
            {
                CorrelationSynchronizer synchronizer;

                public WaitOnChannelCorrelationAsyncResult(CorrelationSynchronizer synchronizer, AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    this.synchronizer = synchronizer;

                    if (synchronizer.IsChannelWorkComplete)
                    {
                        Complete(true);
                    }
                    else
                    {
                        if (synchronizer.SetWorkflowNotificationCallback(new Action(OnChannelCorrelationComplete)))
                        {
                            // The bool flipped just before we set the action so
                            // we're actually complete.  The contract is that the
                            // action will never be raised if Set returns true.
                            Complete(true);
                        }
                    }
                }

                public static void End(IAsyncResult result)
                {
                    AsyncResult.End<WaitOnChannelCorrelationAsyncResult>(result);
                }

                void OnChannelCorrelationComplete()
                {
                    Complete(false);
                }
            }
        }

       internal class CorrelationSynchronizer
        {
            Action onRequestSetByChannel;
            Action<Message> onWorkflowCorrelationProcessingComplete;
            object thisLock;
            Completion completion;

            public CorrelationSynchronizer()
            {
                this.thisLock = new object();
            }

            public bool IsChannelWorkComplete
            {
                get;
                private set;
            }

            public Message UpdatedMessage
            {
                get;
                private set;
            }

            public void NotifyRequestSetByChannel(Action<Message> onWorkflowCorrelationProcessingComplete)
            {
                Fx.Assert(onWorkflowCorrelationProcessingComplete != null, "Must have a non-null callback.");
                Action toCall = null;

                lock (this.thisLock)
                {
                    this.IsChannelWorkComplete = true;
                    this.onWorkflowCorrelationProcessingComplete = onWorkflowCorrelationProcessingComplete;

                    toCall = this.onRequestSetByChannel;
                }

                if (toCall != null)
                {
                    toCall();
                }
            }

            public void NotifyMessageUpdatedByWorkflow(Message message)
            {
                this.UpdatedMessage = message;
            }

            public bool NotifyWorkflowCorrelationProcessingComplete()
            {
                Fx.Assert(this.onWorkflowCorrelationProcessingComplete != null, "This must be set before this can be called.");

                bool result = false;

                lock (this.thisLock)
                {
                    if (this.completion == Completion.SendComplete)
                    {
                        // The send has already completed so we are responsible for
                        // making sure FinalizeSendMessage is called.
                        result = true;
                    }
                    else
                    {
                        Fx.Assert(this.completion == Completion.None, "We should be the first one to complete.");

                        this.completion = Completion.CorrelationComplete;
                    }
                }

                this.onWorkflowCorrelationProcessingComplete(this.UpdatedMessage);

                return result;
            }

            public bool NotifySendComplete()
            {
                bool result = false;
                lock (this.thisLock)
                {
                    if (this.completion == Completion.CorrelationComplete)
                    {
                        // The correlation has already finished so we are responsible for
                        // making sure that FinalizeSendMessage is called.
                        result = true;
                    }
                    else
                    {
                        Fx.Assert(this.completion == Completion.None, "We should be the first one to complete.");

                        this.completion = Completion.SendComplete;
                    }
                }

                return result;
            }

            // Returns true if the channel work is actually done.  If this
            // returns true then the passed in Action will never be called.
            public bool SetWorkflowNotificationCallback(Action onRequestSetByChannel)
            {
                Fx.Assert(onRequestSetByChannel != null, "Must have a non-null callback.");

                bool result = false;
                lock (this.thisLock)
                {
                    result = this.IsChannelWorkComplete;
                    this.onRequestSetByChannel = onRequestSetByChannel;
                }

                return result;
            }

            // This three state enum allows us to determine whether
            // we are the first or second code path.  The second
            // code path needs finalize the send.
            enum Completion
            {
                None,
                SendComplete,
                CorrelationComplete
            }
        }

        // This class defines the instance data that used to store intermediate states
        // during the volatile async operation of sending a message.
        internal class SendMessageInstance
        {
            CorrelationHandle explicitChannelCorrelationHandle;
            IList<ISendMessageCallback> sendMessageCallbacks;
            ChannelFactoryReference factoryReference;
            ObjectCacheItem<ChannelFactoryReference> cacheItem;
            ObjectCache<FactoryCacheKey, ChannelFactoryReference> factoryCache;
            
            readonly InternalSendMessage parent;
            bool isUsingCacheFromExtension;

            // needed so that we can return our ClientSendChannel to the pool under Dispose
            ObjectCacheItem<Pool<IChannel>> clientChannelPool;

            public SendMessageInstance(InternalSendMessage parent, NativeActivityContext context)
            {
                this.parent = parent;

                // setup both our following state as well as any anonymous response information
                CorrelationHandle correlatesWith = (parent.CorrelatesWith == null) ? null : parent.CorrelatesWith.Get(context);
                if (correlatesWith != null && !correlatesWith.IsInitalized())
                {
                    // if send or sendReply has a correlatesWith, it should always be initialized with either content or with callbackcontext, context or 
                    // ResponseContext
                    throw FxTrace.Exception.AsError(new ValidationException(SR.SendWithUninitializedCorrelatesWith(this.parent.OperationName ?? string.Empty)));
                }

                if (correlatesWith == null)
                {
                    this.AmbientHandle = context.Properties.Find(CorrelationHandle.StaticExecutionPropertyName) as CorrelationHandle;
                    correlatesWith = this.AmbientHandle;
                }

                this.CorrelatesWith = correlatesWith;

                if (!parent.IsSendReply)
                {
                    // we're a client-side request

                    // Validate correlation handle
                    CorrelationHandle requestReplyCorrelationHandle = GetExplicitRequestReplyCorrelationHandle(context, parent.correlationInitializers);
                    if (parent.IsOneWay)
                    {
                        if (requestReplyCorrelationHandle != null)
                        {
                            // this is a one-way send , we should not have a RequestReply Correlation initializer
                            throw FxTrace.Exception.AsError(new InvalidOperationException(SR.RequestReplyHandleShouldNotBePresentForOneWay));

                        }
                    }
                    else // two-way send
                    {
                        if (requestReplyCorrelationHandle == null && this.AmbientHandle == null)
                        {
                            this.AmbientHandle = context.Properties.Find(CorrelationHandle.StaticExecutionPropertyName) as CorrelationHandle;
                            if (this.AmbientHandle == null)
                            {
                                // we neither have a channelHandle nor an ambientHandle
                                throw FxTrace.Exception.AsError(new InvalidOperationException(
                                    SR.SendMessageNeedsToPairWithReceiveMessageForTwoWayContract(parent.OperationName ?? string.Empty)));
                            }
                        }
                    }

                    // Formatter and OperationContract should be  removed from CorrelationRequestContext
                    // This will be done when SendMessage/ReceiveMessage is completely removed from the code base
                    this.RequestContext = new CorrelationRequestContext();

                    // callback correlationHandle is used for initalizing context based correlation 
                    this.ContextBasedCorrelationHandle = CorrelationHandle.GetExplicitCallbackCorrelation(context, parent.correlationInitializers);

                    // by default we use the channel factory cache from the extension
                    isUsingCacheFromExtension = true;
                }
                else
                {
                    // we are a server-side following send
                    CorrelationResponseContext responseContext;
                    if (correlatesWith == null || !correlatesWith.TryAcquireResponseContext(context, out responseContext))
                    {
                        throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CorrelatedContextRequiredForAnonymousSend));
                    }

                    // Contract inference logic should validate that the Receive and Following send do not have conflicting data(e.g., OperationName)

                    this.ResponseContext = responseContext;

                    // in case of Context based correlation, we use context handle to initialize correlation
                    this.ContextBasedCorrelationHandle = CorrelationHandle.GetExplicitContextCorrelation(context, parent.correlationInitializers);
                }

                this.sendMessageCallbacks = MessagingActivityHelper.GetCallbacks<ISendMessageCallback>(context.Properties);

                if (TraceUtility.MessageFlowTracing)
                {
                    this.ActivityInstanceId = context.ActivityInstanceId;
                }
            }

            public InternalSendMessage Activity
            {
                get
                {
                    return this.parent;
                }
            }

            public CorrelationHandle CorrelatesWith
            {
                get;
                private set;
            }

            public CorrelationHandle AmbientHandle
            {
                get;
                private set;
            }

            public CorrelationHandle ContextBasedCorrelationHandle
            {
                get;
                private set;
            }

            public EndpointAddress EndpointAddress
            {
                get;
                set;
            }

            public IChannel ClientSendChannel
            {
                get;
                private set;
            }

            public CorrelationSynchronizer CorrelationSynchronizer
            {
                get;
                set;
            }

            public Message RequestOrReply
            {
                get;
                set;
            }

            public OperationContext OperationContext
            {
                get;
                set;
            }

            public CorrelationRequestContext RequestContext
            {
                get;
                private set;
            }

            // This is required for setting adding the ChannelFactory to the cache once it is opened
            public ObjectCache<FactoryCacheKey, ChannelFactoryReference> FactoryCache
            {
                get
                {
                    return this.factoryCache;
                }
            }

            // This is required for setting adding the ChannelFactory to the cache once it is opened
            public SendMessageChannelCache CacheExtension
            {
                get;
                set;
            }

            //This is required for returning it to the cache after use
            public ChannelFactoryReference FactoryReference
            {
                get
                {
                    return this.factoryReference;
                }
            }

            public CorrelationResponseContext ResponseContext
            {
                get;
                private set;
            }

            public CorrelationKeyCalculator CorrelationKeyCalculator
            {
                get;
                private set;
            }

            public CorrelationCallbackContext CorrelationCallbackContext
            {
                get;
                set;
            }

            public CorrelationContext CorrelationContext
            {
                get;
                set;
            }

            public Guid AmbientActivityId
            {
                get;
                set;
            }

            public ICollection<string> CorrelationSendNames
            {
                get;
                private set;
            }

            public Guid E2EActivityId
            {
                get;
                set;
            }

            public string ActivityInstanceId
            {
                get;
                private set;
            }

            public bool IsCorrelationInitialized
            {
                get;
                set;
            }

            public void SetupFactoryReference(ObjectCacheItem<ChannelFactoryReference> cacheItem, ChannelFactoryReference newFactoryReference, ObjectCache<FactoryCacheKey, ChannelFactoryReference> factoryCache)
            {
                this.factoryCache = factoryCache;
                if (this.factoryCache == null)
                {
                    isUsingCacheFromExtension = false;
                }
                if (cacheItem != null)
                {
                    // we found the item in our cache
                    Fx.Assert(newFactoryReference == null, "need one of cacheItem or newFactoryReference");
                    Fx.Assert(cacheItem.Value != null, "should have valid value");
                    this.cacheItem = cacheItem;
                    this.factoryReference = cacheItem.Value;
                }
                else
                {
                    Fx.Assert(newFactoryReference != null, "need one of cacheItem or newFactoryReference");
                    this.factoryReference = newFactoryReference;
                }
            }

            public void RegisterNewCacheItem(ObjectCacheItem<ChannelFactoryReference> newCacheItem)
            {
                Fx.Assert(this.cacheItem == null, "should only be called for new cache items");
                this.cacheItem = newCacheItem;
            }

            public CorrelationHandle GetExplicitRequestReplyCorrelationHandle(NativeActivityContext context, Collection<CorrelationInitializer> additionalCorrelations)
            {
                if (this.explicitChannelCorrelationHandle == null)
                {
                    this.explicitChannelCorrelationHandle = CorrelationHandle.GetExplicitRequestReplyCorrelation(context, additionalCorrelations);
                }
                return this.explicitChannelCorrelationHandle;
            }

            public void RegisterCorrelationBehavior(CorrelationQueryBehavior correlationBehavior)
            {
                Fx.Assert(correlationBehavior != null, "caller must verify");
                if (correlationBehavior.ScopeName != null)
                {
                    CorrelationKeyCalculator keyCalculator = correlationBehavior.GetKeyCalculator();
                    if (keyCalculator != null)
                    {
                        this.CorrelationKeyCalculator = keyCalculator;
                        if (this.RequestContext != null)
                        {
                            this.RequestContext.CorrelationKeyCalculator = keyCalculator;
                            // for requests, determine if we should be using the correlation callback
                            if (correlationBehavior.SendNames != null && correlationBehavior.SendNames.Count > 0)
                            {
                                this.CorrelationSendNames = correlationBehavior.SendNames;
                            }
                        }
                    }
                }
            }

            public void ProcessMessagePropertyCallbacks()
            {
                if (this.sendMessageCallbacks != null)
                {
                    foreach (ISendMessageCallback sendMessageCallback in this.sendMessageCallbacks)
                    {
                        sendMessageCallback.OnSendMessage(this.OperationContext);
                    }
                }
            }

            public void PopulateClientChannel()
            {
                Fx.Assert(this.ClientSendChannel == null && this.clientChannelPool == null, "should only be called once per instance");
                this.ClientSendChannel = this.FactoryReference.TakeChannel(this.EndpointAddress, out this.clientChannelPool);
            }

            public void Dispose()
            {
                if (this.ClientSendChannel != null)
                {
                    Fx.Assert(this.FactoryReference != null, "Must have a factory reference.");
                    this.FactoryReference.ReturnChannel(this.ClientSendChannel, this.clientChannelPool);
                    this.ClientSendChannel = null;
                    this.clientChannelPool = null;
                }

                if (this.cacheItem != null)
                {
                    this.cacheItem.ReleaseReference();

                    // if we are using the FactoryCache from the extension, store the last used cacheItem and extension
                    if (this.isUsingCacheFromExtension)
                    {
                        this.parent.lastUsedFactoryCacheItem = new KeyValuePair<ObjectCacheItem<ChannelFactoryReference>, SendMessageChannelCache>(this.cacheItem, this.CacheExtension);
                    }
                    this.cacheItem = null;
                }
            }

            public Exception GetCompletionException()
            {
                if (this.RequestContext != null)
                {
                    // We got an exception trying to send message or receive a reply
                    // Scenario: ContractFilterMismatch at serverside if the message action is not matched correctly
                    return this.RequestContext.Exception;
                }
                else
                {
                    return this.ResponseContext.Exception;
                }
            }
        }

        class MessageCorrelationCallbackMessageProperty : CorrelationCallbackMessageProperty
        {
            public MessageCorrelationCallbackMessageProperty(ICollection<string> neededData, SendMessageInstance instance)
                : base(neededData)
            {
                this.Instance = instance;
            }

            protected MessageCorrelationCallbackMessageProperty(MessageCorrelationCallbackMessageProperty callback)
                : base(callback)
            {
                this.Instance = callback.Instance;
            }

            public SendMessageInstance Instance
            {
                get;
                private set;
            }

            public override IMessageProperty CreateCopy()
            {
                return new MessageCorrelationCallbackMessageProperty(this);
            }

            protected override IAsyncResult OnBeginFinalizeCorrelation(Message message, TimeSpan timeout, AsyncCallback callback, object state)
            {
                return new FinalizeCorrelationAsyncResult(this, message, callback, state);
            }

            protected override Message OnEndFinalizeCorrelation(IAsyncResult result)
            {
                return FinalizeCorrelationAsyncResult.End(result);
            }

            protected override Message OnFinalizeCorrelation(Message message, TimeSpan timeout)
            {
                return OnEndFinalizeCorrelation(OnBeginFinalizeCorrelation(message, timeout, null, null));
            }

            class FinalizeCorrelationAsyncResult : AsyncResult
            {
                Message message;
                Completion completion;

                object thisLock;

                public FinalizeCorrelationAsyncResult(MessageCorrelationCallbackMessageProperty property, Message message,
                    AsyncCallback callback, object state)
                    : base(callback, state)
                {
                    bool completeSelf = false;
                    if (property.Instance.IsCorrelationInitialized)
                    {
                        // we do not modify the message since correlation is not calculated again
                        this.message = message;
                        completeSelf = true;
                    }
                    else
                    {
                        property.Instance.IsCorrelationInitialized = true;
                        this.thisLock = new object();

                        property.Instance.RequestOrReply = message;

                        property.Instance.CorrelationSynchronizer.NotifyRequestSetByChannel(new Action<Message>(OnWorkflowCorrelationProcessingComplete));

                        // We have to do this dance with the lock because
                        // we aren't sure if we've been running [....] or not.
                        // NOTE: It is possible for us to go async and
                        // still decide we're completing [....].  This is fine
                        // as it does not violate the async pattern since
                        // the work is done by the time Begin completes.
                        completeSelf = false;

                        lock (this.thisLock)
                        {
                            if (completion == Completion.WorkflowCorrelationProcessingComplete)
                            {
                                completeSelf = true;
                            }
                            else
                            {
                                Fx.Assert(this.completion == Completion.None, "We must be not ready then.");

                                this.completion = Completion.ConstructorComplete;
                            }
                        }
                    }
                    if (completeSelf)
                    {
                        Complete(true);
                    }

                }

                void OnWorkflowCorrelationProcessingComplete(Message updatedMessage)
                {
                    this.message = updatedMessage;

                    // We have to do this dance with the lock because
                    // we aren't sure if we've been running [....] or not.
                    // NOTE: It is possible for us to go async and
                    // still decide we're completing [....].  This is fine
                    // as it does not violate the async pattern since
                    // the work is done by the time Begin completes.
                    bool completeSelf = false;

                    lock (this.thisLock)
                    {
                        if (this.completion == Completion.ConstructorComplete)
                        {
                            completeSelf = true;
                        }
                        else
                        {
                            Fx.Assert(this.completion == Completion.None, "We must be not ready then.");

                            this.completion = Completion.WorkflowCorrelationProcessingComplete;
                        }
                    }

                    if (completeSelf)
                    {
                        Complete(false);
                    }
                }

                public static Message End(IAsyncResult result)
                {
                    FinalizeCorrelationAsyncResult thisPtr = AsyncResult.End<FinalizeCorrelationAsyncResult>(result);
                    return thisPtr.message;
                }

                // This three state enum allows us to determine whether
                // we are the first or second code path.  The second
                // code path needs to complete the async result.
                enum Completion
                {
                    None,
                    ConstructorComplete,
                    WorkflowCorrelationProcessingComplete
                }
            }
        }

        [DataContract]
        internal class VolatileSendMessageInstance
        {
            public VolatileSendMessageInstance()
            {
            }

            // Note that we do not mark this DataMember since we dont want it to be serialized
            public SendMessageInstance Instance { get; set; }
        }

        // Represents an item in our object cache. Stores a ChannelFactory and an associated pool of channels
        internal sealed class ChannelFactoryReference : IDisposable
        {
            static AsyncCallback onDisposeCommunicationObject = Fx.ThunkCallback(new AsyncCallback(OnDisposeCommunicationObject));
            Action<Pool<IChannel>> disposeChannelPool;
            readonly FactoryCacheKey factoryKey;
            readonly ServiceEndpoint targetEndpoint;
            ChannelFactory channelFactory;
            ObjectCache<EndpointAddress, Pool<IChannel>> channelCache;
            CorrelationQueryBehavior correlationQueryBehavior;
            Func<Pool<IChannel>> createChannelCacheItem;

            // Aborting a channel that is in the middle of closing can cause an ObjectDisposedException in the Close.
            // We need to prevent DisposeCommunicationObject(ChannelFactory) from racing with a call to 
            // DisposeCommunicationObject()on an individual channel.
            // This lock will be used to synchronize calls into DisposeCommunicationObject method.
            object disposeLock = new object();

            public ChannelFactoryReference(FactoryCacheKey factoryKey, ServiceEndpoint targetEndpoint, ChannelCacheSettings channelCacheSettings)
            {
                Fx.Assert(channelCacheSettings != null, " channelCacheSettings should not be null");
                Fx.Assert(factoryKey != null, " factoryKey should not be null");
                Fx.Assert(targetEndpoint != null, " targetEndpoint should not be null");

                this.factoryKey = factoryKey;
                this.targetEndpoint = targetEndpoint;
                                
                if (factoryKey.IsOperationContractOneWay)
                {
                    this.channelFactory = new ChannelFactory<IOutputChannel>(targetEndpoint);
                }
                else
                {
                    this.channelFactory = new ChannelFactory<IRequestChannel>(targetEndpoint);
                }

                this.channelFactory.UseActiveAutoClose = true;
                this.channelFactory.Credentials.Windows.AllowedImpersonationLevel = factoryKey.TokenImpersonationLevel;

                ObjectCacheSettings channelSettings = new ObjectCacheSettings
                {
                    CacheLimit = channelCacheSettings.MaxItemsInCache,
                    IdleTimeout = channelCacheSettings.IdleTimeout,
                    LeaseTimeout = channelCacheSettings.LeaseTimeout
                };

                this.disposeChannelPool = new Action<Pool<IChannel>>(this.DisposeChannelPool);

                // our channel cache is keyed solely on endpoint since we don't allow the via to be dynamic
                // for a ChannelFactoryReference
                this.channelCache = new ObjectCache<EndpointAddress, Pool<IChannel>>(channelSettings)
                {
                    DisposeItemCallback = this.disposeChannelPool
                };
                this.createChannelCacheItem = () => new Pool<IChannel>(channelCacheSettings.MaxItemsInCache);
            }

            public CorrelationQueryBehavior CorrelationQueryBehavior
            {
                get
                {
                    if (this.correlationQueryBehavior == null)
                    {
                        this.correlationQueryBehavior = this.targetEndpoint.Behaviors.Find<CorrelationQueryBehavior>();
                    }

                    return this.correlationQueryBehavior;
                }
            }
            
            // As a perf optimization, we provide this property to avoid async result/callback creations
            public bool NeedsOpen
            {
                get
                {
                    return this.channelFactory.State == CommunicationState.Created;
                }
            }

            public IAsyncResult BeginOpen(AsyncCallback callback, object state)
            {
                Fx.Assert(NeedsOpen, "caller should check NeedsOpen first");
                return this.channelFactory.BeginOpen(callback, state);
            }

            // after open we should be added to a cache if one is provided
            public ObjectCacheItem<ChannelFactoryReference> EndOpen(IAsyncResult result, ObjectCache<FactoryCacheKey, ChannelFactoryReference> factoryCache)
            {
                this.channelFactory.EndOpen(result);

                ObjectCacheItem<ChannelFactoryReference> cacheItem = null;
                if (factoryCache != null)
                {
                    cacheItem = factoryCache.Add(this.factoryKey, this);
                }

                return cacheItem;
            }

            [SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DisposableFieldsShouldBeDisposed,
                Justification = "disposable field is being disposed using DisposeCommunicationObject")]
            public void Dispose()
            {
                lock (this.disposeLock)
                {
                    DisposeCommunicationObject(this.channelFactory);
                }
            }

            public IChannel TakeChannel(EndpointAddress endpointAddress, out ObjectCacheItem<Pool<IChannel>> channelPool)
            {
                channelPool = this.channelCache.Take(endpointAddress, this.createChannelCacheItem);
                Fx.Assert(channelPool != null, "Take with delegate should always return a valid Item");

                IChannel result = null;

                lock (channelPool.Value)
                {
                    result = channelPool.Value.Take();
                }

                // make an effort to kill stale channels
                ServiceChannel serviceChannel = result as ServiceChannel;
                if (result != null && (result.State != CommunicationState.Opened || (serviceChannel != null && serviceChannel.Binder.Channel.State != CommunicationState.Opened)))
                {
                    result.Abort();
                    result = null;
                }

                if (result == null)
                {
                    Uri via = null;

                    // service endpoint always sets the ListenUri, which will break default callback-context behavior
                    if (this.targetEndpoint.Address != null && this.targetEndpoint.Address.Uri != this.targetEndpoint.ListenUri)
                    {
                        via = this.targetEndpoint.ListenUri;
                    }

                    if (this.factoryKey.IsOperationContractOneWay)
                    {
                        result = ((ChannelFactory<IOutputChannel>)this.channelFactory).CreateChannel(endpointAddress, via);
                    }
                    else
                    {
                        result = ((ChannelFactory<IRequestChannel>)this.channelFactory).CreateChannel(endpointAddress, via);
                    }
                }

                if (!(result is ServiceChannel))
                {
                    result = ServiceChannelFactory.GetServiceChannel(result);
                }

                return result;
            }

            public void ReturnChannel(IChannel channel, ObjectCacheItem<Pool<IChannel>> channelPool)
            {
                bool shouldDispose = channel.State != CommunicationState.Opened;

                // channel is in open state, try returning it to the pool
                if (!shouldDispose)
                {
                    lock (channelPool.Value)
                    {
                        shouldDispose = !channelPool.Value.Return(channel);
                    }
                }

                if (shouldDispose)
                {
                    lock (this.disposeLock)
                    {
                        if (this.channelFactory.State != CommunicationState.Closed &&
                            this.channelFactory.State != CommunicationState.Closing)
                        {
                            // not caching the channel, so we need to close it
                            DisposeCommunicationObject(channel);
                        }
                    }
                }

                // and return our cache item
                channelPool.ReleaseReference();
            }

            public void DisposeChannelPool(Pool<IChannel> channelPool)
            {
                IChannel channel;

                // we don't need to lock the Take from the Pool here since no one will be accessing this anymore
                // Dispose will be called under a lock from the ObjectCacheItem
                while ((channel = channelPool.Take()) != null)
                {
                    lock (this.disposeLock)
                    {
                        if (this.channelFactory.State != CommunicationState.Closed &&
                            this.channelFactory.State != CommunicationState.Closing)
                        {
                            DisposeCommunicationObject(channel);
                        }
                    }
                }
            }

            static void DisposeCommunicationObject(ICommunicationObject communicationObject)
            {
                bool success = false;
                try
                {
                    if (communicationObject.State == CommunicationState.Opened)
                    {
                        IAsyncResult result = communicationObject.BeginClose(ServiceDefaults.CloseTimeout, onDisposeCommunicationObject, communicationObject);
                        if (result.CompletedSynchronously)
                        {
                            communicationObject.EndClose(result);
                        }
                        success = true;
                    }
                }
                catch (CommunicationException)
                {
                    // expected, we'll abort
                }
                catch (TimeoutException)
                {
                    // expected, we'll abort
                }
                finally
                {
                    if (!success)
                    {
                        communicationObject.Abort();
                    }
                }
            }

            static void OnDisposeCommunicationObject(IAsyncResult result)
            {
                if (result.CompletedSynchronously)
                {
                    return;
                }
                ICommunicationObject communicationObject = (ICommunicationObject)result.AsyncState;

                bool success = false;
                try
                {
                    communicationObject.EndClose(result);
                    success = true;
                }
                catch (CommunicationException)
                {
                    // expected, we'll abort
                }
                catch (TimeoutException)
                {
                    // expected, we'll abort
                }
                catch (ObjectDisposedException)
                {
                    // expected,
                    // ObjectDisposedException may be thrown if you try to abort ClientSecurityDuplexSessionChannel that is in the middle of closing.
                    // we'll abort
                }
                finally
                {
                    if (!success)
                    {
                        communicationObject.Abort();
                    }
                }
            }
        }

        internal class FactoryCacheKey : IEquatable<FactoryCacheKey>
        {
            Endpoint endpoint;
            bool isOperationContractOneWay;
            
            TokenImpersonationLevel tokenImpersonationLevel;
            ContractDescription contract;
            Collection<CorrelationQuery> correlationQueries;
            string endpointConfigurationName;

            public FactoryCacheKey(Endpoint endpoint, string endpointConfigurationName, bool isOperationOneway,
                TokenImpersonationLevel tokenImpersonationLevel, ContractDescription contractDescription,
                ICollection<CorrelationQuery> correlationQueries)
            {
                this.endpoint = endpoint;
                this.endpointConfigurationName = endpointConfigurationName;
                this.isOperationContractOneWay = isOperationOneway;
                this.tokenImpersonationLevel = tokenImpersonationLevel;
                this.contract = contractDescription;

                if (correlationQueries != null)
                {
                    this.correlationQueries = new Collection<CorrelationQuery>();
                    foreach (CorrelationQuery query in correlationQueries)
                    {
                        this.correlationQueries.Add(query);
                    }
                }
            }

            public bool IsOperationContractOneWay
            {
                get
                {
                    return this.isOperationContractOneWay;
                }
            }

            public TokenImpersonationLevel TokenImpersonationLevel
            {
                get
                {
                    return this.tokenImpersonationLevel;
                }
            }

            public bool Equals(FactoryCacheKey other)
            {
                if (object.ReferenceEquals(this, other))
                {
                    return true;
                }

                if (other == null)
                {
                    // this means only one of them is null
                    return false;
                }

                // 1) Compare Endpoint/EndpointConfigurationName
                if ((this.endpoint == null && other.endpoint != null) ||
                    (other.endpoint == null && this.endpoint != null))
                {
                    return false;
                }

                // if endpoint is not null we compare the endpoint, else we compare the endpointconfiguration
                if (this.endpoint != null)
                {
                    if (!object.ReferenceEquals(this.endpoint, other.endpoint))
                    {
                        // Binding -
                        // We are comparing by ref here, can we compare binding elements instead
                        if (this.endpoint.Binding != other.endpoint.Binding)
                        {
                            return false;
                        }
                    }
                }
                else if (this.endpointConfigurationName != other.endpointConfigurationName)
                {
                    return false;
                }

                // (2) TokenImpersonationlevel
                if (this.TokenImpersonationLevel != other.TokenImpersonationLevel)
                {
                    return false;
                }

                // (3) OperationContract.IsOneWay to decide if the ChannelFactory needs to be of type RequestChannel or OutputChannel
                if (this.IsOperationContractOneWay != other.IsOperationContractOneWay)
                {
                    return false;
                }

                // (4) Verify if the ContractDescriptions are equivalent
                if (!ContractDescriptionComparerHelper.IsContractDescriptionEquivalent(this.contract, other.contract))
                {
                    return false;
                }

                // (5) Verify the correlationquery collection
                //  For now, we verify each query by ref, so that loop scenarios would work
                //  Can we do a value comparison here?  
                if (!ContractDescriptionComparerHelper.EqualsUnordered(this.correlationQueries, other.correlationQueries))
                {
                    return false;
                }
                
                return true;
            }
            
            public override int GetHashCode()
            {
                int hashCode = 0;

                if (this.contract != null && this.contract.Name != null)
                {
                    //using ContractName as the hashcode
                    hashCode ^= this.contract.Name.GetHashCode();
                }

                if (this.endpoint != null && this.endpoint.Binding != null)
                {
                    //we compare binding by ref
                    hashCode ^= this.endpoint.Binding.GetHashCode();
                }

                return hashCode;
            }
        }
        
        static class ContractDescriptionComparerHelper
        {
            public static bool EqualsUnordered<T>(Collection<T> left, Collection<T> right) where T : class
            {
                return EqualsUnordered(left, right, (t1, t2) => t1 == t2);
            }

            public static bool IsContractDescriptionEquivalent(ContractDescription c1, ContractDescription c2)
            {
                if (c1 == c2)
                {
                    return true;
                }

                // if the contract is not one of the default contracts that we use, we only do a byref comparison
                // fully inferred contracts always have null ContractType
                if (c1.ContractType == null || c2.ContractType == null)
                {
                    return false;
                }

                //compare contractname
                return (c1 != null &&
                        c2 != null &&
                        c1.Name == c2.Name &&
                        c1.Namespace == c2.Namespace &&
                        c1.ConfigurationName == c2.ConfigurationName &&
                        c1.ProtectionLevel == c2.ProtectionLevel &&
                        c1.SessionMode == c2.SessionMode &&
                        c1.ContractType == c2.ContractType &&
                        c1.Behaviors.Count == c2.Behaviors.Count && //we have no way to verify each one
                        EqualsUnordered<OperationDescription>(c1.Operations, c2.Operations, (o1, o2) => IsOperationDescriptionEquivalent(o1, o2)));
            }

            static bool EqualsOrdered<T>(IList<T> left, IList<T> right, Func<T, T, bool> equals)
            {
                if (left == null)
                {
                    return (right == null || right.Count == 0);
                }
                else if (right == null)
                {
                    return left.Count == 0;
                }
                if (left.Count != right.Count)
                {
                    return false;
                }
                for (int i = 0; i < left.Count; i++)
                {
                    if (!equals(left[i], right[i]))
                    {
                        return false;
                    }
                }
                return true;
            }

            static bool EqualsUnordered<T>(Collection<T> left, Collection<T> right, Func<T, T, bool> equals)
            {
                if (left == null)
                {
                    return (right == null || right.Count == 0);
                }
                else if (right == null)
                {
                    return left.Count == 0;
                }
                // This check ensures that the lists have the same contents, but does not verify that they have the same
                // quantity of each item if they are duplicates.
                return left.Count == right.Count &&
                    left.All(leftItem => right.Any(rightItem => equals(leftItem, rightItem))) &&
                    right.All(rightItem => left.Any(leftItem => equals(leftItem, rightItem)));
            }

            static bool IsOperationDescriptionEquivalent(OperationDescription o1, OperationDescription o2)
            {
                if (o1 == o2)
                {
                    return true;
                }

                return (o1.Name == o2.Name &&
                        o1.ProtectionLevel == o2.ProtectionLevel &&
                        o1.IsOneWay == o2.IsOneWay &&
                        IsTransactionBehaviorEquivalent(o1, o2) && //we are verifying only the TransactionFlowBehavior
                        EqualsOrdered(o1.Messages, o2.Messages, (m1, m2) => IsMessageDescriptionEquivalent(m1, m2)));
            }

            static bool IsMessageDescriptionEquivalent(MessageDescription m1, MessageDescription m2)
            {
                if (m1 == m2)
                {
                    return true;
                }

                //we are comparing only action and direction
                return (m1.Action == m2.Action && m1.Direction == m2.Direction);
            }

            static bool IsTransactionBehaviorEquivalent(OperationDescription o1, OperationDescription o2)
            {
                if ((o1 == null || o2 == null) && o1 == o2)
                {
                    return true;
                }
                if (o1.Behaviors.Count == o2.Behaviors.Count)
                {
                    //we are only going to check the TransactionFlowAttribute
                    TransactionFlowAttribute t1 = o1.Behaviors.Find<TransactionFlowAttribute>();
                    TransactionFlowAttribute t2 = o2.Behaviors.Find<TransactionFlowAttribute>();
                    if ((t1 == null && t2 != null) || (t2 == null && t1 != null))
                    {
                        return false;

                    }
                    //verify if both have the same value for TransactionFlowOption
                    if ((t1 != null) && (t1.Transactions != t2.Transactions))
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
        }
    }
}