File: SqlTrackingService.cs

package info (click to toggle)
mono 6.14.1%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,282,732 kB
  • sloc: cs: 11,182,461; xml: 2,850,281; ansic: 699,123; cpp: 122,919; perl: 58,604; javascript: 30,841; asm: 21,845; makefile: 19,602; sh: 10,973; python: 4,772; pascal: 925; sql: 859; sed: 16; php: 1
file content (2635 lines) | stat: -rw-r--r-- 116,819 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
using System.Timers;
using System.Diagnostics;
using System.Reflection;
using System.Workflow.Runtime;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime.Hosting;
using System.Text.RegularExpressions;
using System.Threading;
using System.Transactions;
using System.Globalization;
using System.Workflow.ComponentModel.Serialization;
using System.ComponentModel.Design.Serialization;
using System.Xml;
using System.Configuration;


namespace System.Workflow.Runtime.Tracking
{
    [Obsolete("The System.Workflow.* types are deprecated.  Instead, please use the new types from System.Activities.*")]
    public sealed class SqlTrackingService : TrackingService, IProfileNotification
    {
        #region Private/Protected Members

        private bool _isTrans = true;
        private bool _partition = false;
        private bool _defaultProfile = true;
        private bool _enableRetries = false;
        private bool _ignoreCommonEnableRetries = false;

        private DateTime _lastProfileCheck;
        private System.Timers.Timer _timer = new System.Timers.Timer();
        private double _interval = 60000;
        //private static int _deadlock = 1205;
        private TypeKeyedCollection _types = new TypeKeyedCollection();
        private object _typeCacheLock = new object();
        private WorkflowCommitWorkBatchService _transactionService;
        private DbResourceAllocator _dbResourceAllocator;

        private static Version UnknownProfileVersionId = new Version(0, 0);

        // Saved from constructor input to be used in service start initialization        
        private NameValueCollection _parameters;
        string _unvalidatedConnectionString;

        private delegate void ExecuteRetriedDelegate(object param);

        #endregion

        #region Configuration Properties

        public string ConnectionString
        {
            get { return _unvalidatedConnectionString; }
        }
        /// <summary>
        /// Determines if tracking data should be held and transactionally written to the database at persistence points.
        /// </summary>
        /// <value></value>
        public bool IsTransactional
        {
            get { return _isTrans; }
            set
            {
                _isTrans = value;
            }
        }
        /// <summary>
        /// Indicates that records should be moved from the active instance tables to the appropriate parition tables when the instance completes.
        /// </summary>
        public bool PartitionOnCompletion
        {
            get { return _partition; }
            set { _partition = value; }
        }
        /// <summary>
        /// Determines if the default profile should be used for workflow types that do not have a profile specified for them.
        /// </summary>
        /// <value></value>
        public bool UseDefaultProfile
        {
            get { return _defaultProfile; }
            set { _defaultProfile = value; }
        }

        /// <summary>
        /// The time interval, in milliseconds, at which to check the database for changes to profiles.  
        /// Default is 60000.
        /// </summary>
        /// <remarks>
        /// Setting the interval results in the next check to occur the specified number of millisecond 
        /// from the time at which the property is set.
        /// </remarks>
        public double ProfileChangeCheckInterval
        {
            get { return _interval; }
            set
            {
                if (value <= 0)
                    throw new ArgumentException(ExecutionStringManager.InvalidProfileCheckValue);
                _interval = value;
                //
                // Set the timer's interval.
                // This will reset the timer
                _timer.Interval = _interval;
            }
        }

        public bool EnableRetries
        {
            get { return _enableRetries; }
            set
            {
                _enableRetries = value;
                _ignoreCommonEnableRetries = true;
            }
        }

        internal DbResourceAllocator DbResourceAllocator
        {
            get { return this._dbResourceAllocator; }
        }

        #endregion

        #region Construction

