summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/contactsmodel/cntsrv/src/ccntstatemachine.cpp
blob: 85003c6408c8e1074ffc2aabf5fc22e3aa66baec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
/*
* Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: 
*
*/

/**
 @file
 @internalTechnology
 @released 
*/

#include "ccntstatemachine.h"
#include "ccntrequest.h"
#include "ccntdbmanager.h"
#include "ccntbackuprestoreagent.h"
#include "persistencelayer.h"
#include "cntspeeddials.h"
#include <cntfldst.h>         // for ccontacttextfield
#include <cntfield.h>         // for ccontacttextfield
#include "cntstd.h"           // for Panic codes

// Event related headers
#include <cntdbobs.h>         // for ccontactdbobserver
#include "ccntserver.h"     // for KCntNullConnectionId.
#include "ccnteventqueue.h" // for KMaxNumberOfEventsInEventQueue, KCntEventGranularity
#include "ccntlogger.h"  

// Require SQL header for leave code checking
#include <sqldb.h>
    
/** 
CState - Base state destructor, default implementataion
*/
CState::~CState() 
    {}

/**
 CState constructor. 
 The main purpose of the CState class is to define the state transition table.
 The CState class implements the most common state behaviour for each request object, 
 in the overridden AcceptRequestL method.
 Note there is no NewL method on the CState class. It is not meant to be instantiated.
 
 @param aStateMachine The statemachine object that is used for state transitions
 @param aPersistenceLayer The persistence layer that allows provides database access
 
*/    
CState::CState(CCntStateMachine& aStateMachine, CPersistenceLayer&    aPersistenceLayer)
:iStateMachine(aStateMachine), iPersistenceLayer(aPersistenceLayer)
    {}

/**
 TransactionStartLC is called from many derived states. The session that started the
 transaction is remembered in order to only allow that session perform database operations
 during the transaction. 
 Transaction rollback is pushed onto the clean up stack in case of a leave should occur before the
 transaction is committed. If the transaction can not be committed in full, then none of
 the transaction should be committed.
 
 @param aSessionId The unique ID of session that is moving the state machine into a transaction state.
*/
void CState::TransactionStartLC(TUint aSessionId)
    {
    iCurrentTransactionSessionId = aSessionId;
    iPersistenceLayer.FactoryL().GetCollectorL().Reset();
    iPersistenceLayer.TransactionManager().StartTransactionL();
    CleanupStack::PushL(TCleanupItem(CState::CleanupTransactionRollback, this));
    }

/** 
 Rollback a transaction after an leave has occured.
 None of the transaction is committed to the database
 
 @param aState The state in which the leave occured
*/
void CState::CleanupTransactionRollback(TAny* aState)
    {
    TRAP_IGNORE(static_cast<CState*>(aState)->RollbackTransAndRecoverL(EFalse));
    }

/**
 Commit the current transaction.
*/
void CState::TransactionCommitLP()
    {
    iPersistenceLayer.TransactionManager().CommitCurrentTransactionL(iCurrentTransactionSessionId);
    iCurrentTransactionSessionId = 0;
    CleanupStack::Pop(); // CleanupTransactionRollback
    }

/**
 Clean up the transaction after a leave occurs. 
*/
void CState::RollbackTransAndRecoverL(const TBool aNotification)
    {
    // Some operation has left before a commit could be called.
    iPersistenceLayer.TransactionManager().RollbackCurrentTransactionL(iCurrentTransactionSessionId);
    iCurrentTransactionSessionId = 0;
    
    iPersistenceLayer.ContactsFileL().CloseTablesL(!aNotification);
    iPersistenceLayer.ContactsFileL().OpenTablesL(!aNotification);
    iStateMachine.SetCurrentStateL(iStateMachine.StateWritable());
    }

/* Note: The following methods implement default 
   AcceptRequestL behaviour for all states derived 
   from Parent Class CState
*/

/* 
 Default behaviour: The file has already been opened 
 so complete KErrNone.
 
 @param aRequest Open database request object
 @return TAccept EProcessed - finished processing request
*/ 
TAccept CState::AcceptRequestL(CReqAsyncOpen* aRequest)
    {
    aRequest->Complete();
    return EProcessed;
    }

/**
 Default behaviour is to defer the request

 @param aRequest Update contact item request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqUpdateCnt* aRequest)
    {
    return DeferRequest(aRequest);
    }

/**
 Default behaviour is to defer the request

 @param aRequest Commit contact item request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqCommitCnt* aRequest)
    {
    return DeferRequest(aRequest);
    }
    

/** 
 Default behaviour is to allow read access on the database    
 Open is the same as read but with locking - does not change the database    

 @param aRequest Open contact item request object
 @return EProcessed if the request is completed or one of the values returned by 
         CState::DeferRequest if the database is currently locked.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqOpenCnt* aRequest)
    {
    if (iStateMachine.TransactionLockL().LockLX(aRequest->SessionId(), aRequest->CntItemId()) == KErrInUse)
        {
        // The contact item has been locked by another session
        aRequest->SetTimeOutError(KErrInUse);
        return DeferRequest(aRequest);
        }

    CContactItem* cntItem = iPersistenceLayer.PersistenceBroker().ReadLC(aRequest->CntItemId(), aRequest->ItemViewDef(), EPlAllInfo, aRequest->SessionId(), ETrue);
    aRequest->CompleteL(*cntItem);
    CleanupStack::PopAndDestroy(cntItem); 
    CleanupStack::Pop(); // we do not destroy it since that would trigger the leave mechanism and unlock the record
    return EProcessed;
    }

/**
 Default behaviour is to allow read access on the database.
 Read Contact does not change the database
 
 @param aRequest Read contact item request object
 @return TAccept EProcessed - finished processing request
*/ 
TAccept CState::AcceptRequestL(CReqReadCnt* aRequest)
    {
    CContactItem* cntItem = iPersistenceLayer.PersistenceBroker().ReadLC(aRequest->CntItemId(), aRequest->ItemViewDef(), EPlAllInfo, aRequest->SessionId());
    aRequest->CompleteL(*cntItem);
    CleanupStack::PopAndDestroy(cntItem);
    return EProcessed;
    }

/**
 Default behaviour is to defer the request

 @param aRequest Delete contact item request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqDeleteCnt* aRequest)
    {
    return DeferRequest(aRequest);
    }
    
/**
 Default behaviour is to close the contact item by removing the locking 
 The lock was added during from an Open Contact Request
 If the contact id is supplied, explicity unlock that contact item, otherwise
 unlock the last contact item locked by the session

 @param aRequest Close contact item request object
 @return TAccept EProcessed - finished processing request
*/  
TAccept CState::AcceptRequestL(CReqCloseCnt* aRequest)
    {
    if (aRequest->CntItemId() > KNullContactId)
        {
        aRequest->Complete(iStateMachine.TransactionLockL().UnLockL(aRequest->SessionId(), aRequest->CntItemId()));    
        }
    else
        {
        iStateMachine.TransactionLockL().UnlockLastLockedContactL(aRequest->SessionId());
        aRequest->Complete(KErrNone);
        }
    return EProcessed;
    }

/**
 Default behaviour is to always allow a session to unlock any contact 
 items that remain locked for that session before the session is closed

 @param aRequest Unlock all contact items request object  
 @return TAccept EProcessed - finished processing request
*/  
TAccept CState::AcceptRequestL(CReqInternalSessionUnlock* aRequest)
    {
    iStateMachine.TransactionLockL().UnLockAllL(aRequest->SessionId());
    aRequest->Complete(KErrNone);
    return EProcessed;
    }

/**
 Default behaviour is to defer the request

 @param Create contact item request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqCreateCnt* aRequest)
    {
    return DeferRequest(aRequest);
    }

/**
 The default behaviour for Cancelling an Asyncronous Open database command
 is to accept the file has been opened.
 
 @param aRequest Cancel database open request object 
 @return TAccept EProcessed - finished processing request
*/ 
TAccept CState::AcceptRequestL(CReqCancelAsyncOpen* aRequest)
    {
    aRequest->Complete();
    return EProcessed;
    }


/**
 Default behaviour is to defer the request
   
 @param aRequest Close contact database tables request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqCloseTables* aRequest)
    {
    return DeferRequest(aRequest);
    }

/**
 Default behaviour is to defer the request

 @param aRequest ReOpen contact database tables request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqReOpen* aRequest)
    {
    return DeferRequest(aRequest);
    }

/**
 Default behaviour is to defer the request

 @param aRequest Begin transaction request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqDbBeginTrans* aRequest)
    {
    return DeferRequest(aRequest);
    }

/**
 Default behaviour is to defer the request

 @param aRequest Commit transaction request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqDbCommitTrans* aRequest)
    {
    return DeferRequest(aRequest);
    }

/**
 Default behaviour is to defer the request

 @param aRequest Rollback transaction request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
 */
TAccept CState::AcceptRequestL(CReqDbRollbackTrans* aRequest)
    {
    return DeferRequest(aRequest);
    }

/**
 Default behaviour is to defer the request

 @param aRequest Notification of database backup/restore request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqBackupRestoreBegin* aRequest)
    {
    return DeferRequest(aRequest);
    }

/**
 Default behaviour is to complete the request

 @param aRequest Notification that a backup/restore has finished request object
 @return TAccept EProcessed - finished processing request
*/
TAccept CState::AcceptRequestL(CReqBackupRestoreEnd* aRequest)
    {
    // In most cases no backup/restore will be in progress so by default
    // complete this request.
    aRequest->Complete();
    return EProcessed;
    }
  
/**
 Default behaviour is set an internal low disk flag to true
 
 @param aRequest Notification of low disk space request object
 @return TAccept EProcessed - finished processing request
*/  
TAccept CState::AcceptRequestL(CReqDiskSpaceLow* aRequest)
    {
    iStateMachine.SetLowDisk(ETrue);
    aRequest->Complete();
    return EProcessed;
    }

/**
 Default behaviour is to set an internal low disk flag to false

 @param aRequest Notification disk space is normal request object
 @return TAccept EProcessed - finished processing request
*/
TAccept CState::AcceptRequestL(CReqDiskSpaceNormal* aRequest)
    {
    iStateMachine.SetLowDisk(EFalse);
    aRequest->Complete();
    return EProcessed;
    }