        public SqlTrackingService(string connectionString)
        {
            if (String.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString", ExecutionStringManager.MissingConnectionString);

            _unvalidatedConnectionString = connectionString;
        }

        public SqlTrackingService(NameValueCollection parameters)
        {
            if (parameters == null)
                throw new ArgumentNullException("parameters", ExecutionStringManager.MissingParameters);

            if (parameters.Count > 0)
            {
                foreach (string key in parameters.Keys)
                {
                    if (0 == string.Compare("IsTransactional", key, StringComparison.OrdinalIgnoreCase))
                        _isTrans = bool.Parse(parameters[key]);
                    else if (0 == string.Compare("UseDefaultProfile", key, StringComparison.OrdinalIgnoreCase))
                        _defaultProfile = bool.Parse(parameters[key]);
                    else if (0 == string.Compare("PartitionOnCompletion", key, StringComparison.OrdinalIgnoreCase))
                        _partition = bool.Parse(parameters[key]);
                    else if (0 == string.Compare("ProfileChangeCheckInterval", key, StringComparison.OrdinalIgnoreCase))
                    {
                        _interval = double.Parse(parameters[key], NumberFormatInfo.InvariantInfo);
                        if (_interval <= 0)
                            throw new ArgumentException(ExecutionStringManager.InvalidProfileCheckValue);
                    }
                    else if (0 == string.Compare("ConnectionString", key, StringComparison.OrdinalIgnoreCase))
                        _unvalidatedConnectionString = parameters[key];
                    else if (0 == string.Compare("EnableRetries", key, StringComparison.OrdinalIgnoreCase))
                    {
                        _enableRetries = bool.Parse(parameters[key]);
                        _ignoreCommonEnableRetries = true;
                    }
                }
            }

            _parameters = parameters;
        }

        #endregion

        #region WorkflowRuntimeService

        override protected internal void Start()
        {
            _lastProfileCheck = DateTime.UtcNow;

            _dbResourceAllocator = new DbResourceAllocator(this.Runtime, _parameters, _unvalidatedConnectionString);

            // Check connection string mismatch if using SharedConnectionWorkflowTransactionService
            _transactionService = this.Runtime.GetService<WorkflowCommitWorkBatchService>();
            _dbResourceAllocator.DetectSharedConnectionConflict(_transactionService);

            //
            // If we didn't find a local value for enable retries
            // check in the common section
            if ((!_ignoreCommonEnableRetries) && (null != base.Runtime))
            {
                NameValueConfigurationCollection commonConfigurationParameters = base.Runtime.CommonParameters;
                if (commonConfigurationParameters != null)
                {
                    // Then scan for connection string in the common configuration parameters section
                    foreach (string key in commonConfigurationParameters.AllKeys)
                    {
                        if (string.Compare("EnableRetries", key, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            _enableRetries = bool.Parse(commonConfigurationParameters[key].Value);
                            break;
                        }
                    }
                }
            }

            _timer.Interval = _interval;
            _timer.AutoReset = false; // ensure that only one timer thread is checking for profile changes at a time
            _timer.Elapsed += new ElapsedEventHandler(CheckProfileChanges);
            _timer.Start();

            base.Start();
        }

        #endregion WorkflowRuntimeService

        #region IProfileNotification Implementation

        protected internal override TrackingChannel GetTrackingChannel(TrackingParameters parameters)
        {
            if (null == parameters)
                throw new ArgumentNullException("parameters");

            //
            // Return a new channel for this instance
            // Give it the parameters and this to store
            return new SqlTrackingChannel(parameters, this);
        }

        public event EventHandler<ProfileUpdatedEventArgs> ProfileUpdated;

        public event EventHandler<ProfileRemovedEventArgs> ProfileRemoved;

        protected internal override TrackingProfile GetProfile(Type workflowType, Version profileVersion)
        {
            if (null == workflowType)
                throw new ArgumentNullException("workflowType");

            // parameter wantToCreateDefault = false:
            // looking for a specific version that has already been running with this instance; don't use a default here
            return GetProfileByScheduleType(workflowType, profileVersion, false);
        }

        protected internal override bool TryGetProfile(Type workflowType, out TrackingProfile profile)
        {
            if (null == workflowType)
                throw new ArgumentNullException("workflowType");

            profile = GetProfileByScheduleType(workflowType, SqlTrackingService.UnknownProfileVersionId, _defaultProfile);

            if (null == profile)
                return false;
            else
                return true;
        }

        protected internal override TrackingProfile GetProfile(Guid scheduleInstanceId)
        {
            TrackingProfile profile = null;
            GetProfile(scheduleInstanceId, out profile);
            return profile;
        }

        private bool GetProfile(Guid scheduleInstanceId, out TrackingProfile profile)
        {
            profile = null;

            DbCommand cmd = this._dbResourceAllocator.NewCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[dbo].[GetInstanceTrackingProfile]";
            cmd.Parameters.Add(this._dbResourceAllocator.NewDbParameter("@InstanceId", scheduleInstanceId));

            DbDataReader reader = null;
            try
            {
                reader = ExecuteReaderRetried(cmd, CommandBehavior.CloseConnection);
                //
                // Should only reach here in non exception state
                if (!reader.HasRows)
                {
                    //
                    // Didn't find a specific profile for this instance
                    reader.Close();
                    profile = null;
                    return false;
                }
                else
                {
                    if (!reader.Read())
                    {
                        reader.Close();
                        profile = null;
                        return false;
                    }

                    if (reader.IsDBNull(0))
                        profile = null;
                    else
                    {
                        string tmp = reader.GetString(0);
                        TrackingProfileSerializer serializer = new TrackingProfileSerializer();
                        StringReader pReader = null;

                        try
                        {
                            pReader = new StringReader(tmp);
                            profile = serializer.Deserialize(pReader);
                        }
                        finally
                        {
                            if (null != pReader)
                                pReader.Close();
                        }
                    }
                    return true;
                }
            }
            finally
            {
                if ((null != reader) && (!reader.IsClosed))
                    reader.Close();

                if ((null != cmd) && (null != cmd.Connection) && (ConnectionState.Closed != cmd.Connection.State))
                    cmd.Connection.Close();
            }
        }

        protected internal override bool TryReloadProfile(Type workflowType, Guid scheduleInstanceId, out TrackingProfile profile)
        {
            if (null == workflowType)
                throw new ArgumentNullException("workflowType");

            bool found = GetProfile(scheduleInstanceId, out profile);

            if (found)
                return true;
            else
            {
                profile = null;
                return false;
            }
        }

        #endregion

        #region Profile Management Methods

        private void CheckProfileChanges(object sender, ElapsedEventArgs e)
        {
            DbCommand cmd = null;
            DbDataReader reader = null;
            try
            {
                if ((null == ProfileUpdated) && (null == ProfileRemoved))
                    return; // no one to notify

                Debug.WriteLine("Checking for updated profiles...");

                cmd = this._dbResourceAllocator.NewCommand();
                cmd.CommandText = "GetUpdatedTrackingProfiles";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add(this._dbResourceAllocator.NewDbParameter("@LastCheckDateTime", _lastProfileCheck));

                DbParameter param = this._dbResourceAllocator.NewDbParameter();
                param.ParameterName = "@MaxCheckDateTime";
                param.DbType = DbType.DateTime;
                param.Direction = System.Data.ParameterDirection.Output;

                cmd.Parameters.Add(param);

                reader = ExecuteReaderRetried(cmd, CommandBehavior.CloseConnection);
                //
                // No changes
                if (!reader.HasRows)
                    return;

                while (reader.Read())
                {
                    Type t = null;
                    string tmp = null;
                    TrackingProfile profile = null;

                    t = Assembly.Load(reader[1] as string).GetType(reader[0] as string);

                    if (null == t)
                        continue;

                    tmp = reader[2] as string;

                    if (null == tmp)
                    {
                        if (null != ProfileRemoved)
                            ProfileRemoved(this, new ProfileRemovedEventArgs(t));
                    }
                    else
                    {
                        TrackingProfileSerializer serializer = new TrackingProfileSerializer();
                        StringReader pReader = null;

                        try
                        {
                            pReader = new StringReader(tmp);
                            profile = serializer.Deserialize(pReader);
                        }
                        finally
                        {
                            if (null != pReader)
                                pReader.Close();
                        }

                        if (null != ProfileUpdated)
                            ProfileUpdated(this, new ProfileUpdatedEventArgs(t, profile));
                    }
                    Debug.WriteLine(ExecutionStringManager.UpdatedProfile + t.FullName);
                }
            }
            finally
            {
                if ((null != reader) && (!reader.IsClosed))
                    reader.Close();

                //
                // This should never be null/empty unless the proc failed which should throw
                if (null != cmd)
                {
                    //
                    // If the value is null we error'd so keep the same last time for the next check
                    if (null != cmd.Parameters[1].Value)
                        _lastProfileCheck = (DateTime)cmd.Parameters[1].Value;
                }

                if ((null != cmd) && (null != cmd.Connection) && (ConnectionState.Closed != cmd.Connection.State))
                    cmd.Connection.Close();
                //
                // Start the timer again (autoreset is false to avoid multiple threads checking for profile changes)
                _timer.Start();
            }
        }

        #endregion

        #region Private Methods

        private void ExecuteRetried(ExecuteRetriedDelegate executeRetried, object param)
        {
            short count = 0;

            DbRetry dbRetry = new DbRetry(_enableRetries);
            while (true)
            {
                try
                {
                    WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteRetried " + executeRetried.Method.Name + " start: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
                    executeRetried(param);
                    WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteRetried " + executeRetried.Method.Name + " end: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
                    break;
                }
                catch (Exception e)
                {
                    WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlTrackingService.ExecuteRetried caught exception: " + e.ToString());

                    if (dbRetry.TryDoRetry(ref count))
                    {
                        WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteRetried " + executeRetried.Method.Name + " retrying.");
                        continue;
                    }
                    throw;
                }
            }
        }

        private DbDataReader ExecuteReaderRetried(DbCommand command, CommandBehavior behavior)
        {
            DbDataReader reader = null;
            short count = 0;
            DbRetry dbRetry = new DbRetry(_enableRetries);
            while (true)
            {
                try
                {
                    ResetConnectionForCommand(command);

                    WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteReaderRetried ExecuteReader start: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
                    reader = command.ExecuteReader(behavior);
                    WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteReaderRetried ExecuteReader end: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
                    break;
                }
                catch (Exception e)
                {
                    WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlTrackingService.ExecuteReaderRetried caught exception from ExecuteReader: " + e.ToString());

                    if (dbRetry.TryDoRetry(ref count))
                    {
                        WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteReaderRetried retrying.");
                        continue;
                    }
                    throw;
                }
            }

            return reader;
        }

        private void ExecuteNonQueryRetried(DbCommand command)
        {
            short count = 0;
            DbRetry dbRetry = new DbRetry(_enableRetries);
            while (true)
            {
                try
                {
                    ResetConnectionForCommand(command);

                    WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteNonQueryRetried ExecuteNonQuery start: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
                    command.ExecuteNonQuery();
                    WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteNonQueryRetried ExecuteNonQuery end: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
                    break;
                }
                catch (Exception e)
                {
                    WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlTrackingService.ExecuteNonQueryRetried caught exception from ExecuteNonQuery: " + e.ToString());

                    if (dbRetry.TryDoRetry(ref count))
                    {
                        WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteNonQueryRetried retrying.");
                        continue;
                    }
                    throw;
                }
            }
        }

        private void ExecuteNonQueryWithTxRetried(DbCommand command)
        {
            try
            {
                short count = 0;
                DbRetry dbRetry = new DbRetry(_enableRetries);
                while (true)
                {
                    try
                    {
                        ResetConnectionForCommand(command);

                        WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteNonQueryWithTxRetried ExecuteNonQuery start: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
                        command.Transaction = command.Connection.BeginTransaction();
                        command.ExecuteNonQuery();
                        command.Transaction.Commit();
                        WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteNonQueryWithTxRetried ExecuteNonQuery end: " + DateTime.UtcNow.ToString("G", System.Globalization.CultureInfo.InvariantCulture));
                        break;
                    }
                    catch (Exception e)
                    {
                        WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "SqlTrackingService.ExecuteNonQueryWithTxRetried caught exception from ExecuteNonQuery: " + e.ToString());

                        try
                        {
                            if (null != command.Transaction)
                                command.Transaction.Rollback();
                        }
                        catch
                        {
                            //
                            // Rollback() can throw, nothing to do but ---- if this happens
                            // so that we don't lose the original exception
                        }

                        if (dbRetry.TryDoRetry(ref count))
                        {
                            WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "SqlTrackingService.ExecuteNonQueryWithTxRetried retrying.");
                            continue;
                        }

                        throw;
                    }
                }
            }
            finally
            {
                if ((null != command) && (null != command.Connection) && (ConnectionState.Closed != command.Connection.State))
                    command.Connection.Close();
            }
        }

        private void ResetConnectionForCommand(DbCommand command)
        {
            if (null == command)
                return;

            if (null != command.Connection)
            {
                if (ConnectionState.Open != command.Connection.State)
                {
                    if (ConnectionState.Closed != command.Connection.State)
                        command.Connection.Close();

                    command.Connection.Dispose();

                    command.Connection = _dbResourceAllocator.OpenNewConnectionNoEnlist();
                }
            }
        }

        internal static XmlWriter CreateXmlWriter(TextWriter output)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.IndentChars = ("\t");
            settings.OmitXmlDeclaration = true;
            settings.CloseOutput = true;

            return XmlWriter.Create(output as TextWriter, settings);
        }

        private TrackingProfile GetProfileByScheduleType(Type workflowType, Version profileVersionId, bool wantToCreateDefault)
        {
            DbCommand cmd = this._dbResourceAllocator.NewCommand();
            DbDataReader reader = null;
            TrackingProfile profile = null;

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "dbo.GetTrackingProfile";

            cmd.Parameters.Add(this._dbResourceAllocator.NewDbParameter("@TypeFullName", workflowType.FullName));
            cmd.Parameters.Add(this._dbResourceAllocator.NewDbParameter("@AssemblyFullName", workflowType.Assembly.FullName));

            if (profileVersionId != SqlTrackingService.UnknownProfileVersionId)
                cmd.Parameters.Add(this._dbResourceAllocator.NewDbParameter("@Version", profileVersionId.ToString()));

            cmd.Parameters.Add(this._dbResourceAllocator.NewDbParameter("@CreateDefault", wantToCreateDefault));
            try
            {
                reader = ExecuteReaderRetried(cmd, CommandBehavior.CloseConnection);

                if (reader.Read())
                {
                    string tmp = reader[0] as string;

                    if (null != tmp)
                    {
                        TrackingProfileSerializer serializer = new TrackingProfileSerializer();
                        StringReader pReader = null;

                        try
                        {
                            pReader = new StringReader(tmp);
                            profile = serializer.Deserialize(pReader);
                        }
                        finally
                        {
                            if (null != pReader)
                                pReader.Close();
                        }
                    }
                }
            }
            finally
            {
                if ((null != reader) && (!reader.IsClosed))
                    reader.Close();

                if ((null != cmd) && (null != cmd.Connection) && (ConnectionState.Closed != cmd.Connection.State))
                    cmd.Connection.Close();
            }

            return profile;

        }


        #endregion

        #region Private Classes

        private class TypeKeyedCollection : KeyedCollection<string, Type>
        {
            protected override string GetKeyForItem(Type item)
            {
                return item.AssemblyQualifiedName;
            }
        }

        private class SerializedDataItem : TrackingDataItem
        {
            public Type Type;
            public string StringData;
            public byte[] SerializedData;
            public bool NonSerializable;
        }

        private class SerializedEventArgs : EventArgs
        {
            public Type Type;
            public byte[] SerializedArgs;
        }

        private struct AddedActivity
        {
            public string ActivityTypeFullName;
            public string ActivityTypeAssemblyFullName;
            public string QualifiedName;
            public string ParentQualifiedName;
            public string AddedActivityActionXoml;
            public int Order;
        }

        private struct RemovedActivity
        {
            public string QualifiedName;
            public string ParentQualifiedName;
            public string RemovedActivityActionXoml;
            public int Order;
        }

        private class SerializedWorkflowChangedEventArgs : SerializedEventArgs
        {
            public IList<AddedActivity> AddedActivities = new List<AddedActivity>();
            public IList<RemovedActivity> RemovedActivities = new List<RemovedActivity>();
        }

        #endregion Private Classes

        internal class SqlTrackingChannel : TrackingChannel, IPendingWork
        {
            #region Private Members

            private SqlTrackingService _service = null;
            private string _callPathKey = null, _parentCallPathKey = null;
            private bool _isTrans = false;
            private long _internalId = -1;
            private long _tmpInternalId = -1;
            private Dictionary<string, long> _activityInstanceId = new Dictionary<string, long>(32);
            private Dictionary<string, long> _tmpActivityInstanceId = new Dictionary<string, long>(10);
            private TrackingParameters _parameters = null;
            private bool _pendingArchive = false;
            private bool _completedTerminated = false;

            private static int _activityEventBatchSize = 5;
            private static int _dataItemBatchSize = 5;
            private static int _dataItemAnnotationBatchSize = 5;
            private static int _eventAnnotationBatchSize = 5;


            #endregion

            #region Construction
            protected SqlTrackingChannel()
            {
            }

            public SqlTrackingChannel(TrackingParameters parameters, SqlTrackingService service)
            {
                if (null == service)
                    return;

                _service = service;
                _parameters = parameters;
                _isTrans = service.IsTransactional;

                GetCallPathKeys(parameters.CallPath);
                if (!_isTrans)
                {
                    //
                    // Look up instance id or insert if new instance
                    // If we're transactional we'll do this in the first IPendingWork.Commit()
                    _service.ExecuteRetried(ExecuteInsertWorkflowInstance, null);
                }
            }

            #endregion

            #region Public Properties

            private DbResourceAllocator DbResourceAllocator
            {
                get { return _service.DbResourceAllocator; }
            }

            private WorkflowCommitWorkBatchService WorkflowCommitWorkBatchService
            {
                get { return _service._transactionService; }
            }
            #endregion

            #region TrackingChannel

            protected internal override void InstanceCompletedOrTerminated()
            {
                if (_isTrans)
                {
                    //
                    // Indicate that at the next batch commit we should stamp the enddate
                    _completedTerminated = true;
                    //
                    // Indicate that when the next batch commit completes successfully we should partition this instance
                    if (_service.PartitionOnCompletion)
                        _pendingArchive = true;
                }
                else
                {
                    _service.ExecuteRetried(ExecuteSetEndDate, null);

                    if (_service.PartitionOnCompletion)
                        _service.ExecuteRetried(PartitionInstance, null);
                }
            }

            private void PartitionInstance(object param)
            {
                DbCommand command = null;
                try
                {
                    //
                    // Allow enlisting if there is an ambient tx
                    // This can only happen on a host initiated terminate in V1.
                    DbConnection connection = DbResourceAllocator.OpenNewConnection(false);
                    command = DbResourceAllocator.NewCommand(connection);
                    command.CommandText = "[dbo].[PartitionWorkflowInstance]";
                    command.CommandType = CommandType.StoredProcedure;

                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", _internalId));

                    command.ExecuteNonQuery();
                }
                finally
                {
                    if ((null != command) && (null != command.Connection) && (ConnectionState.Closed != command.Connection.State))
                        command.Connection.Close();
                }
            }

            private void ExecuteSetEndDate(object param)
            {
                DbCommand command = null;
                try
                {
                    //
                    // Allow enlisting if there is an ambient tx
                    // This can only happen on a host initiated terminate in V1.
                    DbConnection connection = DbResourceAllocator.OpenNewConnection(false);
                    command = DbResourceAllocator.NewCommand(connection);
                    ExecuteSetEndDate(_internalId, command);
                }
                finally
                {
                    if ((null != command) && (null != command.Connection) && (ConnectionState.Closed != command.Connection.State))
                        command.Connection.Close();
                }
            }