/**
 Default behaviour is set an internal async activity flag to true
 
 @param aRequest Notification of async activity request object
 @return TAccept EProcessed - finished processing request
*/  
TAccept CState::AcceptRequestL(CReqAsyncActivity* aRequest)
    {
    iStateMachine.SetAsyncActivity(ETrue);
    aRequest->Complete();
    return EProcessed;
    }

/**
 Default behaviour is to set an internal async activity flag to false

 @param aRequest Notification of no async activity request object
 @return TAccept EProcessed - finished processing request
*/
TAccept CState::AcceptRequestL(CReqNoAsyncActivity* aRequest)
    {
    iStateMachine.SetAsyncActivity(EFalse);
    aRequest->Complete();
    return EProcessed;
    }

/**
 Default behaviour is to defer the request

 @param aRequest Speed dial request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqSetSpeedDial* aRequest)
    {
    return DeferRequest(aRequest);    
    }

/**
 Default behaviour is to defer the request

 @param aRequest Own card request object
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::AcceptRequestL(CReqSetOwnCard* aRequest)
    {
    return DeferRequest(aRequest);    
    }


/**
 Don't do anything with the event here. Simply propagate the event to the dbmanager
 Any state that wishes to handle the event implements it's own overwritten 
 HandleDatabaseEventL method. The only state
 that actually implements this is the Transaction State.
 
 @param aEvent Database event generated in the Persistence Layer
*/ 
void CState::HandleDatabaseEventV2L(TContactDbObserverEventV2 aEvent)
	{
	iStateMachine.DbManager().HandleDatabaseEventV2L(aEvent);
	}

/**
 Sets a timeout error code on the request. This error code is retrieved from the 
 derived state class via a call to TimeOutErrorCode() 
 if the derived state class does not implement a overridden TimeOutErrorCode(), 
 the CState::TimeOutErrorCode() is used.
 
 Calls CState::DeferRequest to determine if the request should be deferred or not
 depending on the request's timer status.

 @param aRequest The request on which the timeout error is set.
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CState::DeferWithTimeOutError(CCntRequest* aRequest)
    {
    // use the time out error code specified with the current state
    aRequest->SetTimeOutError(TimeOutErrorCode());

    return DeferRequest(aRequest);
    }

/**
 Determines if an un-processed request should be completed with timeout error or if it 
 should be re-tried again later, depending on the current status of the request's timer.  

 @param aRequest The request failed to be processed by the current state
 @return EDeferred - if the request's timer has not expired, the request can be processed again at the 
                     next opportunity.
         EProcessed - if the request's timer has expired and is completed with timeout 
                      error.
*/    
TAccept CState::DeferRequest(CCntRequest* aRequest)
    {
    // request still cannot be processed, check if the timer on the request
    // has expired yet
    if (aRequest->TimeOut() <= 0)
        {
        // timer expired, request should be completed with timeout error
        aRequest->Complete(aRequest->TimeOutError());
        return EProcessed;
        }

    // timer still valid, as request cannot be processed now, signal to re-try again later
    return EDeferred;
    }

/** 
 Returns the default timeout - KErrNotReady
*/
TInt CState::TimeOutErrorCode()
    {
    return KErrNotReady;
    }