            private void ExecuteSetEndDate(long internalId, DbCommand command)
            {
                if (null == command)
                    throw new ArgumentNullException("command");

                command.Parameters.Clear();
                command.CommandText = "[dbo].[SetWorkflowInstanceEndDateTime]";
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", internalId));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EndDateTime", DateTime.UtcNow));
                command.ExecuteNonQuery();
            }

            protected internal override void Send(TrackingRecord record)
            {
                if ((Guid.Empty == _parameters.InstanceId) || (null == record))
                    throw new ArgumentException(ExecutionStringManager.MissingParametersTrack);

                if (record is ActivityTrackingRecord)
                {
                    ActivityTrackingRecord act = record as ActivityTrackingRecord;
                    if (_isTrans)
                        WorkflowEnvironment.WorkBatch.Add(this, SerializeRecord(act));
                    else
                        _service.ExecuteRetried(ExecuteInsertActivityStatusInstance, SerializeRecord(act));
                }
                else if (record is WorkflowTrackingRecord)
                {
                    //
                    // Instance events cannot be batched - many occur when there isn't a batch
                    WorkflowTrackingRecord inst = (WorkflowTrackingRecord)record;
                    if (_isTrans)
                    {
                        WorkflowEnvironment.WorkBatch.Add(this, SerializeRecord(inst));
                    }
                    else
                    {
                        if (TrackingWorkflowEvent.Changed == inst.TrackingWorkflowEvent)
                        {
                            //
                            // Dynamic updates are inserted in the WorkflowInstanceEvent table
                            // and then the arg (workflowchanges) is normalized into xoml 
                            // and the added/removed activities tables
                            _service.ExecuteRetried(ExecuteInsertWorkflowChange, SerializeRecord(inst));
                        }
                        else
                        {
                            _service.ExecuteRetried(ExecuteInsertWorkflowInstanceEvent, SerializeRecord(inst));
                        }
                    }
                }
                else if (record is UserTrackingRecord)
                {
                    UserTrackingRecord user = (UserTrackingRecord)record;
                    if (_isTrans)
                        WorkflowEnvironment.WorkBatch.Add(this, SerializeRecord(user));
                    else
                        _service.ExecuteRetried(ExecuteInsertUserEvent, SerializeRecord(user));
                }
            }

            #endregion

            #region IPendingWork Members

            public bool MustCommit(ICollection items)
            {
                //
                // Never force a persist - this is a balancing act but the V1
                // decision is to err on the side of persisting only when the workflow
                // requires it based on its model.  If the workflow uses persistence points
                // wisely this is great.  If it goes a long time between persists with lots
                // of events the persists will take a long time as the batch can be huge.
                return false;
            }

            public void Commit(System.Transactions.Transaction transaction, ICollection items)
            {
                if ((null == items) || (0 == items.Count))
                    return;

                DbCommand command = null;
                DbConnection connection = null;
                bool needToCloseConnection = false;
                DbTransaction localTransaction = null;
                bool commitTx = false;

                try
                {
                    //
                    // Get the connection and transaction
                    // The connection might be shared or local
                    // The tx is shared and may be either a DTC or a local sql tx
                    connection = DbResourceAllocator.GetEnlistedConnection(
                        this.WorkflowCommitWorkBatchService, transaction, out needToCloseConnection);
                    localTransaction = DbResourceAllocator.GetLocalTransaction(
                        this.WorkflowCommitWorkBatchService, transaction);

                    if (null == localTransaction)
                    {
                        localTransaction = connection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
                        commitTx = true;
                    }

                    command = DbResourceAllocator.NewCommand(connection);
                    command.Transaction = localTransaction;
                    //
                    // If we don't have the internal id for the instance this is the first batch
                    // for this channel instance.  If this is a new instance the following will insert
                    // a new instance record in the db and set _tmpInternalId.  If this is a reload of
                    // an existing instance it will just do a lookup and set _tmpInternalId
                    // In Completed we will assign _tmpInternalId to _internalId if the batch is successful.
                    long internalId = -1;
                    if (_internalId <= 0)
                    {
                        ExecuteInsertWorkflowInstance(command);
                        internalId = _tmpInternalId;
                    }
                    else
                        internalId = _internalId;

                    IList<ActivityTrackingRecord> activities = new List<ActivityTrackingRecord>(5);
                    WorkflowTrackingRecord workflow = null;
                    //
                    // Build the batch statement
                    foreach (object o in items)
                    {
                        if (!(o is TrackingRecord))
                            continue;

                        if (o is ActivityTrackingRecord)
                        {
                            //
                            // If we have a cached workflow tracking record send it
                            if (null != workflow)
                            {
                                ExecuteInsertWorkflowInstanceEvent(internalId, workflow, null, command);
                                workflow = null;
                            }

                            ActivityTrackingRecord activity = (ActivityTrackingRecord)o;
                            //
                            // Add this event to the list and send to the db if we've hit our limit
                            activities.Add(activity);

                            if (_activityEventBatchSize == activities.Count)
                            {
                                ExecuteInsertActivityStatusInstance(internalId, activities, command);
                                activities = new List<ActivityTrackingRecord>(5);
                            }
                        }
                        else if (o is UserTrackingRecord)
                        {
                            //
                            // If we have cached activity or workflow tracking records send them
                            if (activities.Count > 0)
                            {
                                ExecuteInsertActivityStatusInstance(internalId, activities, command);
                                activities.Clear();
                            }

                            if (null != workflow)
                            {
                                ExecuteInsertWorkflowInstanceEvent(internalId, workflow, null, command);
                                workflow = null;
                            }

                            ExecuteInsertUserEvent(internalId, (UserTrackingRecord)o, command);
                        }
                        else if (o is WorkflowTrackingRecord)
                        {
                            //
                            // If we have cached activity tracking records send them
                            if (activities.Count > 0)
                            {
                                ExecuteInsertActivityStatusInstance(internalId, activities, command);
                                activities.Clear();
                            }

                            WorkflowTrackingRecord record = (WorkflowTrackingRecord)o;

                            if (TrackingWorkflowEvent.Changed == record.TrackingWorkflowEvent)
                            {
                                //
                                // If we're already holding a workflow tracking record send both to the db
                                // else cache it and wait for the next workflow tracking record
                                if (null != workflow)
                                {
                                    ExecuteInsertWorkflowInstanceEvent(internalId, workflow, null, command);
                                    workflow = null;
                                }
                                ExecuteInsertWorkflowChange(internalId, record, command);
                            }
                            else
                            {
                                //
                                // If we're already holding a workflow tracking record send both to the db
                                // else cache it and wait for the next workflow tracking record
                                if (null != workflow)
                                {
                                    ExecuteInsertWorkflowInstanceEvent(internalId, workflow, record, command);
                                    workflow = null;
                                }
                                else
                                {
                                    workflow = record;
                                }
                            }
                        }
                    }

                    //
                    // If we ended up with any activities event send them.
                    if (activities.Count > 0)
                        ExecuteInsertActivityStatusInstance(internalId, activities, command);

                    if (null != workflow)
                    {
                        ExecuteInsertWorkflowInstanceEvent(internalId, workflow, null, command);
                        workflow = null;
                    }

                    if (_completedTerminated)
                        ExecuteSetEndDate(internalId, command);

                    if (commitTx)
                        localTransaction.Commit();
                }
                catch (DbException e)
                {
                    if (commitTx)
                        localTransaction.Rollback();

                    WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "Error writing tracking data to database: " + e);
                    throw;
                }
                finally
                {
                    if (needToCloseConnection)
                    {
                        connection.Dispose();
                    }
                }

                return;
            }

            public void Complete(bool succeeded, ICollection items)
            {
                //
                // If we didn't succeed on commit reset all flags
                if (!succeeded)
                {
                    _completedTerminated = false;
                    _pendingArchive = false;
                    _tmpInternalId = -1;
                    _tmpActivityInstanceId.Clear();
                    return;
                }
                //
                // Commit succeeded - move the tmp internalId to the real internalId member
                if (-1 == _internalId && _tmpInternalId > 0)
                    _internalId = _tmpInternalId;

                //
                // Move the tmp activity instance ids to the real activity instance id member
                if (null != _tmpActivityInstanceId && _tmpActivityInstanceId.Count > 0)
                {
                    foreach (string key in _tmpActivityInstanceId.Keys)
                    {
                        if (!_activityInstanceId.ContainsKey(key))
                            _activityInstanceId.Add(key, _tmpActivityInstanceId[key]);
                    }
                    _tmpActivityInstanceId.Clear();
                }

                if (_pendingArchive)
                {
                    try
                    {
                        _service.ExecuteRetried(PartitionInstance, null);
                    }
                    catch (Exception e)
                    {
                        //
                        // ---- exceptions here, do not fail the instance.
                        // Partition logic can be re-run to clean up on failure
                        WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, string.Format(System.Globalization.CultureInfo.InvariantCulture, "Error partitioning instance {0}: {1}", _parameters.InstanceId, e.ToString()));
                    }
                }
            }

            #endregion

            #region Sql Commands - InsertWorkflowInstance

            private void ExecuteInsertWorkflowInstance(object param)
            {

                DbConnection conn = DbResourceAllocator.OpenNewConnection();
                DbCommand command = DbResourceAllocator.NewCommand(conn);
                DbTransaction tx = null;

                try
                {
                    tx = conn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
                    command.Connection = conn;
                    command.Transaction = tx;

                    _internalId = ExecuteInsertWorkflowInstance(command);

                    tx.Commit();
                }
                catch (Exception)
                {
                    try
                    {
                        if (null != tx)
                            tx.Rollback();
                    }
                    catch (Exception)
                    {
                        //
                        // Rollback can throw - ignore these exceptions
                        // so we don't lose the original exception
                    }
                    //
                    // Re-throw original exception
                    throw;
                }
                finally
                {
                    if ((null != conn) && (ConnectionState.Closed != conn.State))
                        conn.Close();
                }

                return;
            }

            private long ExecuteInsertWorkflowInstance(DbCommand command)
            {
                if (null == command)
                    throw new ArgumentNullException("command");

                if ((null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentException(ExecutionStringManager.InvalidCommandBadConnection, "command");
                //
                // Write the type and the workflow definition
                string xaml = _parameters.RootActivity.GetValue(Activity.WorkflowXamlMarkupProperty) as string;
                if (null != xaml && xaml.Length > 0)
                    InsertWorkflow(command, _parameters.InstanceId, null, _parameters.RootActivity);
                else
                    InsertWorkflow(command, _parameters.InstanceId, _parameters.WorkflowType, _parameters.RootActivity);
                //
                // Write the instance record
                BuildInsertWorkflowInstanceParameters(command);

                DbDataReader reader = null;
                try
                {
                    reader = command.ExecuteReader();

                    if (reader.Read())
                        _tmpInternalId = reader.GetInt64(0);

                    return _tmpInternalId;
                }
                finally
                {
                    if (null != reader)
                        reader.Close();
                }
            }

            private void BuildInsertWorkflowInstanceParameters(DbCommand command)
            {
                Debug.Assert((command != null), "Null command");
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertWorkflowInstance]";

                command.Parameters.Clear();

                bool xamlInst = false;
                string xaml = _parameters.RootActivity.GetValue(Activity.WorkflowXamlMarkupProperty) as string;
                if (null != xaml && xaml.Length > 0)
                    xamlInst = true;

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceId", _parameters.InstanceId));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@TypeFullName", (xamlInst ? _parameters.InstanceId.ToString() : _parameters.WorkflowType.FullName)));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@AssemblyFullName", (xamlInst ? _parameters.InstanceId.ToString() : _parameters.WorkflowType.Assembly.FullName)));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ContextGuid", _parameters.ContextGuid));
                if (Guid.Empty != _parameters.CallerInstanceId)
                {
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@CallerInstanceId", _parameters.CallerInstanceId));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@CallPath", _callPathKey));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@CallerContextGuid", _parameters.CallerContextGuid));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@CallerParentContextGuid", _parameters.CallerParentContextGuid));
                }
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventDateTime", this.GetSqlDateTimeString(DateTime.UtcNow)));
            }

            private void InsertWorkflow(DbCommand command, Guid workflowInstanceId, Type workflowType, Activity rootActivity)
            {
                string xoml = null;

                //
                // If we've already seen this type just return
                if (null != workflowType)
                {
                    lock (_service._typeCacheLock)
                    {
                        if (_service._types.Contains(workflowType.AssemblyQualifiedName))
                            return;
                        else
                            xoml = GetXomlDocument(rootActivity);
                    }
                }
                else
                {
                    // Don't forget to deal with XOML-only workflows
                    lock (_service._typeCacheLock)
                    {
                        xoml = GetXomlDocument(rootActivity);
                    }
                }
                //
                // It is possible to ---- here but the pk specifies ignore duplicate key
                // This is better than taking a lock around all of the logic in this method.
                command.Parameters.Clear();

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertWorkflow]";

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@TypeFullName", (null == workflowType ? workflowInstanceId.ToString() : workflowType.FullName)));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@AssemblyFullName", (null == workflowType ? workflowInstanceId.ToString() : workflowType.Assembly.FullName)));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@IsInstanceType", (null == workflowType ? true : false)));


                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowDefinition", xoml));

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowId", DbType.Int32, System.Data.ParameterDirection.Output));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Exists", DbType.Boolean, System.Data.ParameterDirection.Output));

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Activities", GetActivitiesXml((CompositeActivity)rootActivity)));

                command.ExecuteNonQuery();
                //
                // Add this to the list of types we've already seen so we don't go
                // through the serialization overhead again and hit the db only to learn we've already stored it
                // Use a lock here to avoid ---- on _types dictionary
                if (null != workflowType)
                {
                    lock (_service._typeCacheLock)
                    {
                        if (!_service._types.Contains(workflowType.AssemblyQualifiedName))
                        {
                            _service._types.Add(workflowType);
                        }
                    }
                }

                return;
            }

            #endregion

            #region Sql Commands - InsertWorkflowInstanceEvent

            private void ExecuteInsertWorkflowInstanceEvent(object param)
            {
                WorkflowTrackingRecord record = param as WorkflowTrackingRecord;

                if (null == record)
                    throw new ArgumentException(ExecutionStringManager.InvalidWorkflowTrackingRecordParameter, "param");

                DbConnection conn = DbResourceAllocator.OpenNewConnection();
                DbCommand command = DbResourceAllocator.NewCommand(conn);
                DbTransaction tx = null;

                try
                {
                    tx = conn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
                    command.Connection = conn;
                    command.Transaction = tx;

                    ExecuteInsertWorkflowInstanceEvent(_internalId, record, null, command);

                    tx.Commit();
                }
                catch (Exception)
                {
                    try
                    {
                        if (null != tx)
                            tx.Rollback();
                    }
                    catch (Exception)
                    {
                        //
                        // Rollback can throw - ignore these exceptions
                        // so we don't lose the original exception
                    }
                    //
                    // Re-throw original exception
                    throw;
                }
                finally
                {
                    if ((null != conn) && (ConnectionState.Closed != conn.State))
                        conn.Close();
                }

                return;
            }

            private void ExecuteInsertWorkflowInstanceEvent(long internalId, WorkflowTrackingRecord record1, WorkflowTrackingRecord record2, DbCommand command)
            {
                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentException();

                BuildInsertWorkflowInstanceEventParameters(internalId, record1, record2, command);

                command.ExecuteNonQuery();

                long eventId1 = (long)command.Parameters["@WorkflowInstanceEventId1"].Value;
                Debug.Assert(eventId1 > 0, "Invalid eventId1");

                long eventId2 = -1;
                if (null != record2)
                {
                    eventId2 = (long)command.Parameters["@WorkflowInstanceEventId2"].Value;
                    Debug.Assert(eventId2 > 0, "Invalid eventId2");
                }

                List<KeyValuePair<long, string>> annotations = new List<KeyValuePair<long, string>>(record1.Annotations.Count + (null == record2 ? 0 : record2.Annotations.Count));

                foreach (string s in record1.Annotations)
                    annotations.Add(new KeyValuePair<long, string>(eventId1, s));

                if (null != record2)
                {
                    foreach (string s in record2.Annotations)
                        annotations.Add(new KeyValuePair<long, string>(eventId2, s));
                }

                BatchExecuteInsertEventAnnotation(internalId, 'w', annotations, command);
            }

            private void BuildInsertWorkflowInstanceEventParameters(long internalId, WorkflowTrackingRecord record1, WorkflowTrackingRecord record2, DbCommand command)
            {
                if (null == record1)
                    throw new ArgumentNullException("record");

                if (null == command)
                    throw new ArgumentNullException("command");

                Debug.Assert(internalId != -1, "Invalid internalId");

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertWorkflowInstanceEvent]";

                command.Parameters.Clear();
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", internalId));

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@TrackingWorkflowEventId1", (int)record1.TrackingWorkflowEvent));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventDateTime1", record1.EventDateTime));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventOrder1", record1.EventOrder));

                if (null != record1.EventArgs)
                {
                    Type t = record1.EventArgs.GetType();
                    Byte[] data = null;

                    if (!(record1.EventArgs is SerializedEventArgs))
                        record1 = SerializeRecord(record1);

                    SerializedEventArgs sargs = record1.EventArgs as SerializedEventArgs;
                    data = sargs.SerializedArgs;
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventArgTypeFullName1", t.FullName));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventArgAssemblyFullName1", t.Assembly.FullName));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventArg1", data));
                }
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceEventId1", DbType.Int64, ParameterDirection.Output));

                if (null != record2)
                {
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@TrackingWorkflowEventId2", (int)record2.TrackingWorkflowEvent));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventDateTime2", record2.EventDateTime));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventOrder2", record2.EventOrder));

                    if (null != record2.EventArgs)
                    {
                        Type t = record2.EventArgs.GetType();
                        Byte[] data = null;

                        if (!(record2.EventArgs is SerializedEventArgs))
                            record2 = SerializeRecord(record2);

                        SerializedEventArgs sargs = record2.EventArgs as SerializedEventArgs;
                        data = sargs.SerializedArgs;
                        command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventArgTypeFullName2", t.FullName));
                        command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventArgAssemblyFullName2", t.Assembly.FullName));
                        command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventArg2", data));
                    }
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceEventId2", DbType.Int64, ParameterDirection.Output));
                }
            }

            #endregion

            #region Sql Commands - InsertActivityStatusInstance

            private void ExecuteInsertActivityStatusInstance(object param)
            {
                ActivityTrackingRecord record = param as ActivityTrackingRecord;

                if (null == record)
                    throw new ArgumentException(ExecutionStringManager.InvalidActivityTrackingRecordParameter, "param");

                DbConnection conn = DbResourceAllocator.OpenNewConnection();

                DbTransaction tx = null;

                try
                {
                    tx = conn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
                    DbCommand command = conn.CreateCommand();
                    command.Transaction = tx;

                    IList<ActivityTrackingRecord> activity = new List<ActivityTrackingRecord>(1);
                    activity.Add(record);

                    ExecuteInsertActivityStatusInstance(_internalId, activity, command);

                    tx.Commit();
                }
                catch (Exception)
                {
                    //
                    // Rollback can throw - ignore these exceptions
                    // so we don't lose the original exception
                    try
                    {
                        if (null != tx)
                            tx.Rollback();
                    }
                    catch (Exception)
                    {
                    }

                    //
                    // Re-throw original exception
                    throw;
                }
                finally
                {
                    if ((null != conn) && (ConnectionState.Closed != conn.State))
                        conn.Close();

                }

                return;
            }

            private void ExecuteInsertActivityStatusInstance(long internalId, IList<ActivityTrackingRecord> activities, DbCommand command)
            {
                if (null == activities || activities.Count <= 0)
                    return;

                if (activities.Count > _activityEventBatchSize)
                    throw new ArgumentOutOfRangeException("activities");

                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentException();

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertActivityExecutionStatusEventMultiple]";
                //
                // Add the common parameters
                command.Parameters.Clear();
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceId", _parameters.InstanceId));
                //
                // If we have the workflow's internal id use it to avoid the look up in the db
                DbParameter param = DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", DbType.Int64, System.Data.ParameterDirection.InputOutput);
                command.Parameters.Add(param);
                if (internalId > 0)
                    param.Value = internalId;

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceContextGuid", _parameters.ContextGuid));
                //
                // Hashed ids of QName, context and pcontext used as key for storing activity record ids
                // Save these for each record in the list so we don't have to recompute them below when adding to the cache
                string[] ids = new string[] { null, null, null, null, null };

                for (int i = 0; i < activities.Count; i++)
                {
                    ActivityTrackingRecord record = activities[i];

                    long aid = -1;
                    ids[i] = BuildQualifiedNameVarName(record.QualifiedName, record.ContextGuid, record.ParentContextGuid);

                    TryGetActivityInstanceId(ids[i], out aid);

                    BuildInsertActivityStatusEventParameters(internalId, aid, i + 1, record, command);
                }

                command.ExecuteNonQuery();
                //
                // Get all the output ids
                long[] eventIds = new long[] { -1, -1, -1, -1, -1 };
                for (int i = 0; i < activities.Count; i++)
                {
                    string index = (i + 1).ToString(CultureInfo.InvariantCulture);
                    //
                    // ActivityInstanceId
                    long aId = (long)command.Parameters["@ActivityInstanceId" + index].Value;
                    Debug.Assert(aId > 0, "Invalid @ActivityInstanceId output parameter value");
                    //
                    // For all status changes that aren't "Closed" add the id to the instance cache
                    // Set... method checks and only adds if it does already exist.
                    // To keep the cache size under control remove entries for activities that have closed.
                    // The activity might fault and need to do a lookup in the db but this isn't the common
                    // path and the db lookup isn't very expensive.
                    if (ActivityExecutionStatus.Closed != activities[i].ExecutionStatus)
                        SetActivityInstanceId(ids[i], aId);
                    else
                        RemoveActivityInstanceId(ids[i]);
                    //
                    // ActivityExecutionStatusEventId
                    long aeseId = (long)command.Parameters["@ActivityExecutionStatusEventId" + index].Value;
                    Debug.Assert(aeseId > 0, "Invalid @ActivityExecutionStatusEventId output parameter value");
                    eventIds[i] = aeseId;
                }

                List<KeyValuePair<long, string>> annotations = new List<KeyValuePair<long, string>>(10);
                List<KeyValuePair<long, TrackingDataItem>> items = new List<KeyValuePair<long, TrackingDataItem>>(10);
                for (int i = 0; i < activities.Count; i++)
                {
                    ActivityTrackingRecord record = activities[i];
                    //
                    // Get the ActivityExecutionStatusEventId
                    long eventId = eventIds[i];
                    if (eventId <= 0)
                        throw new InvalidOperationException();

                    foreach (string s in record.Annotations)
                        annotations.Add(new KeyValuePair<long, string>(eventId, s));

                    foreach (TrackingDataItem item in record.Body)
                        items.Add(new KeyValuePair<long, TrackingDataItem>(eventId, item));
                }

                BatchExecuteInsertEventAnnotation(internalId, 'a', annotations, command);

                BatchExecuteInsertTrackingDataItems(internalId, 'a', items, command);
            }

            private void BuildInsertActivityStatusEventParameters(long internalId, long activityInstanceId, int parameterId, ActivityTrackingRecord record, DbCommand command)
            {
                string paramIdString = parameterId.ToString(CultureInfo.InvariantCulture);
                //
                // If we have the activity's instance id use it to avoid the look up in the db
                DbParameter param = DbResourceAllocator.NewDbParameter("@ActivityInstanceId" + paramIdString, DbType.Int64, System.Data.ParameterDirection.InputOutput);
                command.Parameters.Add(param);

                if (activityInstanceId > 0)
                    param.Value = activityInstanceId;

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@QualifiedName" + paramIdString, record.QualifiedName));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ContextGuid" + paramIdString, record.ContextGuid));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ParentContextGuid" + paramIdString, record.ParentContextGuid));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ExecutionStatusId" + paramIdString, (int)record.ExecutionStatus));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventDateTime" + paramIdString, record.EventDateTime));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventOrder" + paramIdString, record.EventOrder));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ActivityExecutionStatusEventId" + paramIdString, DbType.Int64, ParameterDirection.Output));

            }

            #endregion

            #region Sql Commands - InsertUserEvent

            private void ExecuteInsertUserEvent(object param)
            {
                UserTrackingRecord record = param as UserTrackingRecord;

                if (null == record)
                    throw new ArgumentException(ExecutionStringManager.InvalidUserTrackingRecordParameter, "param");

                DbConnection conn = DbResourceAllocator.OpenNewConnection();

                DbTransaction tx = null;

                try
                {
                    tx = conn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
                    DbCommand command = conn.CreateCommand();
                    command.Transaction = tx;

                    ExecuteInsertUserEvent(_internalId, record, command);

                    tx.Commit();
                }
                catch (Exception)
                {
                    //
                    // Rollback can throw - ignore these exceptions
                    // so we don't lose the original exception
                    try
                    {
                        if (null != tx)
                            tx.Rollback();
                    }
                    catch (Exception)
                    {
                    }

                    //
                    // Re-throw original exception
                    throw;
                }
                finally
                {
                    if ((null != conn) && (ConnectionState.Closed != conn.State))
                        conn.Close();

                }

                return;
            }

            private void ExecuteInsertUserEvent(long internalId, UserTrackingRecord record, DbCommand command)
            {
                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentException();

                long aid = -1;
                bool cached = false;
                //
                // Check if we have the activityInstanceId in the cache - we cache to avoid repeatedly searching this table.
                string id = BuildQualifiedNameVarName(record.QualifiedName, record.ContextGuid, record.ParentContextGuid);
                if (TryGetActivityInstanceId(id, out aid))
                    cached = true;

                BuildInsertUserEventParameters(internalId, aid, record, command);
                command.ExecuteNonQuery();
                //
                // If we didn't already have the activityInstanceId get it from the IN/OUT param and put it in the cache
                if (!cached)
                    SetActivityInstanceId(id, (long)command.Parameters["@ActivityInstanceId"].Value);

                long eventId = (long)command.Parameters["@UserEventId"].Value;

                List<KeyValuePair<long, string>> annotations = new List<KeyValuePair<long, string>>(10);
                List<KeyValuePair<long, TrackingDataItem>> items = new List<KeyValuePair<long, TrackingDataItem>>(10);

                foreach (string s in record.Annotations)
                    annotations.Add(new KeyValuePair<long, string>(eventId, s));

                foreach (TrackingDataItem item in record.Body)
                    items.Add(new KeyValuePair<long, TrackingDataItem>(eventId, item));

                BatchExecuteInsertEventAnnotation(internalId, 'u', annotations, command);

                BatchExecuteInsertTrackingDataItems(internalId, 'u', items, command);
            }

            private void BuildInsertUserEventParameters(long internalId, long activityInstanceId, UserTrackingRecord record, DbCommand command)
            {
                Debug.Assert(internalId != -1, "Invalid internalId");
                Debug.Assert((command != null), "Null command passed to BuildInsertActivityStatusEventParameters");

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertUserEvent]";

                command.Parameters.Clear();

                DbParameter param = DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", DbType.Int64);
                command.Parameters.Add(param);
                param.Value = internalId;

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventOrder", record.EventOrder));
                //
                // If we have the activity's instance id use it to avoid the look up in the db
                param = DbResourceAllocator.NewDbParameter("@ActivityInstanceId", DbType.Int64, System.Data.ParameterDirection.InputOutput);
                command.Parameters.Add(param);

                if (activityInstanceId > 0)
                {
                    param.Value = activityInstanceId;
                }
                else
                {
                    //
                    // Keep the network traffic down - only include the fields needed 
                    // to insert an ActivityInstance record if we don't have the activityInstanceId
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@QualifiedName", record.QualifiedName));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ContextGuid", record.ContextGuid));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ParentContextGuid", record.ParentContextGuid));
                }

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventDateTime", record.EventDateTime));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@UserDataKey", record.UserDataKey));

                if (null != record.UserData)
                {
                    Type t = record.UserData.GetType();
                    Byte[] data = null;
                    bool nonSerializable = false;
                    string userDataString = null;

                    if (!(record.UserData is SerializedDataItem))
                        SerializeDataItem(record.UserData, out data, out nonSerializable);

                    SerializedDataItem sItem = record.UserData as SerializedDataItem;
                    data = sItem.SerializedData;
                    nonSerializable = sItem.NonSerializable;
                    userDataString = sItem.StringData;

                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@UserDataTypeFullName", t.FullName));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@UserDataAssemblyFullName", t.Assembly.FullName));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@UserData_Str", userDataString));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@UserData_Blob", data));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@UserDataNonSerializable", nonSerializable));
                }
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@UserEventId", DbType.Int64, ParameterDirection.Output));
            }

            #endregion

            #region Sql Commands - InsertTrackingDataItem

            private void BatchExecuteInsertTrackingDataItems(long internalId, char eventTypeId, IList<KeyValuePair<long, TrackingDataItem>> items, DbCommand command)
            {
                if (null == items || items.Count <= 0)
                    return;
                //
                // If the list is smaller than the batch size just push the whole thing
                if (items.Count <= _dataItemBatchSize)
                {
                    ExecuteInsertTrackingDataItems(internalId, eventTypeId, items, command);
                    return;
                }
                //
                // Need to split the list into max batch size chunks
                List<KeyValuePair<long, TrackingDataItem>> batch = new List<KeyValuePair<long, TrackingDataItem>>(_dataItemBatchSize);
                foreach (KeyValuePair<long, TrackingDataItem> kvp in items)
                {
                    batch.Add(kvp);
                    if (batch.Count == _dataItemBatchSize)
                    {
                        ExecuteInsertTrackingDataItems(internalId, eventTypeId, batch, command);
                        batch.Clear();
                    }
                }
                //
                // Send anything that hasn't been sent
                if (batch.Count > 0)
                    ExecuteInsertTrackingDataItems(internalId, eventTypeId, batch, command);
            }

            private void ExecuteInsertTrackingDataItems(long internalId, char eventTypeId, IList<KeyValuePair<long, TrackingDataItem>> items, DbCommand command)
            {
                Debug.Assert(internalId != -1, "Invalid internalId");
                if (null == items || items.Count <= 0)
                    return;

                if (items.Count > _dataItemAnnotationBatchSize)
                    throw new ArgumentOutOfRangeException("items");

                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentException();

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertTrackingDataItemMultiple]";

                command.Parameters.Clear();
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", internalId));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventTypeId", eventTypeId));

                int i = 1; // base 1 to match parameter names
                foreach (KeyValuePair<long, TrackingDataItem> kvp in items)
                {
                    string index = (i++).ToString(CultureInfo.InvariantCulture);

                    SerializedDataItem sItem = kvp.Value as SerializedDataItem;
                    if (null == sItem)
                        sItem = SerializeDataItem(kvp.Value);

                    Type t = sItem.Type;

                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventId" + index, kvp.Key));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@FieldName" + index, sItem.FieldName));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@TypeFullName" + index, ((null == t) ? null : t.FullName)));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@AssemblyFullName" + index, ((null == t) ? null : t.Assembly.FullName)));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Data_Str" + index, sItem.StringData));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Data_Blob" + index, sItem.SerializedData));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@DataNonSerializable" + index, sItem.NonSerializable));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@TrackingDataItemId" + index, DbType.Int64, System.Data.ParameterDirection.Output));
                }

                command.ExecuteNonQuery();
                //
                // Get all the out parameters holding the data item record ids
                // This keeps us from repeatedly going into the parameters collection
                // below if a data item has more than one annotation
                List<long> ids = new List<long>(_dataItemAnnotationBatchSize);
                for (i = 0; i < items.Count; i++)
                {
                    string index = (i + 1).ToString(CultureInfo.InvariantCulture);
                    ids.Insert(i, (long)command.Parameters["@TrackingDataItemId" + index].Value);
                }

                //
                // Go through all the data items and send all the annotations in batches
                List<KeyValuePair<long, string>> annotations = new List<KeyValuePair<long, string>>(_dataItemAnnotationBatchSize);
                i = 0;

                foreach (KeyValuePair<long, TrackingDataItem> kvp in items)
                {
                    TrackingDataItem item = kvp.Value;
                    long dataItemId = ids[i++];

                    foreach (string s in item.Annotations)
                    {
                        annotations.Add(new KeyValuePair<long, string>(dataItemId, s));
                        if (annotations.Count == _dataItemAnnotationBatchSize)
                        {
                            ExecuteInsertAnnotation(internalId, annotations, command);
                            annotations.Clear();
                        }
                    }
                }
                //
                // If we have anything left send them.
                if (annotations.Count > 0)
                    ExecuteInsertAnnotation(internalId, annotations, command);
            }

            private void ExecuteInsertAnnotation(long internalId, IList<KeyValuePair<long, string>> annotations, DbCommand command)
            {
                if (null == annotations || annotations.Count <= 0)
                    return;

                if (annotations.Count > _dataItemAnnotationBatchSize)
                    throw new ArgumentOutOfRangeException("annotations");

                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentNullException("command");

                command.Parameters.Clear();
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertTrackingDataItemAnnotationMultiple]";

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", internalId));

                int i = 1; // base 1 to match parameter names
                foreach (KeyValuePair<long, string> kvp in annotations)
                {
                    string index = (i++).ToString(CultureInfo.InvariantCulture);
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@HasData" + index, true));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@TrackingDataItemId" + index, kvp.Key));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Annotation" + index, kvp.Value));
                }

                command.ExecuteNonQuery();

                return;
            }

            private void BatchExecuteInsertEventAnnotation(long internalId, char eventTypeId, IList<KeyValuePair<long, string>> annotations, DbCommand command)
            {
                if (null == annotations || annotations.Count <= 0)
                    return;

                //
                // If the list is smaller than the max batch size just send it directly
                if (annotations.Count <= _eventAnnotationBatchSize)
                {
                    ExecuteInsertEventAnnotation(internalId, eventTypeId, annotations, command);
                    return;
                }
                //
                // Need to split the list into max batch size chunks
                List<KeyValuePair<long, string>> batch = new List<KeyValuePair<long, string>>(_eventAnnotationBatchSize);
                foreach (KeyValuePair<long, string> kvp in annotations)
                {
                    batch.Add(kvp);
                    if (batch.Count == _eventAnnotationBatchSize)
                    {
                        ExecuteInsertEventAnnotation(internalId, eventTypeId, batch, command);
                        batch.Clear();
                    }
                }
                //
                // Send anything that hasn't been sent
                if (batch.Count > 0)
                    ExecuteInsertEventAnnotation(internalId, eventTypeId, batch, command);
            }

            private void ExecuteInsertEventAnnotation(long internalId, char eventTypeId, IList<KeyValuePair<long, string>> annotations, DbCommand command)
            {
                Debug.Assert(internalId != -1, "Invalid internalId");

                if (null == annotations || annotations.Count <= 0)
                    return;

                if (annotations.Count > _eventAnnotationBatchSize)
                    throw new ArgumentOutOfRangeException("annotations");

                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentNullException("command");

                command.Parameters.Clear();
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertEventAnnotationMultiple]";

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", internalId));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventTypeId", eventTypeId));

                int i = 1; //base 1 to match parameter names
                foreach (KeyValuePair<long, string> kvp in annotations)
                {
                    string index = (i++).ToString(CultureInfo.InvariantCulture);
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@HasData" + index, true));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@EventId" + index, kvp.Key));
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Annotation" + index, kvp.Value));
                }

                command.ExecuteNonQuery();

                return;
            }


            #endregion

            #region Workflow Change

            private void ExecuteInsertWorkflowChange(object param)
            {
                WorkflowTrackingRecord record = param as WorkflowTrackingRecord;

                if (null == record)
                    throw new ArgumentException(ExecutionStringManager.InvalidWorkflowTrackingRecordParameter, "param");

                DbCommand command = DbResourceAllocator.NewCommand();

                try
                {
                    if (ConnectionState.Open != command.Connection.State)
                        command.Connection.Open();
                    command.Transaction = command.Connection.BeginTransaction();

                    ExecuteInsertWorkflowChange(_internalId, record, command);

                    command.Transaction.Commit();
                }
                catch (Exception)
                {
                    //
                    // Rollback can throw - ignore these exceptions
                    // so we don't lose the original exception
                    try
                    {
                        if ((null != command) && (null != command.Transaction))
                            command.Transaction.Rollback();
                    }
                    catch (Exception)
                    {
                    }

                    //
                    // Re-throw original exception
                    throw;
                }
                finally
                {
                    if ((null != command) && (null != command.Connection) && (ConnectionState.Closed != command.Connection.State))
                        command.Connection.Close();
                }

                return;
            }

            private void ExecuteInsertWorkflowChange(long internalId, WorkflowTrackingRecord record, DbCommand command)
            {
                if (null == record)
                    throw new ArgumentNullException("record");

                if (null == record.EventArgs)
                    throw new InvalidOperationException(ExecutionStringManager.InvalidWorkflowChangeArgs);

                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentNullException("command");
                //
                // If we haven't already serialized do so now.
                // This is work we have to do to write to store in the db anyway.
                if (!(record.EventArgs is SerializedWorkflowChangedEventArgs))
                    record = SerializeRecord(record);
                //
                // Insert the workflow instance event
                BuildInsertWorkflowInstanceEventParameters(internalId, record, null, command);

                command.ExecuteNonQuery();
                //
                // Get the event id for added/removed activities and annotations
                long eventId = (long)command.Parameters["@WorkflowInstanceEventId1"].Value;

                SerializedWorkflowChangedEventArgs sargs = (SerializedWorkflowChangedEventArgs)record.EventArgs;
                //
                // Normalize the activities that have been added/removed if we're tracking definitions
                if ((null != sargs.AddedActivities) && (sargs.AddedActivities.Count > 0))
                {
                    foreach (AddedActivity added in sargs.AddedActivities)
                        ExecuteInsertAddedActivity(internalId, added.QualifiedName, added.ParentQualifiedName, added.ActivityTypeFullName, added.ActivityTypeAssemblyFullName, added.AddedActivityActionXoml, eventId, added.Order, command);
                }

                if ((null != sargs.RemovedActivities) && (sargs.RemovedActivities.Count > 0))
                {
                    foreach (RemovedActivity removed in sargs.RemovedActivities)
                        ExecuteInsertRemovedActivity(internalId, removed.QualifiedName, removed.ParentQualifiedName, removed.RemovedActivityActionXoml, eventId, removed.Order, command);
                }

                List<KeyValuePair<long, string>> annotations = new List<KeyValuePair<long, string>>(record.Annotations.Count);
                foreach (string s in record.Annotations)
                    annotations.Add(new KeyValuePair<long, string>(eventId, s));
                BatchExecuteInsertEventAnnotation(internalId, 'w', annotations, command);
            }

            private void ExecuteInsertAddedActivity(long internalId, string qualifiedName, string parentQualifiedName, string typeFullName, string assemblyFullName, string addedActivityActionXoml, long eventId, int order, DbCommand command)
            {
                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentNullException("command");

                command.Parameters.Clear();

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertAddedActivity]";

                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", internalId));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceEventId", eventId));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@QualifiedName", qualifiedName));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@TypeFullName", typeFullName));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@AssemblyFullName", assemblyFullName));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ParentQualifiedName", parentQualifiedName));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@AddedActivityAction", addedActivityActionXoml));
                if (-1 == order)
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Order", DBNull.Value));
                else
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Order", order));

                command.ExecuteNonQuery();
            }

            private void ExecuteInsertRemovedActivity(long internalId, string qualifiedName, string parentQualifiedName, string removedActivityActionXoml, long eventId, int order, DbCommand command)
            {
                if ((null == command) || (null == command.Connection) || (ConnectionState.Open != command.Connection.State))
                    throw new ArgumentNullException("command");

                command.Parameters.Clear();

                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "[dbo].[InsertRemovedActivity]";
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceInternalId", internalId));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@WorkflowInstanceEventId", eventId));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@QualifiedName", qualifiedName));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@ParentQualifiedName", parentQualifiedName));
                command.Parameters.Add(DbResourceAllocator.NewDbParameter("@RemovedActivityAction", removedActivityActionXoml));
                if (-1 == order)
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Order", DBNull.Value));
                else
                    command.Parameters.Add(DbResourceAllocator.NewDbParameter("@Order", order));

                command.ExecuteNonQuery();
            }

            #endregion

            #region Utility

            private bool TryGetActivityInstanceId(string key, out long id)
            {
                //
                // Check the cache of committed ids
                if (_activityInstanceId.TryGetValue(key, out id))
                    return true;
                //
                // If we're batched check the cache of temp ids generated during this batch commit
                if (_isTrans)
                    return _tmpActivityInstanceId.TryGetValue(key, out id);
                else
                    return false; // not batched so we didn't find the id
            }

            private void SetActivityInstanceId(string key, long id)
            {
                //
                // If we're batched put the ids in the temp member
                // If the commit is successful we'll move these to the real member
                // in IPendingWork.Complete
                if (_isTrans)
                {
                    if (!_tmpActivityInstanceId.ContainsKey(key))
                        _tmpActivityInstanceId.Add(key, id);
                }
                else
                {
                    if (!_activityInstanceId.ContainsKey(key))
                        _activityInstanceId.Add(key, id);
                }
            }

            private void RemoveActivityInstanceId(string key)
            {
                //
                // Remove from both the temp and real caches
                if (_isTrans)
                {
                    if (_tmpActivityInstanceId.ContainsKey(key))
                        _tmpActivityInstanceId.Remove(key);
                }

                if (_activityInstanceId.ContainsKey(key))
                    _activityInstanceId.Remove(key);
            }

            private string GetSqlDateTimeString(DateTime dateTime)
            {
                return dateTime.Year.ToString(System.Globalization.CultureInfo.InvariantCulture) + PadToDblDigit(dateTime.Month) + PadToDblDigit(dateTime.Day) + " " + dateTime.Hour.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + dateTime.Minute.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + dateTime.Second.ToString(System.Globalization.CultureInfo.InvariantCulture) + ":" + dateTime.Millisecond.ToString(System.Globalization.CultureInfo.InvariantCulture);
            }


            private string PadToDblDigit(int num)
            {
                string s = num.ToString(System.Globalization.CultureInfo.InvariantCulture);
                if (s.Length == 1)
                    return "0" + s;
                else
                    return s;
            }

            /// <summary>
            /// Build a string to uniquely identify each activity that should be recorded as a seperate instance.
            /// A separate instance is defined by the combination of QualifiedName, Context and ParentContext
            /// </summary>
            /// <param name="record"></param>
            /// <returns></returns>
            private string BuildQualifiedNameVarName(string qId, Guid context, Guid parentContext)
            {
                Guid hashed = HashHelper.HashServiceType(qId);
                return hashed.ToString().Replace('-', '_') + "_" + context.ToString().Replace('-', '_') + "_" + parentContext.ToString().Replace('-', '_');
            }

            private ActivityTrackingRecord SerializeRecord(ActivityTrackingRecord record)
            {
                if ((null == record.Body) || (0 == record.Body.Count))
                    return record;

                for (int i = 0; i < record.Body.Count; i++)
                    record.Body[i] = SerializeDataItem(record.Body[i]);

                return record;
            }

            private UserTrackingRecord SerializeRecord(UserTrackingRecord record)
            {
                if (((null == record.Body) || (0 == record.Body.Count)) && (null == record.EventArgs) && (null == record.UserData))
                    return record;

                if (null != record.UserData)
                {
                    SerializedDataItem item = new SerializedDataItem();

                    byte[] data = null;
                    bool nonSerializable;
                    SerializeDataItem(record.UserData, out data, out nonSerializable);

                    item.Type = record.UserData.GetType();
                    item.StringData = record.UserData.ToString();
                    item.SerializedData = data;
                    item.NonSerializable = nonSerializable;

                    record.UserData = item;
                }

                for (int i = 0; i < record.Body.Count; i++)
                    record.Body[i] = SerializeDataItem(record.Body[i]);

                return record;
            }

            private WorkflowTrackingRecord SerializeRecord(WorkflowTrackingRecord record)
            {
                if (null == record.EventArgs)
                    return record;

                SerializedEventArgs args;
                if (TrackingWorkflowEvent.Changed == record.TrackingWorkflowEvent)
                {
                    //
                    // Convert the WorkflowChanged items
                    SerializedWorkflowChangedEventArgs sargs = new SerializedWorkflowChangedEventArgs();
                    TrackingWorkflowChangedEventArgs wargs = (TrackingWorkflowChangedEventArgs)record.EventArgs;
                    if (null != wargs)
                    {
                        for (int i = 0; i < wargs.Changes.Count; i++)
                        {
                            WorkflowChangeAction action = wargs.Changes[i];
                            if (action is RemovedActivityAction)
                                AddRemovedActivity((RemovedActivityAction)action, i, sargs.RemovedActivities);
                            else if (action is AddedActivityAction)
                                AddAddedActivity((AddedActivityAction)action, i, sargs.AddedActivities);
                        }
                    }
                    args = sargs;
                }
                else
                {
                    args = new SerializedEventArgs();
                    byte[] data = null;
                    bool nonSerializable;

                    SerializeDataItem(record.EventArgs, out data, out nonSerializable);
                    args.SerializedArgs = data;
                    //
                    // nonSerializable will only be null for SerializationExceptions, all others bubble
                    if (nonSerializable)
                    {
                        //
                        // Something didn't serialize.
                        // If this is an exception or terminated event it is most likely the Exception member
                        // Save the exception message - better than losing all record of the exception
                        Exception e;
                        switch (record.TrackingWorkflowEvent)
                        {
                            case TrackingWorkflowEvent.Terminated:
                                e = ((TrackingWorkflowTerminatedEventArgs)record.EventArgs).Exception;
                                if (null != e)
                                {
                                    SerializeDataItem(e.ToString(), out data, out nonSerializable);
                                    args.SerializedArgs = data;
                                }
                                break;
                            case TrackingWorkflowEvent.Exception:
                                e = ((TrackingWorkflowExceptionEventArgs)record.EventArgs).Exception;
                                if (null != e)
                                {
                                    SerializeDataItem(e.ToString(), out data, out nonSerializable);
                                    args.SerializedArgs = data;
                                }
                                break;
                        }
                    }
                }
                //
                // Set the type of the EventArgs and then 
                // put the serialized item in the args member, 
                // we don't need the original Args object any longer
                args.Type = record.EventArgs.GetType();
                record.EventArgs = args;

                return record;
            }

            private void AddRemovedActivity(RemovedActivityAction removedAction, int order, IList<RemovedActivity> activities)
            {
                Activity removed = removedAction.OriginalRemovedActivity;
                RemovedActivity removedActivity = new RemovedActivity();
                removedActivity.Order = order;
                removedActivity.QualifiedName = removed.QualifiedName;
                if (null != removed.Parent)
                    removedActivity.ParentQualifiedName = removed.Parent.QualifiedName;
                //
                // Save the defintion of this change
                removedActivity.RemovedActivityActionXoml = GetXomlDocument(removedAction);
                activities.Add(removedActivity);
                //
                // Recursively add all contained activities to the removed list
                if (removed is CompositeActivity)
                {
                    foreach (Activity activity in ((CompositeActivity)removed).Activities)
                    {
                        AddRemovedActivity(activity, activities);
                    }
                }
            }

            private void AddRemovedActivity(Activity removed, IList<RemovedActivity> activities)
            {
                RemovedActivity removedActivity = new RemovedActivity();
                removedActivity.Order = -1;
                removedActivity.QualifiedName = removed.QualifiedName;
                if (null != removed.Parent)
                    removedActivity.ParentQualifiedName = removed.Parent.QualifiedName;
                activities.Add(removedActivity);
                //
                // Recursively add all contained activities to the removed list
                if (removed is CompositeActivity)
                {
                    foreach (Activity activity in ((CompositeActivity)removed).Activities)
                    {
                        AddRemovedActivity(activity, activities);
                    }
                }
            }

            private void AddAddedActivity(AddedActivityAction addedAction, int order, IList<AddedActivity> activities)
            {
                Activity added = addedAction.AddedActivity;
                AddedActivity addedActivity = new AddedActivity();
                addedActivity.Order = order;
                Type type = added.GetType();

                addedActivity.ActivityTypeFullName = type.FullName;
                addedActivity.ActivityTypeAssemblyFullName = type.Assembly.FullName;
                addedActivity.QualifiedName = added.QualifiedName;
                if (null != added.Parent)
                    addedActivity.ParentQualifiedName = added.Parent.QualifiedName;
                addedActivity.AddedActivityActionXoml = GetXomlDocument(addedAction);

                activities.Add(addedActivity);
                //
                // Recursively add all contained activities to the added list
                if (added is CompositeActivity)
                {
                    foreach (Activity activity in ((CompositeActivity)added).Activities)
                    {
                        AddAddedActivity(activity, activities);
                    }
                }
            }

            private void AddAddedActivity(Activity added, IList<AddedActivity> activities)
            {
                AddedActivity addedActivity = new AddedActivity();
                addedActivity.Order = -1;
                Type type = added.GetType();

                addedActivity.ActivityTypeFullName = type.FullName;
                addedActivity.ActivityTypeAssemblyFullName = type.Assembly.FullName;
                addedActivity.QualifiedName = added.QualifiedName;
                if (null != added.Parent)
                    addedActivity.ParentQualifiedName = added.Parent.QualifiedName;

                activities.Add(addedActivity);
                //
                // Recursively add all contained activities to the added list
                if (added is CompositeActivity)
                {
                    foreach (Activity activity in ((CompositeActivity)added).Activities)
                    {
                        AddAddedActivity(activity, activities);
                    }
                }
            }

            private SerializedDataItem SerializeDataItem(TrackingDataItem item)
            {
                if (null == item)
                    return null;

                SerializedDataItem s = new SerializedDataItem();
                s.Data = item.Data;
                s.Annotations.AddRange(item.Annotations);
                s.FieldName = item.FieldName;

                if (null != item.Data)
                {
                    byte[] state = null;
                    bool nonSerializable;
                    SerializeDataItem(item.Data, out state, out nonSerializable);
                    s.SerializedData = state;
                    s.StringData = item.Data.ToString();
                    s.Type = item.Data.GetType();
                    s.NonSerializable = nonSerializable;
                }

                return s;
            }

            /// <summary>
            /// Binary serialize an object.  Used to persist trackingDataItems.
            /// </summary>
            /// <param name="data"></param>
            /// <param name="state"></param>
            private void SerializeDataItem(object data, out byte[] state, out bool nonSerializable)
            {
                nonSerializable = false;
                state = null;
                if (null == data)
                    return;

                MemoryStream stream = new MemoryStream(1024);
                BinaryFormatter bf = new BinaryFormatter();

                try
                {
                    bf.Serialize(stream, data);

                    state = new byte[stream.Length];
                    stream.Position = 0;

                    if (stream.Length > Int32.MaxValue)
                        return;
                    else
                    {
                        int read = 0, totalRead = 0, cbToRead = 0;
                        do
                        {
                            totalRead += read;
                            cbToRead = (int)stream.Length - totalRead;
                            read = stream.Read(state, totalRead, cbToRead);
                        } while (read > 0);
                    }
                }
                catch (SerializationException)
                {
                    nonSerializable = true;
                    return;
                }
                finally
                {
                    stream.Close();
                }
            }
            /// <summary>
            /// Make string sql safe
            /// </summary>
            /// <param name="val"></param>
            /// <returns></returns>
            private string SqlEscape(string val)
            {
                if (null == val)
                    return null;

                return val.Replace("'", "''");
            }
            /*
            static char[] hexDigits = {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
            /// <summary>
            /// Convert a byte array to a string of hex chars for sql image type
            /// </summary>
            /// <param name="bytes"></param>
            /// <returns></returns>
            private static string ToHexString( byte[] bytes )
            {
                if ( null == bytes )
                    return null;

                if ( 0 == bytes.Length )
                    return null;

                char[] chars = new char[bytes.Length * 2];
                for ( int i = 0; i < bytes.Length; i++ )
                {
                    int b = bytes[i];
                    chars[i * 2] = hexDigits[b >> 4];
                    chars[i * 2 + 1] = hexDigits[b & 0xF];
                }
                return "0x" + new string( chars );
            }
            */
            private void GetCallPathKeys(IList<string> callPath)
            {
                if ((null == callPath) || (callPath.Count <= 0))
                    return;

                for (int i = 0; i < callPath.Count; i++)
                {
                    _callPathKey = _callPathKey + "." + callPath[i];
                    if (i < callPath.Count - 1)
                        _parentCallPathKey = _parentCallPathKey + "." + callPath[i];
                }

                if (null != _callPathKey)
                    _callPathKey = SqlEscape(_callPathKey.Substring(1));

                if (null != _parentCallPathKey)
                    _parentCallPathKey = SqlEscape(_parentCallPathKey.Substring(1));
            }

            private string GetActivitiesXml(CompositeActivity root)
            {
                if (null == root)
                    return null;

                StringBuilder sb = new StringBuilder();
                XmlWriter writer = XmlWriter.Create(sb);

                try
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Activities");

                    WriteActivity(root, writer);

                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
                finally
                {
                    writer.Flush();
                    writer.Close();
                }

                return sb.ToString();
            }

            private void WriteActivity(Activity activity, XmlWriter writer)
            {
                if (null == activity)
                    return;
                if (null == writer)
                    throw new ArgumentNullException("writer");

                Type t = activity.GetType();

                writer.WriteStartElement("Activity");
                writer.WriteElementString("TypeFullName", t.FullName);
                writer.WriteElementString("AssemblyFullName", t.Assembly.FullName);
                writer.WriteElementString("QualifiedName", activity.QualifiedName);
                //
                // Don't write the element if the value is null, sql will see a missing element as a null value
                if (null != activity.Parent)
                    writer.WriteElementString("ParentQualifiedName", activity.Parent.QualifiedName);
                writer.WriteEndElement();

                if (activity is CompositeActivity)
                    foreach (Activity a in GetAllEnabledActivities((CompositeActivity)activity))
                        WriteActivity(a, writer);
            }


            // This function returns all the executable activities including secondary flow activities.
            private IList<Activity> GetAllEnabledActivities(CompositeActivity compositeActivity)
            {
                if (compositeActivity == null)
                    throw new ArgumentNullException("compositeActivity");

                List<Activity> allActivities = new List<Activity>(compositeActivity.EnabledActivities);

                foreach (Activity secondaryFlowActivity in ((ISupportAlternateFlow)compositeActivity).AlternateFlowActivities)
                {
                    if (!allActivities.Contains(secondaryFlowActivity))
                        allActivities.Add(secondaryFlowActivity);
                }

                return allActivities;
            }


            internal string GetXomlDocument(object obj)
            {
                string xomlText = null;
                using (StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
                {
                    using (XmlWriter xmlWriter = CreateXmlWriter(stringWriter))
                    {
                        WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
                        serializer.Serialize(xmlWriter, obj);
                        xomlText = stringWriter.ToString();
                    }
                }
                return xomlText;
            }


            #endregion

        }
    }
}