/** 
 CStateClosed Class NewL factory constructor
 @see CState constructor
*/
CStateClosed* CStateClosed::NewL(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
    {
    CStateClosed* stateClosed = new (ELeave) CStateClosed(aStateMachine, aPersistenceLayer);
    return stateClosed;
    }

/** 
 CStateClosed Class constructor
 @see CState constructor
*/
CStateClosed::CStateClosed(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
:CState(aStateMachine, aPersistenceLayer)
    {}

/** 
 CStateClosed Class destructor
 @see CState destructor
*/
CStateClosed::~CStateClosed() {}


/**
 Process an open request in the closed state.
 Note on the State design pattern:
 Unlike the common state design pattern, most of the work is done in
 the opening state and not in the closed state before the state transition.
 The reason for this is re-use of code. 
 
 @param aRequest Open database request object
 @return TAccept EProcessed if finished processing request
                 EDeferred if the request was not processed 
*/        
TAccept CStateClosed::AcceptRequestL(CReqAsyncOpen* aRequest)
    {
    iStateMachine.SetCurrentStateL(iStateMachine.StateOpening());
    return iStateMachine.CurrentState().AcceptRequestL(aRequest);
    }

/**
 We can only process re-open tables requests in the CStateTablesClosed
 which means that this request must be preceeded by both a CReqAsyncOpen &
 a CReqCloseTables. The correct behaviour is to defer the request with
 the default CStateClosed timeout error.
 
 @param aRequest ReOpen database tables request object 
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/

TAccept CStateClosed::AcceptRequestL(CReqReOpen* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }


/** 
 Overridden read-only operations from base class: can't read from the database
 while in the Closed state so defer these requests.
 
 @param aRequest Read contact item request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqReadCnt* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/**
 Defer Update requests with the default error for CStateClosed.
 Note: This default error code is taken from the original
 contacts model.
 
 @param aRequest Update contact item request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/ 
TAccept CStateClosed::AcceptRequestL(CReqUpdateCnt* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/** 
 Defer Commit requests
 The default error for CStateClosed has been taken from the original 
 contacts model

 @param aRequest Commit contact item request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqCommitCnt* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/** 
 Defer Delete requests
 The default error for CStateClosed has been taken from the original 
 contacts model

 @param aRequest Delete contact item request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqDeleteCnt* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/** 
 Defer Create requests
 The default error for CStateClosed has been taken from the original 
 contacts model

 @param aRequest Create contact item request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqCreateCnt* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/** 
 Defer Open requests
 The default error for CStateClosed has been taken from the original 
 contacts model
 The default behaviour of the parent class CStateis to process an open request, the Closed State    
 defers this request

 @param aRequest Commit contact item request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqOpenCnt* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/**
 Defer the Close tables request
 The tables are closed but so is the file. 
 To close the tables the file must be open
     
 @param aRequest Close database tables request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqCloseTables* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }
  
/**
 Defer begin transaction requests  
 The default behaviour of the parent class CState is to process a begin transaction request, 
 the Closed State defers this request

 @param aRequest Begin transaction request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqDbBeginTrans* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/**
 Defer commit transaction requests  
 The default behaviour of the parent class CState is to process a commit transaction request, 
 the Closed State defers this request

 @param aRequest Commit transaction request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqDbCommitTrans* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/**
 Defer rollback transaction requests  
 The default behaviour of the parent class CState is to process a rollback transaction request, 
 the Closed State defers this request

 @param aRequest Rollback transaction request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqDbRollbackTrans*  aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/**
 Defer set speed dial requests  
 The default behaviour of the parent class CState is to process a set speed dial request, 
 the Closed State defers this request

 @param aRequest Set speed dial request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/
TAccept CStateClosed::AcceptRequestL(CReqSetSpeedDial* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }

/**
 Defer set own card requests  
 The default behaviour of the parent class CState is to process a set own card request, 
 the Closed State defers this request

 @param aRequest Set own card request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferWithTimeOutError
*/    
TAccept CStateClosed::AcceptRequestL(CReqSetOwnCard* aRequest)
    {
    return DeferWithTimeOutError(aRequest);
    }


/**
 Backup/restore begin notification requests  

 @param aRequest backup/restore begin notification request object  
 @return TAccept EProcessed
*/    
TAccept CStateClosed::AcceptRequestL(CReqBackupRestoreBegin* aRequest)
    {
    // Backup/restore can take place from this state so close the files.
    // First reset collection, since it construct views based on table 
    // Reset will fail if called after closing tables 
    iPersistenceLayer.FactoryL().GetCollectorL().Reset(); 
    // Close the file to allow the backup/restore to take place.    
    iPersistenceLayer.ContactsFileL().Close();
    iStateMachine.SetCurrentStateL(iStateMachine.StateBackupRestore());
    aRequest->Complete();
    return EProcessed;
    }


/** 
 CStateTablesClosed Class NewL factory constructor
 @see CState constructor
*/      
CStateTablesClosed* CStateTablesClosed::NewL(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
    {
    CStateTablesClosed* stateTablesClosed = new (ELeave) CStateTablesClosed(aStateMachine, aPersistenceLayer);
    return stateTablesClosed;
    }
  
/** 
 CStateTablesClosed Class destructor
 @see CState Destructor
*/      
CStateTablesClosed::~CStateTablesClosed()
    {
    }
  
/** 
 CStateTablesClosed Class constructor
 @see CState constructor
*/      
CStateTablesClosed::CStateTablesClosed(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer) 
  :CStateClosed(aStateMachine, aPersistenceLayer)
    {
    }
  
  
/**
 Accept re-open tables requests  
 The tables are closed. A re-open request will result in re-opening the tables.
   
  @param aRequest re-open tables request object  
  @return TAccept EProcessed - the request was processed 
*/
TAccept CStateTablesClosed::AcceptRequestL(CReqReOpen* aRequest)
    {
    iPersistenceLayer.ContactsFileL().OpenTablesL(ETrue);
    // We can only ever come into this state from the writable state
    // as the database must have been opened
    iStateMachine.SetCurrentStateL(iStateMachine.StateWritable());
    aRequest->Complete();
    return EProcessed;
    }
  
/**
  Accept Open database requests  
  The tables are closed. An async open request will result in re-opening the
  tables.
    
  @param aRequest async open request object  
  @return TAccept EProcessed if finished processing request
*/
TAccept CStateTablesClosed::AcceptRequestL(CReqAsyncOpen* aRequest)
    {
    iPersistenceLayer.ContactsFileL().OpenTablesL(ETrue);
    // We can only ever come into this state from the writable state
    // as the database must have been opened
    iStateMachine.SetCurrentStateL(iStateMachine.StateWritable());
    aRequest->Complete();
    return EProcessed;
    }

/** 
 CStateOpening Class NewL factory constructor
 @see CState constructor
*/ 
CStateOpening* CStateOpening::NewL(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
    {
    CStateOpening* stateOpening = new (ELeave) CStateOpening(aStateMachine, aPersistenceLayer);
    CleanupStack::PushL(stateOpening);
    stateOpening->ConstructL();
    CleanupStack::Pop(stateOpening);
    return stateOpening;
    }

/** 
 CStateOpening ConstructL, gets and holds an instance of the persisitnce layer contact file interface
 and creates and ActiveLoop object which facilitates long running operations.  
 @see CState constructor
*/
void CStateOpening::ConstructL()
    {
    iCntFile = &(iPersistenceLayer.ContactsFileL());
    iActive = CActiveLoop::NewL();
    }
/** 
 CStateOpening constructor
 @see CState constructor
*/
CStateOpening::CStateOpening(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
:CState(aStateMachine, aPersistenceLayer)
    {
    }

/** 
 CStateOpening Class destructor
 @see CState destructor
*/    
CStateOpening::~CStateOpening()
    {
    delete iActive;
    delete iFileName;
    iOpenReqsStore.ResetAndDestroy();
    }

/**
 Accept Open database requests  
 Opens the database file and tables.
  
 @param aRequest Open database request object  
 @return EOwnershipPassed 
 @see CStateOpening::OpenDatabaseFileL
*/
TAccept CStateOpening::AcceptRequestL(CReqAsyncOpen* aRequest)
    {
    SetFileNameL(aRequest->FileName()); 
    return OpenDatabaseFileL(aRequest);
    }

/**
 Private member function that starts the database opening process.  
 This method may be called from several AcceptRequestL methods.
 
 @param aRequest Open database request object  
 @return EOwnershipPassed to indicate ownership of the open database request has 
         been transferred
*/
TAccept CStateOpening::OpenDatabaseFileL(CCntRequest* aRequest, TBool aNotify)
    {
    // Add this request to the store where it will be completed on completion of 
    // the open operaion
    //
    // Note that after the request is successfully transferred to the Request 
    // Store, no leave can occur until the caller is notified that ownership
    // of the request has been transferred.
    iOpenReqsStore.AppendL(aRequest);

    iNotify = aNotify;

    // If we are not already processing an open request, start opening the file.
    if (!iActive->IsActive())
        {
        InitialStep();
        }

    return EOwnershipPassed;
    }

/**
 Accept the Reopen tables request as the tables are being opened anyway

 @param aRequest Open database request object  
 @return EOwnershipPassed 
 @see CStateOpening::OpenDatabaseFileL
*/
TAccept CStateOpening::AcceptRequestL(CReqReOpen* aRequest)
    {
    // Open the database and notify (ETrue) all session of the recovery 
    return OpenDatabaseFileL(aRequest, ETrue);
    }

/** 
 Explicit cancel of an asyncronous Open Database request

 @param aRequest Open database request object  
 @return TAccept EProcessed 
*/
TAccept CStateOpening::AcceptRequestL(CReqCancelAsyncOpen* aRequest)
    {
    TInt max = iOpenReqsStore.Count();
    for (TInt ii = 0; ii < max; ++ii)
        {
        if (aRequest->SessionId() == iOpenReqsStore[ii]->SessionId())
            {
            // If we only have one concurrent open request, cancel the open
            // operation
            if (max == 1)
                {
                iCntFile->Close();
                iActive->Cancel();
                iStateMachine.SetCurrentStateL(iStateMachine.StateClosed());
                }
            
            iOpenReqsStore[ii]->Complete(KErrCancel);
            aRequest->Complete();
            delete iOpenReqsStore[ii];
            iOpenReqsStore.Remove(ii);
            return EProcessed;
            }
        }
    aRequest->Complete(KErrNotFound);
    return EProcessed;
    }

/**
 Start Opening the database using the CActiveLoop class. Opening a file
 is a long running operation and is done in steps allowing other active objects
 processor time between each opening step.
*/
void CStateOpening::InitialStep()
	{
	iActive->Register( *this );
	}

/** 
Perform the next step in the opening operation 
@see InitialStep for more details
*/
TBool CStateOpening::DoStepL()
	{
	if (!iFileName)
		{
		User::Leave(KErrGeneral);
		}

#ifdef __VERBOSE_DEBUG__
	RDebug::Print(_L("[CNTMODEL] ------------- Open Database Step -------------"));
#endif

#if defined(__PROFILE_DEBUG__)
	RDebug::Print(_L("[CNTMODEL] MTD:CStateOpening::DoStepL"));
#endif 
		
    iCntFile->OpenL(*iFileName);		
    // always go to this code if using SQLite
	#ifdef __VERBOSE_DEBUG__
  		RDebug::Print(_L("[CNTMODEL] ------------- Database Opened -------------"));
	#endif
		// The file is now open.
		DoCompletion(KErrNone);	
		iStateMachine.SetCurrentStateL(iStateMachine.StateWritable());
		// Check if Backup/Restore Agent indicates backup in progress (i.e. we
		// are opening database after backup starts).
		if (iStateMachine.DbManager().BackupRestoreAgent().BackupInProgress())
			{
			TContactDbObserverEventV2 event;
			event.iType = EContactDbObserverEventBackupBeginning;
			event.iContactId = 0;
			event.iConnectionId = 0;
	        event.iTypeV2 = EContactDbObserverEventV2Null;
	        event.iAdditionalContactIds = NULL;
			// The HandleBackupRestoreEventL() method of the CCntDbManager that
			// owns this state machine is called to send the appropriate request
			// to the state machine and to notify any observers.  The request
			// causes a transition from CStateWritable to CStateBackupRestore.
			// We need to send this event here since the event has only been
			// heard by CCntDbManager instances (and any of its observers) that
			// existed at the time when the backup first started.
			iStateMachine.DbManager().HandleBackupRestoreEventL(event);
			}
		return EFalse;
	}
	
/** 
 Complete all Opening requests. More than one client (or internal 
 request) may open a database file simultaneously. 
 DoCompletion completes all outstanding Open requests.
 
 @param aError The error code used to complete the request.
 */
void CStateOpening::DoCompletion(TInt aError)
    {
    TInt max = iOpenReqsStore.Count();
    for (TInt ii = 0; ii < max; ++ii)
        {
        iOpenReqsStore[ii]->Complete(aError);
        }
    iOpenReqsStore.ResetAndDestroy();
    }

/**
 Completes all open requests with an error code    

 @param aError The error code used to complete the request. 
*/ 
void CStateOpening::DoError(TInt aError)
    {

    DEBUG_PRINT2(__VERBOSE_DEBUG__,_L("[CNTMODEL] ------------- Database Open Error %d -------------"), aError);

    DoCompletion(aError);
    TRAP_IGNORE(iStateMachine.SetCurrentStateL(iStateMachine.StateClosed() ) );
    }

/**
 Sets the name of the file that is being opened. The name is held by
 the opeing state and re-used when database needs to be closed and 
 re-opened (for example during recovery)
 
 @param aFileName The name of the file that is being opened
*/ 
void CStateOpening::SetFileNameL(const TDes& aFileName)
    {
    HBufC* tmpFileName  = HBufC::NewL(aFileName.Length());
    *tmpFileName = aFileName;
    delete iFileName;
    iFileName = tmpFileName;
    }

/**
 Once a Backup or Restore has completed we can re-open the database.
 
 @param aRequest Notification of Backup/Restore end request object  
 @return EOwnershipPassed 
 @see CStateOpening::OpenDatabaseFileL
*/ 
TAccept CStateOpening::AcceptRequestL(CReqBackupRestoreEnd* aRequest) 
    {
    return OpenDatabaseFileL(aRequest);
    }

/** 
 Overridden read-only operations from base class: can't read from the database
 while in the Opening state so defer these requests.
 
 @param aRequest Read contact item request object  
 @return EDeferred if the request is not processed, EProcessed if the request is
         completed with timeout error.
 @see CState::DeferRequest 
*/
TAccept CStateOpening::AcceptRequestL(CReqReadCnt* aRequest)
    {
    return DeferRequest(aRequest); // Uses the requests default timeout error
    }

// @see CStateOpening::AcceptRequestL(CReqReadCnt* )
TAccept CStateOpening::AcceptRequestL(CReqOpenCnt* aRequest)
    {
    return DeferRequest(aRequest);
    }



// CStateWritable Class implementation //

/** 
 CStateWritable Class NewL factory constructor
 @see CState constructor
*/ 
CStateWritable* CStateWritable::NewL(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
    {
    CStateWritable* stateWritable = new (ELeave) CStateWritable(aStateMachine, aPersistenceLayer);
    return stateWritable;
    }

/** 
 CStateWritable Class constructor
 @see CState constructor
*/ 
CStateWritable::CStateWritable(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
:CState(aStateMachine, aPersistenceLayer)
    {
    }

/** 
 CStateWritable Class destructor
 @see CState destructor
*/ 
CStateWritable::~CStateWritable()
    {
    }


// Derived AcceptRequestL methods - Vistor Pattern

/**
 Update a contact item in the database

 @param aRequest Update contact item request object  
 @return TAccept EProcessed if finished processing request or one of the 
         values returned by DeferWithTimeOutError
 @see CState::DeferWithTimeOutError
*/
TAccept CStateWritable::AcceptRequestL( CReqUpdateCnt* aRequest )
    {
    if ( iStateMachine.LowDisk( ) )
        {
        aRequest->Complete( KErrDiskFull );
        return EProcessed;
        }
    // Check if the contact has been locked 
    if (iStateMachine.TransactionLockL( ).IsLocked( aRequest->Item( ).Id( ) ) )
        {
        // If the request can not be procesed after the timeout period, it should 
        // complete with KErrInUse to assure binary compatibility with the original model
        return DeferWithTimeOutError( aRequest );
        }

    TRAPD( updateErr,  // codescanner::trapcleanup:TransactionStartLC and TransactionCommitLP were used in couples.
        {
        TransactionStartLC(aRequest->SessionId());
        iPersistenceLayer.PersistenceBroker( ).SetConnectionId( aRequest->SessionId( ) );
        iPersistenceLayer.PersistenceBroker( ).UpdateL( aRequest->Item( ), aRequest->SessionId( ) );
        TransactionCommitLP( );
        });

    if ( updateErr == KSqlErrGeneral )
        {
        // Write operation failed, probably due to view read activity
        return DeferWithTimeOutError( aRequest );
        }
    else if ( updateErr != KErrNone )
        {
        // Unknown error, propagate the leave to the client
        User::Leave( updateErr );
        }

    aRequest->Complete( );
    return EProcessed;
    }

/**
 Commit an opened contact item to the database  
 Unlock the contact item so other session can modify it.
 Starts and commits a local transaction inorder to handle leaves.
 
 @param aRequest Commit contact item request object  
 @return TAccept EProcessed if finished processing request or one of the 
         values returned by DeferWithTimeOutError
 @see CState::DeferWithTimeOutError
*/
TAccept CStateWritable::AcceptRequestL( CReqCommitCnt* aRequest )
    {
    if ( iStateMachine.LowDisk( ) )
        {
        aRequest->Complete( KErrDiskFull );
        return EProcessed;
        }

    // Check if the contact has been locked by this session
    if ( iStateMachine.TransactionLockL( ).IsLocked( aRequest->SessionId( ), aRequest->Item( ).Id( ) ) )
        {
        // If the request can not be procesed after the timeout period, it should 
        // complete with KErrInUse to assure binary compatibility with the original model
        return DeferWithTimeOutError( aRequest );
        }
    
    TRAPD( commitErr,  // codescanner::trapcleanup:TransactionStartLC and TransactionCommitLP were used in couples.
        {
        TransactionStartLC(aRequest->SessionId());
        iPersistenceLayer.PersistenceBroker( ).SetConnectionId( aRequest->SessionId( ) );
        iPersistenceLayer.PersistenceBroker( ).UpdateL(aRequest->Item( ), aRequest->SessionId( ) );
        User::LeaveIfError(iStateMachine.TransactionLockL( ).UnLockL(aRequest->SessionId( ), aRequest->Item( ).Id( ) ) );
        TransactionCommitLP();
        });
    if ( commitErr == KSqlErrGeneral )
        {
        // Can't commit contact, probably due to idle sorter activity
        return DeferWithTimeOutError( aRequest );
        }
    else
        {
        User::LeaveIfError( commitErr );
        }
    
    aRequest->Complete( );
    return EProcessed;
    }


/**
 Delete a contact item from the database. 
 Starts and commits a local transaction inorder to handle leaves.
 Checks if the contact item is locked by another session.
 
 @param aRequest Delete contact item request object  
 @return TAccept EProcessed if finished processing request or one of the 
         values returned by DeferWithTimeOutError
 @see CState::DeferWithTimeOutError
*/
TAccept CStateWritable::AcceptRequestL(CReqDeleteCnt* aRequest)
	{
    // Check if the contact has been locked 
    if (iStateMachine.TransactionLockL().IsLocked(aRequest->CntItemId()))
        {
        // If the request can not be procesed after the timeout period, it should 
        // complete with KErrInUse - the contact is locked 
        return DeferWithTimeOutError(aRequest);
        }	
	
    TRAPD(deleteErr,
        {
        TransactionStartLC(aRequest->SessionId());
    
        iPersistenceLayer.PersistenceBroker().SetConnectionId(aRequest->SessionId());
        CContactItem* cntItem = iPersistenceLayer.PersistenceBroker().DeleteLC(aRequest->CntItemId(), aRequest->SessionId(), ESendEvent);
        CleanupStack::PopAndDestroy(cntItem);
    
        TransactionCommitLP();
        });
	if (deleteErr == KSqlErrGeneral)
		{
		// Write operation failed, probably due to view read activity
		return DeferWithTimeOutError(aRequest);
		}
	else if (deleteErr != KErrNone)
		{
		// Unknown error, propagate the leave to the client
		User::Leave(deleteErr);
		}
		
	aRequest->Complete();
	return EProcessed;		
	}		
	
/**
 Create a new contact item

 @param aRequest Create contact item request object  
 @return TAccept EProcessed 
*/
TAccept CStateWritable::AcceptRequestL( CReqCreateCnt* aRequest )
    {
    if ( iStateMachine.LowDisk( ) )
        {
        aRequest->Complete( KErrDiskFull );
        return EProcessed;
        }
    
    TContactItemId cntID(KNullContactId);
    TRAPD( createErr,  // codescanner::trapcleanup:TransactionStartLC and TransactionCommitLP were used in couples.
        {
        TransactionStartLC(aRequest->SessionId());
        
        iPersistenceLayer.PersistenceBroker( ).SetConnectionId( aRequest->SessionId( ) );
        cntID = iPersistenceLayer.PersistenceBroker( ).CreateL( aRequest->Item( ), aRequest->SessionId( ) );
        TransactionCommitLP();
        });
    if ( createErr == KSqlErrGeneral )
        {
        // Write operation failed, probably due to view read activity
        return DeferWithTimeOutError( aRequest );
        }
    else if ( createErr != KErrNone )
        {
        // Unknown error, propagate the leave to the client
        User::Leave( createErr );
        }
    
    aRequest->Complete( cntID );
    return EProcessed;
    }

/**
 Change the current state of the model to CStateTablesClosed. 
 The database is unavailable.        
  
 @param aRequest Close database tables request object  
 @return TAccept EProcessed if finished processing request
*/   
TAccept CStateWritable::AcceptRequestL(CReqCloseTables* aRequest)
    {
    iPersistenceLayer.ContactsFileL().CloseTablesL(ETrue);
    iStateMachine.SetCurrentStateL(iStateMachine.StateTablesClosed());
    aRequest->Complete();
    return EProcessed;
    }


/** 
 Do nothing for Cancel - it's too late as the database is already open.

 @param aRequest Cancel open database request object  
 @return TAccept EProcessed if finished processing request
*/ 
TAccept CStateWritable::AcceptRequestL(CReqCancelAsyncOpen* aRequest)
    {
    aRequest->Complete();
    return EProcessed;
    }


/**
 Start a database transaction by moving to a transaction state        
 
 @param aRequest Begin transaction request object  
 @return TAccept EProcessed if finished processing request
                   EDeferred if the request was not processed 
*/ 
TAccept CStateWritable::AcceptRequestL(CReqDbBeginTrans* aRequest)
    {
    // In the current implementation there are no operations allowed under the
    // low disk condition that will reduce the size of the database: this is in
    // line with Contacts Model 1 behaviour.  Later, when we allow operations
    // that reduce the size of the database, this check should be removed and
    // allow the transition to CStateTransaction.
    if (iStateMachine.LowDisk())
        {
        aRequest->Complete(KErrDiskFull);
        return EProcessed;
        }
    
    iStateMachine.SetCurrentStateL(iStateMachine.StateTransaction());
    return iStateMachine.CurrentState().AcceptRequestL(aRequest);
    }

/**
 Start a database backup/restore by moving to CStateBackupRestore state.  If any
 contact items are locked or there is any asynchronous activity using the
 database then we cannot close the file (and the backup/restore client will not
 be allowed to backup/restore).

 @param aRequest Notification of backup/restore begin request object  
 @return TAccept EProcessed if finished processing request
*/ 
TAccept CStateWritable::AcceptRequestL(CReqBackupRestoreBegin* aRequest)
    {
    if (!iStateMachine.TransactionLockL().AnyLocked() &&
        !iStateMachine.AsyncActivity())
        {
        // First reset collection, since it construct views based on table 
        // Reset will fail if called after closing tables 
        iPersistenceLayer.FactoryL().GetCollectorL().Reset(); 
        // Close the file to allow the backup/restore to take place.    
        iPersistenceLayer.ContactsFileL().Close();
        }
    iStateMachine.SetCurrentStateL(iStateMachine.StateBackupRestore());
    aRequest->Complete();
    return EProcessed;
    }


/**
 Reset the speed dials        

 @param aRequest Reset speed dials request object  
 @return TAccept EProcessed if finished processing request
                   EDeferred if the request was not processed 
*/ 
TAccept CStateWritable::AcceptRequestL(CReqSetSpeedDial* aRequest)
    {
    if (iStateMachine.LowDisk())
        {
        aRequest->Complete(KErrDiskFull);
        return EProcessed;
        }
    
    TContactItemId contactId = aRequest->TheContactId();
    if(contactId == 0)
        {
        User::Leave(KErrArgument);
        }

    // Obtain the contact ID currently associated with the speed dial index.
    // The phone number is not being used at the moment
    TSpeedDialPhoneNumber phoneNumberFromSpeedDialTable;
    TContactItemId OldContactId = aRequest->SpeedDialTable().SpeedDialContactItem(aRequest->SpeedDialIndex(), phoneNumberFromSpeedDialTable);
    
    // We should not be able to remove a speed dial from an open item, even if
    // it has been opened by the same session: use the IsLocked() method which
    // ignores session ID.
    TBool isLocked = iStateMachine.TransactionLockL().IsLocked(OldContactId);        
                
    // This code resets an entry from the speed dial table, as required when calling either 
    // CContactDatabase::ResetServerSpeedDialsL() (contactId is KNullContactId) or 
    // CContactDatabase::RemoveSpeedDialFieldL()  (contactId must be equal to the OldContactId)
    // If the field index is -1, it indicates that the speed dial entry corresponding 
    // to the speed dial index passed in the request should be reset.    
    TBool doResetOldContactItem = ETrue;
    TBool doResetSpeedDialEntry = aRequest->TheFieldIndex() == -1;            
    
    if (doResetSpeedDialEntry)
        {
        if (contactId == KNullContactId || contactId == OldContactId)
            {
            if (isLocked)
                {
                User::Leave(KErrInUse);
                }
                
            aRequest->IniFileManager().SetSpeedDialIdForPositionL(aRequest->SpeedDialIndex(), KNullContactId, KNullDesC(), aRequest->SessionId(), EFalse);                    
            }
        else
            {
            doResetOldContactItem = EFalse;
            }
        }

    //Everything, i.e. removal of the old speed dial reference and 
    //the setting of the new takes place during the same transaction
    //i.e. start transaction here
    TransactionStartLC(aRequest->SessionId());
        {
        // Check if there is already a contact associated with this speed dial
        // index.
        if (OldContactId != KErrNotFound && doResetOldContactItem)
            {
            // Fetch the item from the ID, remember to pop it
            CContactItem* cntItem = iPersistenceLayer.PersistenceBroker().ReadLC(OldContactId, aRequest->ItemViewDef(), EPlAllInfo, aRequest->SessionId());    
            // Remove speed dial attributes from the contact item field.
            TUid fieldTypeUid = CCntServerSpeedDialManager::SpeedDialFieldUidFromSpeedDialPosition(aRequest->SpeedDialIndex());
            TInt fieldIdFound = cntItem->CardFields().Find(fieldTypeUid);
            if (fieldIdFound != KErrNotFound)
                {
                cntItem->CardFields()[fieldIdFound].RemoveFieldType(fieldTypeUid);
                cntItem->CardFields()[fieldIdFound].SetSpeedDial(EFalse);
                }
            // Update changes to the contact item in the database.
            iPersistenceLayer.PersistenceBroker().SetConnectionId(aRequest->SessionId());
            iPersistenceLayer.PersistenceBroker().UpdateL(*cntItem, aRequest->SessionId(), ETrue);
            CleanupStack::PopAndDestroy(cntItem);
            }
        
        if (!doResetSpeedDialEntry)
            {
            // Fetch the contact item containing the phone number to be used as
            // a speed dial.
            CContactItem* cntItem = iPersistenceLayer.PersistenceBroker().ReadLC(contactId, aRequest->ItemViewDef(), EPlAllInfo, aRequest->SessionId());    
            if (cntItem->CardFields().Count() < 1)
                {
                User::Leave(KErrUnknown);
                }
            // Get the field containing the number to be associated with the
            // speed dial.
            CContactItemField& speeddialField = cntItem->CardFields()[aRequest->TheFieldIndex()];
            // Add speed dial attributes to the contact item field.
            TUid fieldTypeUid = CCntServerSpeedDialManager::SpeedDialFieldUidFromSpeedDialPosition(aRequest->SpeedDialIndex());
            if (!speeddialField.ContentType().ContainsFieldType(fieldTypeUid))
                {
                speeddialField.AddFieldTypeL(fieldTypeUid);
                }
            speeddialField.SetUserAddedField(ETrue);
            speeddialField.SetSpeedDial(ETrue);
            // Get the phone number from the field.
            if (speeddialField.StorageType() != KStorageTypeText)
                {
                User::Leave(KErrArgument);
                }
            // Truncate it if its length is > KSpeedDialPhoneLength
            TInt numLen = Min(speeddialField.TextStorage()->Text().Length(), KSpeedDialPhoneLength);
            TPtrC phoneNumber(speeddialField.TextStorage()->Text().Mid(0, numLen));
            // Update changes to the contact item in the database.
            iPersistenceLayer.PersistenceBroker().SetConnectionId(aRequest->SessionId());
            // Update the speed dial table.
            aRequest->IniFileManager().SetSpeedDialIdForPositionL(aRequest->SpeedDialIndex(), contactId, phoneNumber, aRequest->SessionId(), EFalse);
            iPersistenceLayer.PersistenceBroker().UpdateL(*cntItem, aRequest->SessionId(), ETrue);
            // Unlock the item.
            User::LeaveIfError(iStateMachine.TransactionLockL().UnLockL(aRequest->SessionId(), contactId));
            CleanupStack::PopAndDestroy(cntItem);
            }
        }
    TransactionCommitLP();
    aRequest->Complete();
    return EProcessed;
    }


/**
 Set own card data    

 @param aRequest Set own card request object  
 @return TAccept EProcessed if finished processing request
                   EDeferred if the request was not processed 
*/         
TAccept CStateWritable::AcceptRequestL(CReqSetOwnCard* aRequest)
    {
    if (iStateMachine.LowDisk())
        {
        aRequest->Complete(KErrDiskFull);
        return EProcessed;
        }

    TUid aContactType = aRequest->Item().Type();

	// this should leave with kerrnotsupported if the type doesn't match!!!!
	if (aContactType==KUidContactGroup || aContactType==KUidContactTemplate || aContactType==KUidContactCardTemplate)
		{
		User::Leave(KErrNotSupported);	
		}
	// if the requested item is already set as own card then just return
	if (aRequest->Item().Id()==iPersistenceLayer.ContactProperties().OwnCardIdL())
		{
		aRequest->Complete();
		return EProcessed;	
		}
		
	// if the requested ID is system template or KNUllContactID then leave
	if (aRequest->Item().Id()==KGoldenTemplateId || aRequest->Item().Id()==KNullContactId)
		{
		User::Leave(KErrNotFound);
		}
	//Everything, i.e. removal of the old own card reference and 
	//the setting of the new takes place during the same transaction
	//i.e. start transaction here
	TransactionStartLC(aRequest->SessionId());
		{//reset the old own card to become an ordinary contacts card
		if (iPersistenceLayer.ContactProperties().OwnCardIdL() != KNullContactId)
			{
			// Fetch the old current item from the ID, remember to pop it
			CContactItem* oldOwnCard = iPersistenceLayer.PersistenceBroker().ReadLC(iPersistenceLayer.ContactProperties().OwnCardIdL(), aRequest->ItemViewDef(), EPlAllInfo, aRequest->SessionId());	
			iPersistenceLayer.PersistenceBroker().SetConnectionId(aRequest->SessionId());
			//change the type to KUidContactCard for the old ownCard
			iPersistenceLayer.PersistenceBroker().ChangeTypeL(oldOwnCard->Id(), KUidContactCard);
			CleanupStack::PopAndDestroy(oldOwnCard);
			}			
		iPersistenceLayer.PersistenceBroker().SetConnectionId(aRequest->SessionId());
		//Now set the new own card
		iPersistenceLayer.PersistenceBroker().ChangeTypeL(aRequest->Item().Id(), KUidContactOwnCard);
		iPersistenceLayer.ContactProperties().SetOwnCardIdL(aRequest->Item().Id(), EFalse);
		}
	TransactionCommitLP();
	aRequest->Complete();
	return EProcessed;		
	}		

/** 
 The error code which deferred requests use after a timeout from the 
 writable state  this maintians consistency with the original contacts model
 
 @return The most common the timeout error code -KErrInUse- used in the writable state
*/ 
TInt CStateWritable::TimeOutErrorCode()
    {
    return KErrInUse;
    }



// CStateTransaction Implementation//
/** 
 CStateTransaction Class NewL factory constructor
 Create a transaction state
 @see CState constructor
*/ 
CStateTransaction* CStateTransaction::NewL(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
    {
    CStateTransaction* stateTransaction = new (ELeave) CStateTransaction(aStateMachine, aPersistenceLayer);
    CleanupStack::PushL(stateTransaction);
    stateTransaction->ConstructL();
    CleanupStack::Pop(stateTransaction);
    return stateTransaction;
    }

/**
 Instantiate the CTransctionTimer object. The transaction state contains a timer
 because a client may put the server into a transation state and for some unknown 
 reason my never complete the transaction. Such a senario would result in the server
 becoming unusable (ie No other client can modify the database until the transaction 
 is completed or rolled back). If the CStateTransaction class does not hear from the
 client for a given time, the transaction times out and is rolled back. This is the 
 responsibility of the CTransactionTimer.
*/
void CStateTransaction::ConstructL()
    {
    // Pass the transaction state that will timeout.
    iTimeOut = CTransactionTimer::NewL(*this); 
    }

/** 
 CStateTransaction Class constructor
 @see CState constructor
*/ 
CStateTransaction::CStateTransaction(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
: CState(aStateMachine, aPersistenceLayer), iEventQ(KCntEventGranularity)
    {
    }

/** 
 CStateTransaction Class constructor
 @see CState constructor
*/ 
CStateTransaction::~CStateTransaction()
    {
    delete iTimeOut;
    iEventQ.Close();
    }
    
/**    
 Cancel the transaction - will result in a database rollback
 implemented in the base CState class
 This overwritten CancelTransaction is only ever called when the transaction
 times out. The base class CState::CancelTransactionL() is called when any 
 state class or persistence layer method leaves
*/
void CStateTransaction::CancelTransactionL()
    {
    CState::RollbackTransAndRecoverL(EFalse); 
    iSessionId = 0; // Allow another session enter a transaction state.
    }

/**    
 Get the CStateTransaction default timeout error code.
 
 @return TInt ErrLocked
*/
TInt CStateTransaction::TimeOutErrorCode()
    {
    return KErrLocked;
    }


/**
 Begin a database transaction, start the transaction timeout which rolls-back
 the transaction if the session dies. Reset the transactions event queue - this
 event-queue queues all events until the transaction has been committed.
 
 @param aRequest Begin a database transaction
 @return TAccept EProcessed if finished processing request, or one of the values returned
                 by CState::DeferRequest 
 @see CState::DeferRequest 
*/ 
TAccept CStateTransaction::AcceptRequestL(CReqDbBeginTrans* aRequest)
    {
    
#if defined(__PROFILE_DEBUG__)
        RDebug::Print(_L("[CNTMODEL] MTD: CStateTransaction::AcceptRequestL"));
#endif 
    
    // Only one session can ever be in a transaction state
    if (iSessionId == 0)
        {
        iSessionId = aRequest->SessionId();
        iPersistenceLayer.FactoryL().GetCollectorL().Reset();
        iPersistenceLayer.TransactionManager().StartTransactionL();
        iTimeOut->Start();
        aRequest->Complete();
        // Reset the event queue - although it is also reset when a transaction
        // is committed or explicitly rolled back, it will now be reset if a rollback occured 
        // because of a leave. Resetting the queue after commit/explicit rollback free's memory.
        iEventQ.Reset(); 
        return EProcessed;
        }
    // This session has already started a transaction     
    if (iSessionId == aRequest->SessionId())
        {
        aRequest->Complete();
        return EProcessed;
        }
    // Another session has started a transaction
    return DeferRequest(aRequest); 
    }


/**
 Commit the current transaction if started by the same session.
 Stop the transaction timer.
 Propogate all events to the observer.
 Compress the database.
 
 @param aRequest Commit a database transaction
 @return TAccept EProcessed if the transaction has been committed
 @leave KErrLocked if a different session had started the transaction
*/
TAccept CStateTransaction::AcceptRequestL(CReqDbCommitTrans* aRequest)
    {
     if (iSessionId == aRequest->SessionId())
         {
        TRAPD(commitErr, iPersistenceLayer.TransactionManager().CommitCurrentTransactionL(aRequest->SessionId()));
        if (commitErr == KSqlErrGeneral)
            {
            // Operation has probably been blocked due to read lock by view idle sorter.
            return DeferWithTimeOutError(aRequest);
            }
        else
            {
            User::LeaveIfError(commitErr);
            }
        
        iTimeOut->Stop(); // Transaction completed - shouldn't timeout

        // The database had been updated. All session should now be notified
        // of events.
        PropagateDatabaseEventsL();
        
        iStateMachine.SetCurrentStateL(iStateMachine.StateWritable());

        iSessionId = 0;
        // Only complete the request after the last leaving method. If 
        // a leave occurs after the request (message) has been completed, then the method 
        // CCntSession::ServiceError will try to complete the message a second time
        // causing a panic. 
        aRequest->Complete();
         }
     else
        {
        StrayRequestL(aRequest); // Only the current session should be able to
        }// send a commit transaction request
    return EProcessed;
    }



/** 
 Rollback the current transaction if started by the same session
 Reset the event queue as no operation has been committed to the database.
 Don't compress the database as it hasn't changed.
 Notify the observer that a rollback has occured.
 
 @param aRequest Rollback a database transaction
 @return TAccept EProcessed if the transaction has been rolled back
 @leave KErrLocked if a different session had started the transaction
*/
TAccept CStateTransaction::AcceptRequestL(CReqDbRollbackTrans* aRequest)
    {
     if (iSessionId == aRequest->SessionId())
         {
        iEventQ.Reset(); // Empty the event queue - no operations have been committed
                         // so sessions should never be notified of the event

         iCurrentTransactionSessionId = aRequest->SessionId();
        CState::RollbackTransAndRecoverL(ETrue);
        iSessionId = 0;

		// Transaction completed - shouldn't timeout
		iTimeOut->Stop(); 
	
		// Rollback event needs to be propagated.
		TContactDbObserverEventV2 event;
		event.iType			= EContactDbObserverEventRollback;
		event.iContactId	= KNullContactId;
		event.iConnectionId = iSessionId;
	    event.iTypeV2 = EContactDbObserverEventV2Null;
	    event.iAdditionalContactIds = NULL;		
		iStateMachine.DbManager().HandleDatabaseEventV2L(event);

        aRequest->Complete();
        }
    else
        {
        StrayRequestL(aRequest); // Only the current session should be able
        }                         // to rollback a transaction
    return EProcessed;
    }


/** 
 A session tried to commit or rollback a transaction that was started
 by another session. Destroy the request and leave.

 @param aRequest A pointer to a request object scoped to it parent class.
 @leave KErrLocked A different session had started the transaction
*/ 
void CStateTransaction::StrayRequestL(CCntRequest* /* aRequest */)
    {
    User::Leave(KErrLocked);
    }


/**
 Create a contact item from a the session that started the transaction
 
 @param aRequest The request that will contain the created contact item 
 @return TAccept EProcessed if finished processing request
                   EDeferred if the request was not processed 
*/
TAccept CStateTransaction::AcceptRequestL(CReqCreateCnt* aRequest)
    {
#if defined(__PROFILE_DEBUG__)
        RDebug::Print(_L("[CNTMODEL] MTD: CStateTransaction::AcceptRequestL"));
#endif
    
    if (iStateMachine.LowDisk())
        {
        aRequest->Complete(KErrDiskFull);
        return EProcessed;
        }
    
    if (iSessionId == aRequest->SessionId())
        {
        TContactItemId itemId(KNullContactId);
        TRAPD(createErr, itemId = iPersistenceLayer.PersistenceBroker().CreateL(aRequest->Item(),  aRequest->SessionId()));
        if (createErr == KSqlErrGeneral)
            {
            // Can't create contact item, probably due to view idle sorter activity
            return DeferWithTimeOutError(aRequest);
            }
        else
            {
            User::LeaveIfError(createErr);
            }
        
        aRequest->Complete(itemId);
        iTimeOut->Reset(); // restart the timeout as the client session is still alive
        return EProcessed;
        }
    
    // The session that is trying to perform this operation has not started the transaction
    return DeferWithTimeOutError(aRequest);
    }

/**
 Read a contact item - always allow read operation from any session 
 ie the session does not need to have started the transaction to read the contact item
 
 @param aRequest The request that will contain the contact item read from the database
 @return TAccept EProcessed if finished processing request
                   EDeferred if the request was not processed 
*/ 
TAccept CStateTransaction::AcceptRequestL(CReqReadCnt* aRequest)
    {
    iTimeOut->Reset(); // Reset the timeout, the client is still alive
    return CState::AcceptRequestL(aRequest);
    }
    
/**
 Update a contact item from a the session that started the transaction    
 
 @param aRequest The request that contain the contact item that is to be updated in the database
 @return TAccept EProcessed if finished processing request, or one of the values returned
                 by CState::DeferRequest 
 @see CState::DeferRequest 
*/ 
TAccept CStateTransaction::AcceptRequestL(CReqUpdateCnt* aRequest)
    {
    if (iStateMachine.LowDisk())
        {
        aRequest->Complete(KErrDiskFull);
        return EProcessed;
        }

    // Check if the contact has been locked by any session - including this session
    // This is for reasons of compatibility with the original model only
    if (iStateMachine.TransactionLockL().IsLocked(aRequest->Item().Id()) == EFalse)
        {
         if (iSessionId == aRequest->SessionId())
             {
             TRAPD(updateErr, iPersistenceLayer.PersistenceBroker().UpdateL(aRequest->Item(), aRequest->SessionId()));
            if (updateErr == KSqlErrGeneral)
                {
                // Can't update item, probably due to idle sorter activity
                return DeferWithTimeOutError(aRequest);
                }
            else
                {
                User::LeaveIfError(updateErr);
                }
            
            aRequest->Complete();
            iTimeOut->Reset(); 
            
            return EProcessed;
            }
         else
             {
             // The session that is trying to perform this operation has not started the transaction
             return DeferWithTimeOutError(aRequest);
             }
          }
    else
        {
        // If the request can not be procesed after the timeout period, it should 
        // complete with KErrInUse as the contact is locked
        aRequest->SetTimeOutError(KErrInUse);
        }
    return DeferRequest(aRequest);
    }
    
/**
 Delete a contact item if the delete request is from the same session that started the transaction
 
 @param aRequest The request that contain the contact item ID that is to be deleted from the database
 @return TAccept EProcessed if finished processing request, or one of the values returned
                 by CState::DeferRequest 
 @see CState::DeferRequest 
*/ 
TAccept CStateTransaction::AcceptRequestL(CReqDeleteCnt* aRequest)
	{
	if (iStateMachine.LowDisk())
  		{
  		aRequest->Complete(KErrDiskFull);
  		return EProcessed;
  		}	
	
    // Check if the contact has been locked by any session - including this session
    if (iStateMachine.TransactionLockL().IsLocked(aRequest->CntItemId()) == EFalse)
        {
        if (iSessionId == aRequest->SessionId())
            {
            CContactItem* item = NULL; 
            TRAPD(deleteErr, item = iPersistenceLayer.PersistenceBroker().DeleteLC(aRequest->CntItemId(), aRequest->SessionId(), aRequest->NotificationEventAction());CleanupStack::PopAndDestroy(item));
	 		
	 		if (deleteErr == KSqlErrGeneral)
	 			{
	 			// Delete failed, probably due to idle sorter activity
	 			return DeferWithTimeOutError(aRequest);
	 			}
	 		else
	 			{
	 			User::LeaveIfError(deleteErr);
	 			}
	 		
			aRequest->Complete();
			iTimeOut->Reset(); 

            return EProcessed;    
            }
        else
            {
            // The session that is trying to perform this operation has not started the transaction
            return DeferWithTimeOutError(aRequest);
            }
        }
    else
        {
        // If the request can not be procesed after the timeout period, it should 
        // complete with KErrInUse as the contact is locked
        aRequest->SetTimeOutError(KErrInUse);
        }

    return DeferRequest(aRequest);
    }


/**
 Commit (write & unlock) a contact item that has been locked to the database
 The contact item is unlocked.
 
 @param aRequest The request that contain the contact item that is to be written to the database
 @return TAccept EProcessed if finished processing request
                   EDeferred if the request was not processed 
*/ 
TAccept CStateTransaction::AcceptRequestL(CReqCommitCnt* aRequest)
    {
    if (iStateMachine.LowDisk())
        {
        aRequest->Complete(KErrDiskFull);
        return EProcessed;
        }

    if (iSessionId == aRequest->SessionId())
        {
        User::LeaveIfError(iStateMachine.TransactionLockL().UnLockL(aRequest->SessionId(), aRequest->Item().Id()));
        TRAPD(updateErr, iPersistenceLayer.PersistenceBroker().UpdateL(aRequest->Item(), aRequest->SessionId()));
        if (updateErr == KSqlErrGeneral)
            {
            // Can't update contact, probably due to idle sorter activity
            return DeferWithTimeOutError(aRequest);
            }
        else
            {
            User::LeaveIfError(updateErr);
            }
        
        aRequest->Complete();
        iTimeOut->Reset(); 
        
        return EProcessed;
        }
    else
        {
        // The session that is trying to perform this operation has not started the transaction
        return DeferWithTimeOutError(aRequest);
        }
    }

/**
 Open (read and lock) the contact item, returning the opened contact item.
 The contact item is also locked
 
 @param aRequest The request that will contain the contact item that is to be opened (read and locked) 
                  in the database
 @return TAccept EProcessed if finished processing request
                   EDeferred if the request was not processed 
*/ 
TAccept CStateTransaction::AcceptRequestL(CReqOpenCnt* aRequest)
    {
    if (iSessionId == aRequest->SessionId())
        {
        // As a valid operation has been performed by the session, it is still 
        // alive so the timeout for the transaction state must be reset.
        iTimeOut->Reset(); 
        return CState::AcceptRequestL(aRequest);
         }
    else
        {
        // The session that is trying to perform this operation has not started the transaction
        return DeferWithTimeOutError(aRequest);    
        }
    }

/**
 Close (unlock) the locked contact without commiting the contact item to the database 
 only if the session also started the transaction
 
 @param  aRequest The request that contain the contact item that is to be closed (unlocked but not updated)
 @return One of the values returned by DeferWithTimeOutError, or CState::AcceptRequest(CReqCloseCnt*)
 @see CState::DeferWithTimeOutError
 @see CState::AcceptRequest(CReqCloseCnt*)
*/ 
TAccept CStateTransaction::AcceptRequestL(CReqCloseCnt* aRequest)
    {
    if (iSessionId == aRequest->SessionId())
        {
        iTimeOut->Reset(); 
        return CState::AcceptRequestL(aRequest);
        }
    else
        {
        // The session that is trying to perform this operation has not started the transaction
        return DeferWithTimeOutError(aRequest);
        }
    }

/**
 Hanlde a database event while in the transaction state.
 The CStateTransaction holds all events, and does not propagate them to 
 the DbManager, until an explicit commit request is called and the database
 is written to. All events are not valid until a commit is called as a 
 transaction rollback would invalidate the events.
 
 @param aEvent The database event that is being propogated.
*/
void CStateTransaction::HandleDatabaseEventV2L(TContactDbObserverEventV2 aEvent)
	{
	
	DEBUG_PRINT1(__VERBOSE_DEBUG__,_L("[CNTMODEL] Database Event in Transaction"));

    // Do not add a rollback event to the queue. This event will be propagated as 
    // part of the transaction rollback.
    if (aEvent.iType == EContactDbObserverEventRollback)
        {
        return;
        }
    if (iEventQ.Count() <= KMaxNumberOfEventsInEventQueue)
        {
        
        DEBUG_PRINT1(__VERBOSE_DEBUG__,_L("[CNTMODEL] Database Event Added To Q in Transaction"));
    
        iEventQ.AppendL(aEvent);
        } 
    // else - do nothing as a EContactDbObserverEventUnknownChanges will be propagated
    // to all observers    
    }


/** 
 Propagate events back to the CCntDbManager after a commit transaction request
*/
void CStateTransaction::PropagateDatabaseEventsL()
	{
	if (iEventQ.Count() >= KMaxNumberOfEventsInEventQueue)
		{
		
		DEBUG_PRINT1(__VERBOSE_DEBUG__,_L("[CNTMODEL] Max Database Events reached in Transaction - Unknown changes event"));

		// Tell the observer to re-sync with the database as there has been too many
		// operations for which it needs to recieve notification
		TContactDbObserverEventV2 unknownChangeEvent;
		unknownChangeEvent.iType 		 = EContactDbObserverEventUnknownChanges;
		unknownChangeEvent.iContactId 	 = KNullContactId;
		unknownChangeEvent.iConnectionId = KCntNullConnectionId;
		unknownChangeEvent.iTypeV2 = EContactDbObserverEventV2Null;
		unknownChangeEvent.iAdditionalContactIds = NULL;
		
		iStateMachine.DbManager().HandleDatabaseEventV2L(unknownChangeEvent);
		}
	else
		{
		
		DEBUG_PRINT1(__VERBOSE_DEBUG__,_L("[CNTMODEL] Database Events being propagated in Transaction"));
	
		TInt max = iEventQ.Count();
		TInt ii  = 0;
		// Propagate the events from the beginning of the EventQ
		while(ii != max) 
			{
			iStateMachine.DbManager().HandleDatabaseEventV2L(iEventQ[ii]);	
			++ii;	
			}
		}
	iEventQ.Reset(); // Empty the queue	
	}



// CTransactionTimer Implementation //

/** 
 CTransactionTimer Class NewL factory constructor
 Create a transaction timer

 The transaction timer is used to allow a transaction to timeout should
 the session which put the state machine into a transaction state die
 unexpectedly. It is derived from CTimer and times out after sixty seconds.
*/ 
CTransactionTimer* CTransactionTimer::NewL(CStateTransaction& aTransState)
    {
    CTransactionTimer* self = new (ELeave) CTransactionTimer(aTransState);
    CleanupStack::PushL(self);
    self->ConstructL();
    CleanupStack::Pop(self);
    return self;
    }
    
/** 
 CTransactionTimer Class destructor
*/    
CTransactionTimer::~CTransactionTimer()
    {
    CTimer::Cancel();
    }
    
/**
 CTransactionTimer constructor
*/    
CTransactionTimer::CTransactionTimer(CStateTransaction& aTransState) 
                 : CTimer(CActive::EPriorityIdle), iTransState(aTransState)
    {
    }

void CTransactionTimer::ConstructL()
    {
    CTimer::ConstructL();
    CActiveScheduler::Add(this);
    }


/** 
 The Transaction was neither commited nor rolled back 
 The client may have died - clean up the state machine by rolling back
*/ 
void CTransactionTimer::RunL()
    {
    iTransState.CancelTransactionL();
    CTimer::Cancel();
    }

/**
 Start the timer. This is done when a the state machine moves 
 into the transaction state.
*/
void CTransactionTimer::Start()
    { // wait for 60 seconds
    CTimer::Cancel();
    CTimer::After(KSixtySeconds);
    }

/**
 Stop the timer. This is done when a the state machine moves 
 out of the transaction state.
*/
void CTransactionTimer::Stop()
    {
    CTimer::Cancel();
    }

/**
 When a valid operation is performed within the transaction state
 the timer is reset to sixty seconds, if another transaction operation is not
 performed within sixty seconds, the transaction should timeout.
*/
void CTransactionTimer::Reset()
    {
    CTimer::Cancel();
    CTimer::After(KSixtySeconds);
    }
    
// CTransactionLock Class Implementation //
/** 
 CTransactionLock Class NewL factory constructor
 The CTransactionLock class locks contacts allowing only the locking session to
 modify the contact item in the database.
*/
CTransactionLock* CTransactionLock::NewL(CCntStateMachine& aStateMachine)
    {
    CTransactionLock* self = new (ELeave) CTransactionLock(aStateMachine);
    return self;
    }
    
// TLockData constructor    
CTransactionLock::TLockData::TLockData(TContactItemId aCntId, const TUint aSessionId):iCntItemId(aCntId), iSessionId(aSessionId)
    {}
    
// --------- Locking Methods -----------
/** 
 Locks a contact item by adding its ID to an array of locked contact items IDs.
 After a session locks the contact item, no other session can modify the locked contact
 item. 
 Adds the lock to the clean up stack, indicated by the 'X' in the method name
 
 @param aCntId The ID of contact item to be locked
 @param aSessionId The Session which is locking the contact Item
 aContact The contact item to add to the database.
 @return KErrNone if locking was successful.
        KErrInUse if the contact item was locked by another session 
*/

TInt CTransactionLock::LockLX(const TUint aSessionId, const TContactItemId aCntId)
    {
    
    DEBUG_PRINT2(__VERBOSE_DEBUG__,_L("[CNTMODEL] *   Lock item %d"), aCntId);
    
    if (IsLocked(aCntId))
        {
        return KErrInUse; // A session can only lock a cnt item once.    
        }
        
    TLockData lockData(aCntId, aSessionId);
    
    iLockedIds.InsertInSignedKeyOrderL(lockData);
    
    CleanupStack::PushL(TCleanupItem(CTransactionLock::CleanupUnlockRecord, this));
        
    return KErrNone;
    }

    
/**
 Unlocks the last locked contact item after a leave
 
 @param aTransLock The CTransactionLock object from which the last locked contact item
                   ID must be removed (unlocked).
*/
void CTransactionLock::CleanupUnlockRecord(TAny* aTransLock)
    {
    TRAP_IGNORE(static_cast<CTransactionLock*>(aTransLock)->UnlockLastLockedContactL() );
    }
    
/** 
 UnLocks a contact item by removing its ID to an array of locked contact items IDs.
 
 @param aCntId The ID of contact item to be unlocked
 @param aSessionId The Session which is unlocking the contact Item
 @return KErrNone if locking was successful.
          KErrAccessDenied if the contact item was not successfuly locked  
*/    
TInt CTransactionLock::UnLockL(const TUint aSessionId, const TContactItemId aCntId)
    {
    
    DEBUG_PRINT2(__VERBOSE_DEBUG__,_L("[CNTMODEL] * UnLock item %d"), aCntId);
    
    TLockData lockData(aCntId, aSessionId);
    TInt index = iLockedIds.FindInSignedKeyOrder(lockData);
    if (index < 0)
        return KErrAccessDenied;
    
    if (index > iLockedIds.Count())
        {
        return KErrAccessDenied;
        }
    
    if (iLockedIds[index].iSessionId == aSessionId)
        {
        iLockedIds.Remove(index);
        ProcessLockedContactsL(); // Process any requests in the Store
        }
    return KErrNone;
    }

/**
 Process any requests in the Store - Another session
 may have been trying to perform an operation on a  
 locked contact item. This method is called after a contact item
 has been unlocked to allow an operation on the same contact item
 to be performed by another session.
*/
void CTransactionLock::ProcessLockedContactsL()
    {
    if(iStateMachine.ReqStoreL().IsEmpty() == EFalse)
        {
        iStateMachine.ReqStoreL().ActivateRequestsL();
        }
    }

/**
 Unlocks all the locked contacts for a given sessionid, the request 
 that calls this method, CReqInternalSessionUnlock, originates in the session destructor
 
 @param aSessionId The session that is being closed.
*/ 
void CTransactionLock::UnLockAllL(const TUint aSessionId)
    {
    TInt ii = iLockedIds.Count();
    while(ii) 
        {
        --ii;
        if (iLockedIds[ii].iSessionId == aSessionId)
            {
            iLockedIds.Remove(ii);
            }
        }
    ProcessLockedContactsL(); // Process any requests in the Store
    }
    
/** 
 Unlock the last locked contact after an leave has occured    
 
 @param aSessionId The ID of the session that performed the operation in which 
                    the leave occured.
*/
void CTransactionLock::UnlockLastLockedContactL(TUint aSessionId)    
    {
    if (aSessionId == nsState::KNoSessionId)
        {
        // Remove the last Locked Contact regardless of session
        iLockedIds.Remove(iLockedIds.Count() - 1);
        ProcessLockedContactsL(); // Process any requests in the Store
        return;
        }
    
    TInt ii = iLockedIds.Count();
    while(ii) 
        {
        --ii;
        if (iLockedIds[ii].iSessionId == aSessionId)
            {
            iLockedIds.Remove(ii);
            ProcessLockedContactsL(); // Process any requests in the Store
            return; // Finished
            }
        }
    }
    
/** 
Checks if a contact item is locked by another session.

@param aCntId The ID of contact item to be checked
@param aSessionId The Session which is checking for a lock

@return True if the contact has been locked.
        False if the contact has not been locked by another session.
*/
TBool CTransactionLock::IsLocked(const TUint aSessionId, const TContactItemId aCntId) const
    {
    TInt ii = iLockedIds.Count();
    
    while(ii) 
        {
        --ii;
        if (iLockedIds[ii].iCntItemId == aCntId)
            {
            if (iLockedIds[ii].iSessionId != aSessionId)
                {
                return ETrue;    // locked by another session    
                }
            return EFalse; // has not been locked by another session    
            }
        }
    return EFalse; // has not been locked by any session
    }

/**
 Checks if a contact item is locked by this or another session (any session).
 Original behaviour of the contacts model was not to allow a session to lock a contact twice.

 @param aCntId The ID of contact item to be checked
 @return True if the contact has been locked.
        False if the contact has not been locked.
*/
TBool CTransactionLock::IsLocked(const TContactItemId aCntId)const
    {
    TInt ii = iLockedIds.Count();
    
    while(ii) 
        {
        --ii;
        if (iLockedIds[ii].iCntItemId == aCntId)
            {
            return ETrue;    // locked 
            }
        }
    return EFalse;
    }

/**
 Determines if any contacts items are locked by this or another session (any
 session).
 @return True if there is a locked contact.
        False if there is no locked contact.
*/
TBool CTransactionLock::AnyLocked() const
    {
    return iLockedIds.Count() != 0;
    }

/** CStateBackupRestore
    While in this state neither read nor write operations are allowed.  The
    CStateClosed parent class AcceptRequestL() handles all read and write
    requests.
    
    Methods completes the request with KErrLocked via a call to TimeOutErrorCode() 
    from the parent CStateClosed class.
*/
CStateBackupRestore* CStateBackupRestore::NewL(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
    {
    CStateBackupRestore* stateBUR = new (ELeave) CStateBackupRestore(aStateMachine, aPersistenceLayer);
    return stateBUR;
    }
    
    
CStateBackupRestore::~CStateBackupRestore()
    {
    }


CStateBackupRestore::CStateBackupRestore(CCntStateMachine& aStateMachine, CPersistenceLayer& aPersistenceLayer)
:CStateClosed(aStateMachine, aPersistenceLayer)
    {
    }


// Default AsyncOpen requests behaviour to the base implementation
TAccept CStateBackupRestore::AcceptRequestL(CReqAsyncOpen* aRequest)
    {
    return CState::AcceptRequestL(aRequest);
    }


TAccept CStateBackupRestore::AcceptRequestL(CReqBackupRestoreBegin* aRequest)
    {
    // A backup/restore is already in progress so don't defer this request -
    // simply complete it.
    aRequest->Complete();
    return EProcessed;
    }


TAccept CStateBackupRestore::AcceptRequestL(CReqBackupRestoreEnd* aRequest)
    {
    // Once Backup/Restore completes we can re-open the database.  Re-accept
    // request in CStateOpening.    
    iStateMachine.SetCurrentStateL(iStateMachine.StateOpening());  
    return iStateMachine.CurrentState().AcceptRequestL(aRequest);
    }


/**
 If there was asynchronous activity then it has now finished so safe to close
 database.
 
 @param aRequest Notification of end of async activity request object
 @return TAccept EProcessed - finished processing request
*/  
TAccept CStateBackupRestore::AcceptRequestL(CReqNoAsyncActivity* aRequest)
    {
    if (iStateMachine.AsyncActivity())
        {
        iStateMachine.SetAsyncActivity(EFalse);
        // Close the file to allow the backup/restore to take place.    
        iPersistenceLayer.ContactsFileL().Close();
        }
    aRequest->Complete();
    return EProcessed;
    }

/** 
 Returns the default error code - KErrLocked - for the backup restore state 
*/
TInt CStateBackupRestore::TimeOutErrorCode()
    {
    return KErrLocked;
    }


// ======================================        
// CCntStateMachine Class implementation    
// The main purpose of the CState object 
// is to define the state transition table
    
CCntStateMachine::~CCntStateMachine()
    {
    iStateArray.ResetAndDestroy();
    delete iReqStore;
    delete iTransLock;
    }
    
CCntStateMachine* CCntStateMachine::NewL(CPersistenceLayer& aPersistenceLayer, CCntDbManager& aDbManager)
    {
    CCntStateMachine* stateMachine = new (ELeave) CCntStateMachine(aDbManager);
    CleanupStack::PushL(stateMachine);
    stateMachine->ConstructL(aPersistenceLayer);
    CleanupStack::Pop(stateMachine);
    return stateMachine;
    }
    
/** 
 Create and add all states to the state machine array    
 
 @param aPersistenceLayer. The persistence layer that wraps up access to the database.
*/
void CCntStateMachine::ConstructL(CPersistenceLayer& aPersistenceLayer)
    {
    // The order in which states are appended must be in sync with
    // the declaration order of the state enum.
    for (TInt i = 0; i < 6; ++i)
        {
        CState* state;
        switch (i)
            {
            case 0:  state = CStateClosed::NewL(*this, aPersistenceLayer); iState = state; break;
            case 1:  state = CStateTablesClosed::NewL(*this, aPersistenceLayer); break;
            case 2:  state = CStateWritable::NewL(*this, aPersistenceLayer); break;
            case 3:  state = CStateOpening::NewL(*this, aPersistenceLayer); break;
            case 4:  state = CStateTransaction::NewL(*this, aPersistenceLayer); break;
            default: state = CStateBackupRestore::NewL(*this, aPersistenceLayer); 
            }
        CleanupStack::PushL(state);
        iStateArray.AppendL(state); 
        CleanupStack::Pop(state);
        }	
    }

/**
 Get the current active state        
 
 @return The current active state
*/ 
CState& CCntStateMachine::CurrentState()
    {
    return *iState;
    }
    
/** 
 Get the transaction lock    
 
 @return The Transaction Lock object
*/
CTransactionLock& CCntStateMachine::TransactionLockL()
    {
    if (!iTransLock)
        {
        iTransLock = CTransactionLock::NewL(*this);
        }

    return *iTransLock;
    }

/** 
 Get the Database Manager
 
 @return the Contact Database Manager object
*/
CCntDbManager& CCntStateMachine::DbManager()
    {
    return iDbManager;
    }

/**
 StateMachine constructor
 
 @param aDbManager The Database Manager.
*/
CCntStateMachine::CCntStateMachine(CCntDbManager& aDbManager)
    :
    iDbManager(aDbManager),
    iLowDisk(EFalse),
    iAsyncActivity(EFalse)
    {
    // Nothing to do.
    }

/**
 Used for debugging the transition between state. 
 Define __STATE_MACHINE_DEBUG__ in the project definition file (mmp).
 
 @param aState The state which is becoming active
 @return A descriptor containing the active state name.
*/ 
#ifdef __STATE_MACHINE_DEBUG__
const TDesC& CCntStateMachine::StateName(CState& aState)
    {
    _LIT(KStateClosedName,       "EStateClosed");
    _LIT(KStateTablesClosed,     "EStateTablesClosed");
    _LIT(KStateWritableName,     "EStateWritable");
    _LIT(KStateOpeningName,      "EStateOpening");
    _LIT(KStateTransactionName,  "EStateTransaction");
    _LIT(KStateBackupRestoreName, "EStateBackupRestore");
    _LIT(KStateUnknownName,      "Unknown State");

    if (&aState == &StateClosed())
        {
        return KStateClosedName();
        }
        
    if (&aState == &StateTablesClosed())
        {
        return KStateTablesClosed();
        }
        
    if (&aState == &StateWritable())
        {
        return KStateWritableName();
        }

    if (&aState == &StateOpening())
        {
        return KStateOpeningName();
        }

    if (&aState == &StateTransaction())
        {
        return KStateTransactionName();
        }

    if (&aState == &StateBackupRestore())
        {
        return KStateBackupRestoreName();
        }

    return KStateUnknownName();
    }
#endif

/** 
 Set the active state in the state machine    
 
 @param aState The state which is becoming active
*/
void CCntStateMachine::SetCurrentStateL(CState& aState)
    {
    
#ifdef __STATE_MACHINE_DEBUG__
    RDebug::Print(_L("[CNTMODEL] STA: %S --> %S\r\n"),    &CCntStateMachine::StateName(*iState), &CCntStateMachine::StateName(aState));
#endif

    iState = &aState;
    // Process any requests in the Store on each state change
    // The state may have changed to one where queued requests 
    // can now be processed.
    if(ReqStoreL().IsEmpty() == EFalse)
        {
        iReqStore->ActivateRequestsL();
        }
    }

/** 
 This is the interface to the state machine (used by the session class). 
 The state machine is asked to process a request by the session. It does this
 by passing the  current active state to the request object (VisitStateL). 
 The request then calls AcceptRequest on the current active state object. The
 state and the request are completely decoupled.
 
 Caller of ProcessRequestL should assume transfer request ownership unless 
 ProcessRequestL leaves.  In the event ProcessRequestL leaves, the original owner
 of the request is responsible for the cleanup of the request.  
 
 Note that if the request is to be transferred to another object, ensure once the 
 transfer has taken place, no leave should occur, as this will trigger both the new 
 owner and the original owner to cleanup the request.
 
 @param aRequest A request that is being processed.
*/ 
void CCntStateMachine::ProcessRequestL(CCntRequest* aRequest)
    {
    // Obtained ownership of the request object.  It is the responsibility
    // of this function to ensure the request is properly disposed after being 
    // processed unless leave occurs.
    TAccept result = aRequest->VisitStateL(*iState);

    switch(result)
        {
        case EDeferred:
            // The visited state cannot process the request at the moment.  Activate the 
            // request's timer and transfer ownership of the request to the request store.  
            // Hopefully, a state change happens before timeout occurs, when the new state 
            // will attempt to process all deferred request.  If timeout occurs before 
            // a change of state, the request will be completed with its' timeout error code.  
            // This timeout error code can be set thru the CCntRequest API SetTimeOutError.
            aRequest->ActivateTimeOutL(ReqStoreL());
            ReqStoreL().AppendL(aRequest);  // ownership transferred
            break;

        case EProcessed:
            // The request has been processed by the visited state - nothing more
            // to do, except to destroy the request now
            delete aRequest;
            break;

        case EOwnershipPassed:
            // the request has been hi-jacked by the visited state, the new owner will
            // assume responsibility of cleanup, no need to do anything here.
        default:
            break;
        }
    }


/**
 Allow the active state to process the event. The only state that actually
 processes events is the Transaction State. All other states (via the base state CState) 
 simply propagate the event back to the CCntDbManager, from where it is propogated to
 each CCntSession contained within the CCntDbManager.
 
 @param aEvent The database event that is being propagated.
*/ 
void CCntStateMachine::HandleDatabaseEventV2L(TContactDbObserverEventV2 aEvent)
	{
	#if defined(__PROFILE_DEBUG__)
		RDebug::Print(_L("[CNTMODEL] MTD: CCntStateMachine::HandleDatabaseEventV2L"));
	#endif 
	
	iState->HandleDatabaseEventV2L(aEvent);
	}

/** 
 Create the state machines request store. When a request cannot be processed in
 the active state, it is deferred until the active state changes or a contact item is unlocked.
 That is the request in this ReqStore is processed by the state machine - again - after either 
 a state change or unlock operation. 
 The store takes a reference to the CCntStateMachine in order to ProcessRequestL
 
 @return The Request Store      
*/ 
CRequestStore& CCntStateMachine::ReqStoreL()
    {
    if (!iReqStore)
        {
        iReqStore = CRequestStore::NewL(*this);
        }
    return *iReqStore;
    }