summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/contactsmodel/tsrc/t_cnt_backup.cpp
blob: 0ba8c340fec90ff077137cd2dd28ed1ed95c962c (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
/*
* Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
* Contact: http://www.qt-project.org/legal
* 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: 
*
*/


#include <e32test.h>
#include <f32file.h>
#include <s32file.h>
#include <cntdb.h>
#include <cntitem.h>
#include <cntfield.h>
#include <cntfldst.h>
#include <coreappstest/testserver.h>

#include <connect/sbeclient.h>

#include "t_utils.h"
#include "t_utils2.h"
#include "t_cnt_backup.h"


// cleanup version of test macro
LOCAL_C void TestCondition(TBool aCondition, TInt aLineNumber);
#define TEST_CONDITION(x) TestCondition(x, __LINE__)


// test databases to create, for use by Contacts test clients
_LIT(KBackupDatabaseFile1,"c:BackupTest1.cdb");
_LIT(KBackupDatabaseFile2,"c:BackupTest2.cdb");
_LIT(KBackupDatabaseFile3,"c:BackupTest3.cdb"); 


// real location of Contacts db files
#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
_LIT(KBackupDatabaseFileFullPath1,"c:\\private\\10003A73\\BackupTest1.cdb");
_LIT(KBackupDatabaseFileFullPath2,"c:\\private\\10003A73\\BackupTest2.cdb");
_LIT(KBackupDatabaseFileFullPath3,"c:\\private\\10003A73\\BackupTest3.cdb"); 
_LIT(KBackupDestinationDatabasePath1,"c:\\t_cnt_backup\\BackupTest1.cdb");
_LIT(KBackupDestinationDatabasePath2,"c:\\t_cnt_backup\\BackupTest2.cdb");
_LIT(KBackupDestinationDatabasePath3,"c:\\t_cnt_backup\\BackupTest3.cdb"); 
_LIT(KContactsBackupRegistrationDefaultDbFileFullPath, "c:\\private\\10003A73\\backup_registrationcontacts_cdb.xml");
#else
_LIT(KBackupDatabaseFileFullPath1,"c:\\private\\10003A73\\SQLite__BackupTest1.cdb");
_LIT(KBackupDatabaseFileFullPath2,"c:\\private\\10003A73\\SQLite__BackupTest2.cdb");
_LIT(KBackupDatabaseFileFullPath3,"c:\\private\\10003A73\\SQLite__BackupTest3.cdb"); 
_LIT(KBackupDestinationDatabasePath1,"c:\\t_cnt_backup\\SQLite__BackupTest1.cdb");
_LIT(KBackupDestinationDatabasePath2,"c:\\t_cnt_backup\\SQLite__BackupTest2.cdb");
_LIT(KBackupDestinationDatabasePath3,"c:\\t_cnt_backup\\SQLite__BackupTest3.cdb"); 
_LIT(KContactsBackupRegistrationDefaultDbFileFullPath, "c:\\private\\10003A73\\backup_registrationSQLite__contacts_cdb.xml");
#endif


// Contact model backup files
_LIT(KContactsBackupRegistrationIniFileFullPath, "c:\\private\\10003A73\\backup_registration.xml");
_LIT(KContactsIniBackupFileFullPath, "c:\\private\\10003A73\\Cntmodel.ini");
_LIT(KBackupDestinationDirectory, "c:\\t_cnt_backup\\");
_LIT(KBackupDestinationContactsIniPath,"c:\\t_cnt_backup\\Cntmodel.ini");
_LIT(KRestoreDamagedDatabasePath,"z:\\t_cnt_backup_Corrupted_100065FF.cdb");

// delays between Backup/Restoretest steps, to allow notifications to propagate to all components
static const TInt KWaitForBackupNotification(15000000);
static const TInt KWaitForClientToSettle(2000000);
static const TInt KWaitForSystemToSettle(20000000);


// Test databases have 10 contacts created, various contact Ids are used for different purposes
static const TInt KNumContactsInDatabase= 10;
static const TContactItemId KOpenContactId1 = 1;
static const TContactItemId KOpenContactId2 = 2;
static const TContactItemId KOpenContactId3 = 3;
static const TContactItemId KSpeedDialContactId = 4;
static const TContactItemId KReadContactId = 5;
static const TInt KSpeedDialPositionOne = 1;


_LIT(KAsyncFindMatch,"a");


// global data for unit test
_LIT(KTestName, "t_cnt_backup");
static RTest test(KTestName);
static RFs TheFsSession;


/*
 Class CBackupTestConductor drives the whole set of tests
 1. Check the Backup Registration file is present
 2. Check the Secure Backup Engine has processed it as we expect
 3. ... various Backup / Restore scenarios for contacts clients
 */

CBackupTestConductor* CBackupTestConductor::NewL()
	{
	CBackupTestConductor* self = new (ELeave) CBackupTestConductor();
	CleanupStack::PushL(self);
	self->ConstructL();
	CleanupStack::Pop(self);
	return self;
	}

CBackupTestConductor::~CBackupTestConductor()
	{
	// ensure test databases are deleted
	CBackupTestConductor::DeleteDatabases();

	// cleanup backup files
	TheFsSession.Delete(KBackupDestinationContactsIniPath);
	TheFsSession.Delete(KBackupDestinationDatabasePath1);
	TheFsSession.Delete(KBackupDestinationDatabasePath2);
	TheFsSession.Delete(KBackupDestinationDatabasePath3);
	TheFsSession.RmDir(KBackupDestinationDirectory);
	}


CBackupTestConductor::CBackupTestConductor()
	{
	}


void CBackupTestConductor::ConstructL()
	{
	const TInt err = TheFsSession.MkDirAll(KBackupDestinationDirectory);
	if ((err != KErrNone) && (err != KErrAlreadyExists))
		{
		test.Printf(_L("Unable to create the directory %S\n"), &KBackupDestinationDirectory);
		User::Leave(err);
		}
	}


void CBackupTestConductor::RunTestsL()
	{
	// need databases for B&R testing
	CreateDatabasesL();
	// 1.x Check Backup Registration files
	test.Start(_L("Backup registration files exist"));
	TEST_CONDITION(CheckXMLBackupRegistrationExistsL());
	test.End();

	
	// framework that runs a Backup & Restore test cycle
	CBackupTestFramework* backupFramework = CBackupTestFramework::NewLC();
	CleanupStack::Check(backupFramework);

	// 2. ... run all Backup / Restore test situations
	backupFramework->DoBackupRestoreTestsL();

	// delete framework
	CleanupStack::PopAndDestroy(backupFramework);
	}


// demonstrates that database is populated correctly
#ifdef _DEBUG
void CBackupTestConductor::ShowFieldsL(CContactDatabase* aDb)
#else
void CBackupTestConductor::ShowFieldsL(CContactDatabase* /*aDb*/)
#endif
	{
#if _DEBUG
	CContactItem* contact = aDb->ReadContactLC(iFirstContactId);
	
	CContactItemFieldSet& fields = contact->CardFields();
	const TInt fieldCount = fields.Count();

	for (TInt i = 0; i < fieldCount; i++)
		{
		CContactItemField &field = fields[i];
		if (field.StorageType() == KStorageTypeText)
			{
			TPtrC fieldText = field.TextStorage()->Text();
			TPtrC labelText = field.Label();
		    test.Printf(_L("--Field(%d) %S: %S \n\r"), i, &labelText, &fieldText);
			}
		}
	CleanupStack::PopAndDestroy(contact);	
#endif
	}


/*
 Populate the database - add TEN contacts, based on the default template,
 setting FOUR fields. (Given name, Family name, phone number + Company name.)
 Set the Company Name field to be the same as the name of the database.
 
 @param aDb the CContactDatabase instance to add contacts to.
 @param aFileName Database file name to put in the Company name field
 */
void CBackupTestConductor::PopulateDatabaseL(CContactDatabase* aDb,const TDesC& aFileName)
	{
	test.Printf(_L("Populating database %S\n"), &aFileName);
	TInt index = 0;
	TBool allDone = EFalse;

	const TContactItemId templateId = aDb->TemplateId();
	CContactItem* templateCard = aDb->ReadContactLC(templateId);

	do
	{
		CContactCard* card = CContactCard::NewLC(templateCard);

		CContactItemFieldSet& cardFields = card->CardFields();

		TInt posLastName = cardFields.Find(KUidContactFieldGivenName);
		TInt posFirstName = cardFields.Find(KUidContactFieldFamilyName);


		switch (index)
			{ // (famous writers on computer topics)
			case 0:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Kernighan"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Brian"));
				break;

			case 1:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Ritchie"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Dennis"));
				break;

			case 2:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Thompson"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Ken"));
				break;

			case 3:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Aho"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Alfred"));
				break;

			case 4:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Weinberger"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Peter J."));
				break;

			case 5:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Bourne"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Steven"));
				break;

			case 6:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Pike"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Rob"));
				break;

			case 7:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Bellovin"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Steven"));
				break;

			case 8:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Stevens"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("W. Richard"));
				break;

			case 9:
				cardFields[posLastName].TextStorage()->SetTextL(_L("Raymond"));
				cardFields[posFirstName].TextStorage()->SetTextL(_L("Eric"));
				// last contact
				allDone = ETrue;
				break;
			}


		// Set the telephone number
		TInt posNumber = cardFields.Find(KUidContactFieldPhoneNumber);
		if (posNumber != KErrNotFound)
			{
			cardFields[posNumber].SetMapping(KUidContactFieldVCardMapTEL);
			cardFields[posNumber].TextStorage()->SetTextL(_L("1234"));
			}


		// set database file name as company name
		TInt posCompanyName = cardFields.Find(KUidContactFieldCompanyName);
		if (posCompanyName != KErrNotFound)
			{
			cardFields[posCompanyName].TextStorage()->SetTextL(aFileName);
			}


		iLastContactId = aDb->AddNewContactL(*card);
		if (index == 0)
			{
			iFirstContactId = iLastContactId;
			}

		CleanupStack::PopAndDestroy(card);
		++index;
		
		test.Printf(_L("."));
		}
		while (!allDone);

	CleanupStack::PopAndDestroy(templateCard);

	ShowFieldsL(aDb);
	}

// create THREE empty contacts databases then populate each
void CBackupTestConductor::CreateDatabasesL()
	{
	// Create & close databases
	CContactDatabase* db;
	// Need to create the default data base if it does not exist to enusre
	// prescence of backup registration file.
	if (!CContactDatabase::DefaultContactDatabaseExistsL())
		{
		db = CContactDatabase::CreateL();
		delete db;		
		}
		
	test.Printf(_L("Creating database %S\n"), &KBackupDatabaseFile1);
	db = CContactDatabase::ReplaceL(KBackupDatabaseFile1);
	PopulateDatabaseL(db, KBackupDatabaseFile1);
	delete db;
	
	test.Printf(_L("Creating database %S\n"), &KBackupDatabaseFile2);
	db = CContactDatabase::ReplaceL(KBackupDatabaseFile2);
	PopulateDatabaseL(db, KBackupDatabaseFile2);
	delete db;
	
	test.Printf(_L("Creating database %S\n"), &KBackupDatabaseFile3);
	db = CContactDatabase::ReplaceL(KBackupDatabaseFile3);
	PopulateDatabaseL(db, KBackupDatabaseFile3);
	delete db;
	}


void CBackupTestConductor::DeleteDatabases()
	{
	// Delete databases
	TRAP_IGNORE(CContactDatabase::DeleteDatabaseL(KBackupDatabaseFile1));
	TRAP_IGNORE(CContactDatabase::DeleteDatabaseL(KBackupDatabaseFile2));
	TRAP_IGNORE(CContactDatabase::DeleteDatabaseL(KBackupDatabaseFile3));
	}


/*
 Check that the Contact Model's Backup Registration files are present and > 0 bytes length
 */
TBool CBackupTestConductor::CheckXMLBackupRegistrationExistsL()
	{
	// Check the Contacts private area for the expected registration files
	TEntry entry;

	// See if initialisation registration file is in the directory on drive Z:
	TInt error = TheFsSession.Entry(KContactsBackupRegistrationIniFileFullPath, entry);

	if (error == KErrNotFound)
		{
		return EFalse;
		}
		
	User::LeaveIfError(error);

	if(entry.iSize == 0)
		{
		// file is present but is empty
		User::Leave(KErrCorrupt);
		}

	// See if default database registration file is in the directory on drive Z:
	error = TheFsSession.Entry(KContactsBackupRegistrationDefaultDbFileFullPath, entry);

	if (error == KErrNotFound)
		{
		return EFalse;
		}
		
	User::LeaveIfError(error);

	if(entry.iSize == 0)
		{
		// file is present but is empty
		User::Leave(KErrCorrupt);
		}

	// Found the registration files
	return ETrue;
	}
			

///////////////////////////////////////////////////////////////////////////////////////

/*
 Framework for simulating Contact Model clients
 
 @param aDatabaseName database file name to open
 @param aObserver Observer in Backup / Restore test framework to count Backup and Restore notifications
 @param aContactViewObserver Observer in Backup / Restore test framework to count View Ready and Unavailable notifications
 */
CContactsClient* CContactsClient::NewLC(const TDesC& aDatabaseName, MBackupRestoreObserver* aObserver, MContactViewObserver& aContactViewObserver, TBool aCloseForBackup)
	{
	CContactsClient* self = new (ELeave) CContactsClient(aObserver, aContactViewObserver, aCloseForBackup);
	CleanupStack::PushL(self);
	self->ConstructL(aDatabaseName);
	return self;
	}
	
	
CContactsClient::CContactsClient(MBackupRestoreObserver* aObserver, MContactViewObserver& aContactViewObserver, TBool aCloseForBackup)
	: CActive(EPriorityStandard), iObserver(aObserver), iContactViewObserver(aContactViewObserver), iDatabaseIsOpen(EFalse), iCloseForBackup(aCloseForBackup), iOpenContacts(4)
	{
	CActiveScheduler::Add(this);
	}

CContactsClient::~CContactsClient()
	{
	Cancel();
	CloseViews();
	CloseDatabase();
	iOpenContacts.ResetAndDestroy();

	delete iDbName;
	}


void CContactsClient::StartActiveClose()
	{
	// start active object to close contact/view/database
	// required as these can't be closed directly from the event handlers
	if (!IsActive() && iDatabaseIsOpen)
		{
		TRequestStatus* pS = &iStatus;
		User::RequestComplete(pS,0);
		SetActive();
		}
	}
	
void CContactsClient::DoCancel()
	{
	}
	

void CContactsClient::RunL()
	{
	if (iStatus.Int() != KErrCancel)
		{
		CloseDatabase();
		}
	}
	
void CContactsClient::CloseDatabase()
	{
	CloseContacts();
	CloseViews();
	iDatabaseIsOpen = EFalse;

	if (iIdleFinder)
		{
		delete iIdleFinder;
		iIdleFinder = NULL;
		}

	if (iItemFieldDef)
		{
		delete iItemFieldDef;
		iItemFieldDef = NULL;
		}

	if (iActiveCompress)
		{
		delete iActiveCompress;
		iActiveCompress = NULL;
		}

	if (iActiveRecover)
		{
		delete iActiveRecover;
		iActiveRecover = NULL;
		}

	delete iNotifier;
	iNotifier = NULL;
	delete iDb;
	iDb = NULL;
	}


void CContactsClient::ConstructL(const TDesC& aDatabaseName)
	{
	// remember the database name
	iDbName = aDatabaseName.AllocL();
	// open it
	OpenDatabaseL();
	}


void CContactsClient::OpenDatabaseL()
	{
	// can only open once
	if (iDatabaseIsOpen)
		{
		User::Leave(KErrInUse);
		}

	test.Printf(_L("Open database %S\n"), iDbName);
	iDb = CContactDatabase::OpenL(iDbName->Des());
	iDatabaseIsOpen = ETrue;
	iNotifier = CContactChangeNotifier::NewL(*iDb,this);
	}


const TDesC& CContactsClient::DatabaseName()
	{
	return *iDbName;
	}


TBool CContactsClient::IsOpen()
	{
	return iDatabaseIsOpen;
	}

TBool CContactsClient::IsCloseForBackup()
	{
	return iCloseForBackup;
	}	

void CContactsClient::OpenRemoteViewL()
	{
	if (iRemoteView != NULL)
		{
		User::Leave(KErrInUse);
		}
		
	RContactViewSortOrder viewSortOrder;
	
	viewSortOrder.AppendL(KUidContactFieldFamilyName);
	viewSortOrder.AppendL(KUidContactFieldGivenName);
	viewSortOrder.AppendL(KUidContactFieldCompanyName);

	iRemoteView = CContactRemoteView::NewL(iContactViewObserver, *iDb, viewSortOrder, EContactsOnly);

	viewSortOrder.Close();
	}


void CContactsClient::OpenLocalViewL()
	{
	if (iLocalView != NULL)
		{
		User::Leave(KErrInUse);
		}
		
	RContactViewSortOrder viewSortOrder;
	
	viewSortOrder.AppendL(KUidContactFieldFamilyName);
	viewSortOrder.AppendL(KUidContactFieldGivenName);
	viewSortOrder.AppendL(KUidContactFieldCompanyName);

	iLocalView = CContactLocalView::NewL(iContactViewObserver, *iDb, viewSortOrder, EContactsOnly);

	viewSortOrder.Close();
	}


void CContactsClient::CloseViews()
	{
	if (iLocalView)
		{
		iLocalView->Close(iContactViewObserver);
		iLocalView = NULL;
		}

	if (iRemoteView)
		{
		iRemoteView->Close(iContactViewObserver);
		iRemoteView = NULL;
		}
	}


void CContactsClient::FindPhoneNumberL()
	{
	_LIT(KPhoneNumber, "1234");
	const TInt KNumMatchDigit = 4;
	CContactIdArray* array = iDb->MatchPhoneNumberL(KPhoneNumber, KNumMatchDigit);
	CleanupStack::PushL(array);
	TEST_CONDITION(array->Count() == 10);
	CleanupStack::PopAndDestroy(array);
	}


// try to open a contact for edit
void CContactsClient::OpenContactL(TContactItemId aContactId)
	{
	CContactItem* contact = iDb->OpenContactL(aContactId);
	iOpenContacts.AppendL(contact);
	}


// try to commit an open contact
void CContactsClient::CommitContactL(TContactItemId aContactId)
	{
	const TInt numOpenContacts = iOpenContacts.Count();
	
	for (TInt j = 0; j < numOpenContacts; ++j)
		{
		CContactItem* tempContact = iOpenContacts[j];
		if (tempContact->Id() == aContactId)
			{
			iDb->CommitContactL(*tempContact);
			iOpenContacts.Remove(j);
			delete tempContact;
			return;
			}
		}
	// contact isn't in open list
	TEST_CONDITION(EFalse);
	}


// close any open contacts
void CContactsClient::CloseContacts()
	{
	while (iOpenContacts.Count())
		{
		CContactItem* tempContact = iOpenContacts[0];
		TRAP_IGNORE(iDb->CloseContactL(tempContact->Id()));
		iOpenContacts.Remove(0);
		delete tempContact;
		}
	}

// try to Read the template Contact from database
// and also, check that one record exists with the Company Name field set 
// to the clients database name 
void CContactsClient::ReadContactL()
	{
	CContactItem* contact = iDb->ReadContactLC(KReadContactId);
	CleanupStack::PopAndDestroy(contact);

	// find records with the Company Name field set
	CContactItemFieldDef* fieldDef = new(ELeave) CContactItemFieldDef;
	CleanupStack::PushL(fieldDef);
	TFieldType fieldtype = KUidContactFieldCompanyName;
	fieldDef->AppendL(fieldtype);
	CContactIdArray* matchList = iDb->FindLC(iDbName->Des(),fieldDef);
  
	// all added contacts should have this field initialised
	TInt matchCount = matchList->Count();
    TEST_CONDITION(matchCount == KNumContactsInDatabase);	

    CleanupStack::PopAndDestroy(2, fieldDef);
	}


void CContactsClient::HandleDatabaseEventL(TContactDbObserverEvent aEvent)
	{
	/** Contacts DB about to be backed up  */
	if (aEvent.iType == EContactDbObserverEventBackupBeginning)
		{
		iRestore = EFalse;
		iObserver->ContactsBackupRestoreObserver(*this, iRestore, ETrue);
		}
	/** Contacts DB about to be restored */
	else if (aEvent.iType == EContactDbObserverEventRestoreBeginning)
		{
		iRestore = ETrue;
		iObserver->ContactsBackupRestoreObserver(*this, iRestore, ETrue);
		}
	/** The backup/restore operation has completed. */
	else if (aEvent.iType == EContactDbObserverEventBackupRestoreCompleted)
		{
		iObserver->ContactsBackupRestoreObserver(*this, iRestore, EFalse);
		}
	/** The restore operation has completed but the database could not be opened. */
	else if (aEvent.iType == EContactDbObserverEventRestoreBadDatabase)
		{
		iObserver->ContactsBackupRestoreObserver(*this, iRestore, EFalse);
		}
	}


void CContactsClient::StartAsyncFindL()
	{
	if (!iItemFieldDef)
		{
		iItemFieldDef = new(ELeave) CContactItemFieldDef();
		iItemFieldDef->AppendL(KUidContactFieldGivenName);
		iItemFieldDef->AppendL(KUidContactFieldFamilyName);
		iItemFieldDef->AppendL(KUidContactFieldCompanyName);
		iItemFieldDef->AppendL(KUidContactFieldPhoneNumber);
		iItemFieldDef->AppendL(KUidContactFieldFax);
		iItemFieldDef->AppendL(KUidContactFieldEMail);
		iItemFieldDef->AppendL(KUidContactFieldUrl);
		iItemFieldDef->AppendL(KUidContactFieldAddress);
		iItemFieldDef->AppendL(KUidContactFieldLocality);
		iItemFieldDef->AppendL(KUidContactFieldRegion);
		iItemFieldDef->AppendL(KUidContactFieldPostcode);
		iItemFieldDef->AppendL(KUidContactFieldCountry);
		iItemFieldDef->AppendL(KUidContactFieldNote);
		}

	iIdleFinder = iDb->FindAsyncL(KAsyncFindMatch, iItemFieldDef, this);
	}


void CContactsClient::StartActiveCompactL()
	{
#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
	if (! iActiveCompress)
		{
		iActiveCompress = iDb->CreateCompressorLC();
		CleanupStack::Pop();
		}
	iActiveCompress->SetObserver(this);
#endif
	}


void CContactsClient::StartActiveRecoverL()
	{
#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
	if (! iActiveRecover)
		{
		iActiveRecover = iDb->CreateRecoverLC();
		CleanupStack::Pop();
		}
	iActiveRecover->SetObserver(this);
#endif
	}


void CContactsClient::StartIdleSorterL(TRequestStatus& aStatus)
	{
	CArrayFix<CContactDatabase::TSortPref>* sortOrder = new(ELeave) CArrayFixFlat<CContactDatabase::TSortPref>(3);
	CleanupStack::PushL(sortOrder);

	// prepare a sort order
	sortOrder->AppendL(CContactDatabase::TSortPref(KUidContactFieldGivenName));
	sortOrder->AppendL(CContactDatabase::TSortPref(KUidContactFieldFamilyName));
	sortOrder->AppendL(CContactDatabase::TSortPref(KUidContactFieldCompanyName));

	// starts Contacts Model Idle Sorter
	iDb->SortAsyncL(sortOrder, aStatus);


	// sortOrder ownership was passed to the Contact Model
	CleanupStack::Pop(sortOrder);
	}


void CContactsClient::CompleteAsyncFindL()
	{
	// nothing to do Async Find completes in its own time
	}


void CContactsClient::CompleteActiveCompactL()
	{
#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
	TInt step;
	while(iActiveCompress->Step())
		{
		step = iActiveCompress->StepsTogo();
		TEST_CONDITION(step > 0);
		}
	step = iActiveCompress->StepsTogo();
	TEST_CONDITION(step == 0);
	delete iActiveCompress;
	iActiveCompress = NULL;
#endif
	}


void CContactsClient::CompleteActiveRecoverL()
	{
#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
	TInt step;
	while(iActiveRecover->Step())
		{
		step = iActiveRecover->StepsTogo();
		TEST_CONDITION(step > 0);
		}
	step = iActiveRecover->StepsTogo();
	TEST_CONDITION(step == 0);
	delete iActiveRecover;
	iActiveRecover = NULL;
#endif
	}


// class MContactUiCompactObserver
void CContactsClient::Step(TInt /*aStep*/)
	{
	}


void CContactsClient::HandleError(TInt /*aError*/)
	{
	}


// class MIdleFindObserver
void CContactsClient::IdleFindCallback()
	{
	}


// Speed Dial Check, Remove and Set - for testing cntmodel.ini is Backed up and Restored correctly
void CContactsClient::CheckSpeedDialSetL(TContactItemId aContactId, TInt aSpeedDialPosition)
	{
	HBufC* buf = HBufC::NewLC(100);	
	TPtr fieldContents = buf->Des();
	
	TContactItemId id = iDb->GetSpeedDialFieldL(aSpeedDialPosition, fieldContents);
	CleanupStack::PopAndDestroy(buf);

	TEST_CONDITION(id == aContactId);
	}


void CContactsClient::RemoveSpeedDialL(TContactItemId aContactId, TInt aSpeedDialPosition)
	{
	iDb->RemoveSpeedDialFieldL(aContactId, aSpeedDialPosition);
	}


void CContactsClient::SetSpeedDialL(TContactItemId aContactId, TInt aSpeedDialPosition)
	{
	CContactItem* speedDialItem = iDb->OpenContactLX(aContactId);
	CleanupStack::PushL(speedDialItem);
	CContactItemFieldSet& cardFields = speedDialItem->CardFields();

	TInt posNumber = cardFields.Find(KUidContactFieldPhoneNumber);

	iDb->SetFieldAsSpeedDialL(*speedDialItem, posNumber, aSpeedDialPosition);
	CleanupStack::PopAndDestroy(speedDialItem);
	CleanupStack::Pop(); // Lock Record
	}


//
// Backup and Restore Test Framework class
//

CBackupHelper* CBackupHelper::NewL(RPIMTestServer& aTestServer)
	{
    CBackupHelper* self = new(ELeave) CBackupHelper(aTestServer);
	CleanupStack::PushL(self);
	self->ConstructL();
	CleanupStack::Pop(self);
	return self;
	}
	
	
CBackupHelper::CBackupHelper(RPIMTestServer& aTestServer) : 
    iTestServ (aTestServer)
	{
	}
	
	
void CBackupHelper::ConstructL()
	{
	/* Initialise the drive list to empty and then get drive list data from
	 File Server.
	 Required before Backup and Restore testing
	 */
	iDriveList.FillZ();
	User::LeaveIfError(TheFsSession.DriveList(iDriveList));

	iBackupClient = conn::CSBEClient::NewL();
	}


CBackupHelper::~CBackupHelper()
	{
	delete iBackupClient;
	}
	
	
void CBackupHelper::StartBackupL(conn::TBURPartType aBURPartType, conn::TBackupIncType aBackupIncType)
	{
	/* Use the Secure Backup Engine API to "start" a backup.  Ultimate effect
	 is to cause CContactsClient::HandleDatabaseEventL() to be called.
	 This happens indirectly through CLockSrvServer::BackupBeginningL()/
	 BackupCompletedL()/RestoreBeginningL()/RestoreCompletedL() methods.
	 These methods are implementations for MBackupRestoreNotificatioObserver
	 which monitors changes in the P&S property conn::KUidBackupRestoreKey.
	 This P&S property is changed by calling the Secure Backup Engine API
	 below.
	 */	
	iBackupClient->SetBURModeL(iDriveList, aBURPartType, aBackupIncType);
	}


void CBackupHelper::EndBackupL()
	{
	/* Use the Secure Backup Engine API to "end" a backup.  Ultimate effect
	 is to cause CContactsClient::HandleDatabaseEventL() to be called.
	 This happens indirectly through CLockSrvServer::BackupBeginningL()/
	 BackupCompletedL()/RestoreBeginningL()/RestoreCompletedL() methods.
	 These methods are implementations for MBackupRestoreNotificatioObserver
	 which monitors changes in the P&S property conn::KUidBackupRestoreKey.
	 This P&S property is changed by calling the Secure Backup Engine API
	 below.
	 */
	iBackupClient->SetBURModeL(iDriveList, conn::EBURNormal, conn::ENoBackup);
	}


void CBackupHelper::StartRestoreL()
	{
	/* Use the Secure Backup Engine API to "start" a restore.  Ultimate effect
	 is to cause CContactsClient::HandleDatabaseEventL() to be called.
	 This happens indirectly through CLockSrvServer::BackupBeginningL()/
	 BackupCompletedL()/RestoreBeginningL()/RestoreCompletedL() methods.
	 These methods are implementations for MBackupRestoreNotificatioObserver
	 which monitors changes in the P&S property conn::KUidBackupRestoreKey.
	 This P&S property is changed by calling the Secure Backup Engine API
	 below.
	 */
	iBackupClient->SetBURModeL(iDriveList, conn::EBURRestoreFull, conn::EBackupBase);
	}


void CBackupHelper::EndRestoreL()
	{
	/* Use the Secure Backup Engine API to "end" a restore.  Ultimate effect
	 is to cause CContactsClient::HandleDatabaseEventL() to be called.
	 This happens indirectly through CLockSrvServer::BackupBeginningL()/
	 BackupCompletedL()/RestoreBeginningL()/RestoreCompletedL() methods.
	 These methods are implementations for MBackupRestoreNotificatioObserver
	 which monitors changes in the P&S property conn::KUidBackupRestoreKey.
	 This P&S property is changed by calling the Secure Backup Engine API
	 below.
	 */
	iBackupClient->SetBURModeL(iDriveList, conn::EBURNormal, conn::ENoBackup);
	}




//
// Simulate Backup of .ini file. Indicating if the operation was a success.
//
TBool CBackupHelper::SimulateIniBackup()
	{
    // Backup CntModel.ini file.
    TRAPD(error, iTestServ.CopyFileL(KContactsIniBackupFileFullPath,
        KBackupDestinationContactsIniPath))
	
	if (error != KErrNone)
		{
		test.Printf(_L("Copy failed with error %i"), error);
		return EFalse;
		}
	return ETrue;
	}


//
// Simulate Backup of database(s). Indicating if the operation was a success.
//
TBool CBackupHelper::SimulateDbBackup()
	{
    // backup databases
    TRAPD(error, iTestServ.CopyFileL(KBackupDatabaseFileFullPath1, KBackupDestinationDatabasePath1))

	if (error == KErrNone)
		{
        TRAP(error, iTestServ.CopyFileL(KBackupDatabaseFileFullPath2, KBackupDestinationDatabasePath2))
		}

	if (error == KErrNone)
		{
        TRAP(error, iTestServ.CopyFileL(KBackupDatabaseFileFullPath3, KBackupDestinationDatabasePath3))
		}

	if (error != KErrNone)
		{
		test.Printf(_L("Copy failed with error %i"), error);
		return EFalse;
		}

	return ETrue;
	}


//
// Simulate restore of .ini file. Indicating if the operation was a success.
//
TBool CBackupHelper::SimulateIniRestore()
	{
	// Restore CntModel.ini file.
    TRAPD(error, iTestServ.CopyFileL(KBackupDestinationContactsIniPath, KContactsIniBackupFileFullPath))

	if (error != KErrNone)
		{
		test.Printf(_L("Copy failed with error %i"), error);
		return EFalse;
		}
	return ETrue;
	}


//
// Simulate restore of database(s). Indicating if the operation was a success.
//
TBool CBackupHelper::SimulateDbRestore()
	{
	// restore databases
    TRAPD(error, iTestServ.CopyFileL(KBackupDestinationDatabasePath1, KBackupDatabaseFileFullPath1))

    if (error == KErrNone)
		{
        TRAP(error, iTestServ.CopyFileL(KBackupDestinationDatabasePath2, KBackupDatabaseFileFullPath2))
		}

	if (error == KErrNone)
		{
        TRAP(error, iTestServ.CopyFileL(KBackupDestinationDatabasePath3, KBackupDatabaseFileFullPath3))
		}

	if (error != KErrNone)
		{
		test.Printf(_L("Copy failed with error %i"), error);
		return EFalse;
		}

	return ETrue;
	}

//
// Simulate restoring a corrupted database.
//
TBool CBackupHelper::SimulateDamagedDbRestore()
    {
    // Restore first one from a damaged and the rest from a good copy.		
    TRAPD(error, iTestServ.CopyFileL(KRestoreDamagedDatabasePath, KBackupDatabaseFileFullPath1))	

    if (error == KErrNone)
        {
        TRAP(error, iTestServ.CopyFileL(KBackupDestinationDatabasePath2, KBackupDatabaseFileFullPath2))
        }

    if (error == KErrNone)
        {
        TRAP(error, iTestServ.CopyFileL(KBackupDestinationDatabasePath3, KBackupDatabaseFileFullPath3))
        }
	
    if (error != KErrNone)
        {
        test.Printf(_L("Copy failed with error %i"), error);
        return EFalse;
        }

    return ETrue;
    }

//
// Backup and Restore Test Framework class
//
static const CBackupTestFramework::TBackupRestoreTestCase BackupTestCases[] =
	{
		/* iTestTitle, iNumDatabases, iClientsPerDatabase, iActivity, iCloseForBackup, iExpectedBackupSuccess */

		/*
		 Test client activities that DO NOT BLOCK Backup / Restore
		 Backup and Restore should always succeed, tests are in pairs:
		 1. does not respond to Backup
		 2. closes all resources when Backup or Restore begin
		*/

		// Single client per database - Backup and Restore should always succeed
		{
		(TText*) L"Clients that keep CContactDatabase Open",
		3, 1, CBackupTestFramework::EIdleClient, ETrue, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Clients that close CContactDatabase",
		3, 1, CBackupTestFramework::EIdleClient, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
    	},

        {
		(TText*) L"Clients that keep CContactDatabase Open; Restore fails",
		3, 1, CBackupTestFramework::ERestoreCorruptDbTest, ETrue, CBackupTestFramework::EAllOpenForBackup , conn::EBackupBase
		},

		// clients open a contact Local View - Backup and Restore should always succeed
		{
		(TText*) L"Clients that keep a Local View Open",
		1, 1, CBackupTestFramework::EOpenLocalView, ETrue, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Clients that close Local View and database",
		1, 1, CBackupTestFramework::EOpenLocalView, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},

		// clients open a contact Remote View - Backup and Restore should always succeed
		{
		(TText*) L"Clients that keep a Remote View Open",
		1, 1, CBackupTestFramework::EOpenRemoteView, ETrue, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Clients that close Remote View and database",
		1, 1, CBackupTestFramework::EOpenRemoteView, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},

		// Multiple clients per database - Backup and Restore should always succeed
		{
		(TText*) L"Multiple clients per database, all keep CContactDatabase Open",
		3, 3, CBackupTestFramework::EIdleClient, ETrue, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Multiple clients per database, all close CContactDatabase",
		3, 3, CBackupTestFramework::EIdleClient, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},
		
				
		{
		(TText*) L"Two clients per database, one close and one keep CContactDatabase open",
		2, 2, CBackupTestFramework::EIdleClient, ETrue, CBackupTestFramework::EHalfCloseForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Two clients per database, one closes its contact item and one keeps its contact item open",
		1, 2, CBackupTestFramework::EMultipleOpenOneContactForEdit, EFalse, CBackupTestFramework::EHalfCloseForBackup, conn::EBackupBase
        },

		/*
		 Test client activities that should BLOCK Backup / Restore
		 Tests are in pairs:
		 1. does not respond to Backup or Restore - (tests that Backup & Restore fail)
		 2. closes all resources when Backup or Restore begin - (tests that Backup & Restore succeed)
		*/

		// Client opens contact for edit - Backup and Restore succeed when resources are freed
		{
		(TText*) L"Client opens contact for edit, resources kept open",
		1, 1, CBackupTestFramework::EOpenOneContactForEdit, EFalse, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Client opens contact for edit, resources released",
		1, 1, CBackupTestFramework::EOpenOneContactForEdit, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},

		// Open two contacts for edit - Backup and Restore succeed when resources are freed
		{
		(TText*) L"Open two contacts for edit, resources kept open",
		1, 1, CBackupTestFramework::EOpenTwoContactsForEdit, EFalse, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Open two contacts for edit, resources released",
		1, 1, CBackupTestFramework::EOpenTwoContactsForEdit, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},


#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
		// Active Compact - Backup and Restore succeed when resources are free
		{
		(TText*) L"Active Compact, resources kept open",
		1, 1, CBackupTestFramework::EContactsActiveCompact, EFalse, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Active Compact, resources released",
		1, 1, CBackupTestFramework::EContactsActiveCompact, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},

		// Active Recover - Backup and Restore succeed when resources are free
		{
		(TText*) L"Active Recover, resources kept open",
		1, 1, CBackupTestFramework::EContactsActiveRecover, EFalse, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Active Recover, resources released",
		1, 1, CBackupTestFramework::EContactsActiveRecover, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},
#endif

		// Async Find - Backup and Restore succeed when resources are freed
		{
		(TText*) L"Async Find - Blocks Backup / Restore until it completes",
		1, 1, CBackupTestFramework::EContactsAsyncFind, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},

		// Contacts Idle Sorter - Backup and Restore succeed when it completes and resources are freed
		{
		(TText*) L"Contacts Idle Sorter - Blocks Backup / Restore until it completes",
		1, 1, CBackupTestFramework::EContactsIdleSorter, ETrue, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},

		// Contacts client updates SpeedDial and checks this is Backed-up and Restored
		{
		(TText*) L"Contacts test for .Ini file Backup and Restore (clients don't close)",
		1, 1, CBackupTestFramework::EContactsIniFileTest, ETrue, CBackupTestFramework::EAllOpenForBackup, conn::EBackupBase
		},
		// Open Remote View and open a contact - Backup and Restore succeed when it completes and resources are freed
 		{
		(TText*) L"Multiple clients that create a remote view and open a contact(clients close)",
		1, 2, CBackupTestFramework::EOpenRemoteViewOneContactForEdit, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},
		{
		(TText*) L"Contacts test for .Ini file Backup and Restore(clients close",
		1, 1, CBackupTestFramework::EContactsIniFileTest, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupBase
		},

		//////////
		// Incremental Backup and Restore. Should always succeed.
		{
		(TText*) L"INCREMENTAL: Clients that keep CContactDatabase Open",
		3, 1, CBackupTestFramework::EIdleClient, ETrue, CBackupTestFramework::EAllOpenForBackup, conn::EBackupIncrement
		},
		{
		(TText*) L"INCREMENTAL: Client opens contact for edit, resources released",
		1, 1, CBackupTestFramework::EOpenOneContactForEdit, ETrue, CBackupTestFramework::EAllCloseForBackup, conn::EBackupIncrement
 		}
	};


CBackupTestFramework* CBackupTestFramework::NewLC()
	{
	CBackupTestFramework* self = new(ELeave) CBackupTestFramework();
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}
	
	
CBackupTestFramework::CBackupTestFramework() : CTimer(CActive::EPriorityStandard)
	{
	CActiveScheduler::Add(this);
	}
	
	
void CBackupTestFramework::ConstructL()
	{
	CTimer::ConstructL();
	
    // Test server used for copying files around.    
    User::LeaveIfError(iTestServ.Connect());
    iBackupHelper = CBackupHelper::NewL(iTestServ);
	}


CBackupTestFramework::~CBackupTestFramework()
	{
	// cleanup from current test case
	CTimer::Cancel();

    iTestServ.Close();

	delete iBackupHelper;
	iContactClientSession.ResetAndDestroy();
	}
	
	
void CBackupTestFramework::DoBackupRestoreTestsL()
	{
	const TInt testCount = sizeof(BackupTestCases) / sizeof(CBackupTestFramework::TBackupRestoreTestCase);

	test.Printf(_L("Iterate through all %i Backup and Restore test cases"), testCount);

	for (TInt testIndex = 0; testIndex < testCount; ++testIndex)
		{
		iTestCase = &BackupTestCases[testIndex];
		BackupRestoreTestL();
		}
	}



// Method to setup the Use Case under test
// returns ETrue if TrequestStatus was used
TBool CBackupTestFramework::PrepareBackupClientTestCaseL(TRequestStatus& aStatus)
	{
	TBool asyncRequest = EFalse;

	// for every database we are required to open
	for (TInt dbCount = 1; (dbCount <= iTestCase->iNumDatabases) && (!asyncRequest); ++dbCount)
		{
		switch (dbCount)
			{
			case 1:
				asyncRequest = PrepareTestCaseL(KBackupDatabaseFile1(), aStatus);
				break; 

			case 2:
				asyncRequest = PrepareTestCaseL(KBackupDatabaseFile2(), aStatus);
				break;

			case 3:
				asyncRequest = PrepareTestCaseL(KBackupDatabaseFile3(), aStatus);
				break;

			default: // something is wrong with test code
				User::Invariant();
			}
		}

	return asyncRequest;
	}
	

// Method to implement the Use Case under test
TBool CBackupTestFramework::PrepareTestCaseL(const TDesC& aDatabaseName, TRequestStatus& aStatus)
	{
	TBool asyncRequest = EFalse;

	// at least one, possibly more, clients per database
	for (TInt clClient = 1; clClient <= iTestCase->iClientsPerDatabase; ++clClient)
		{
		// open database
				TBool isCloseForBackup = ETrue;

		switch(iTestCase->iCloseForBackup)
			{
			case EAllOpenForBackup:
				isCloseForBackup = EFalse;
				break;
			case EHalfCloseForBackup:
				if(clClient > iTestCase->iClientsPerDatabase/2)
					{
					isCloseForBackup = EFalse;
					}
				break;
			case EAllCloseForBackup:
			default:
				break;
			}

		CContactsClient* db = NewDatabaseClientL(aDatabaseName, isCloseForBackup);


		// specific test case behaviour
		switch (iTestCase->iActivity)
			{
			// activities that do not block backup / restore
			case EIdleClient:
			case ERestoreCorruptDbTest:
				// demonstrate database is open, read from it
				test.Next(_L("Read a contact from database"));
				db->ReadContactL();
				break;

			case EOpenLocalView:
				test.Next(_L("open contact Local View"));
				db->OpenLocalViewL();
				break;

			case EOpenRemoteView:
				test.Next(_L("open contact Remote View"));
				db->OpenRemoteViewL();
				break;

			// activities that can block backup / restore
			case EOpenOneContactForEdit:
				test.Next(_L("Open a contact from database"));
				db->OpenContactL(KOpenContactId1);
				break;

			case EOpenTwoContactsForEdit:
				test.Next(_L("Open 2 contacts from database"));
				db->OpenContactL(KOpenContactId1);
				db->OpenContactL(KOpenContactId2);
				break;

			case EContactsAsyncFind:
				test.Next(_L("Start Async Find on database"));
				db->StartAsyncFindL();
				break;

			case EContactsActiveCompact:
#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
				test.Next(_L("Start Active Compact on database"));
				db->StartActiveCompactL();
#endif
				break;

			case EContactsActiveRecover:
#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
				test.Next(_L("Start Active Recover on database"));
				db->StartActiveRecoverL();
#endif
				break;

			case EContactsIdleSorter:
				test.Next(_L("Start Contacts Idle Sorter"));
				db->StartIdleSorterL(aStatus);
				asyncRequest = ETrue;
				break;

			case EContactsIniFileTest:
				// demonstrate database is open, read from it
				test.Next(_L("Read a contact from database"));
				db->ReadContactL();
				break;
				
						case EOpenRemoteViewOneContactForEdit:
			    test.Next(_L("Open a contact from database & open contact Remote View"));
			    if(clClient == 1) //There are two clients for this DB, first opens a view, second edits a contact
			        {
			    	db->OpenRemoteViewL();
			        }
			    else
			        {
			    	db->OpenContactL(KOpenContactId1);
			        }
			    break;
			case EMultipleOpenOneContactForEdit:
			    test.Next(_L("Multiple clients, one closes contact item one leaves open"));
			    if (isCloseForBackup) //ETrue
			        {
			    	db->OpenContactL(KOpenContactId1);
			        }  
				else //EFalse
				    {
					db->OpenContactL(KOpenContactId2);
				    }
				    
				break;

			}
		}

	return asyncRequest;
	}



// Reconnect disconnected client after Backup/Restore
void CBackupTestFramework::ReconnectBackupClientTestCaseL()
	{
	// check that databases can be re-opened and are still useable
	const TInt numDatabases = iContactClientSession.Count();
	for (TInt i = 0; i < numDatabases; i++)
		{
		if (!iContactClientSession[i]->IsOpen())
			{
			test.Printf(_L("reopen database client # %i after backup/restore\n\r"), i + 1);
			iContactClientSession[i]->OpenDatabaseL();
			}
			
		// read from db
		test.Next(_L("Read a contact through database client"));
		iContactClientSession[i]->ReadContactL();
		}
	}


// test action if client didn't close database
void CBackupTestFramework::CheckConnectionAfterBackupForTestCaseL()
	{
	const TInt numDatabases = iContactClientSession.Count();

	// specific test case behaviour
	switch (iTestCase->iActivity)
		{
		// activities that do not block backup / restore
		case EIdleClient:
		case EOpenLocalView:
		case EOpenRemoteView:
		case EContactsIniFileTest:
			for (TInt i = 0; i < numDatabases; i++)
				{
				// read from each db
				test.Next(_L("Read a contact through database client"));
				iContactClientSession[i]->ReadContactL();
				}
			break;

		case ERestoreCorruptDbTest:
#ifndef __SYMBIAN_CNTMODEL_USE_SQLITE__
			for (TInt i = 0; i < numDatabases; i++)
				{
				// read from each db
				test.Next(_L("Read a contact through database client"));
				TRAPD(err, iContactClientSession[i]->ReadContactL());
				
				// The restore is complete. The corrupted db file was damaged
                // but should have been recovered after the restore completed. 
                // However, the contact doesn't exist in the db. If the 
                // corrupted db file was totally unrecognizable then the recover
                // wouldn't have been attempted and the db would be closed. This
                // would then return KErrNotReady.
				if((iTestStep == EPostRestore) &&
				    (iContactClientSession[i]->DatabaseName()==KBackupDatabaseFile1))
					{
					TEST_CONDITION(err==KErrNotFound);
					}
				else //others should not Leave, so propagate Leave if it occurs.
					{
					if(err != KErrNone)
						{
						User::Leave(err);
						}
					}
				}
#endif
			break;

		// activities that can block backup / restore
		case EOpenOneContactForEdit:
			for (TInt i = 0; i < numDatabases; i++)
				{
				test.Next(_L("Commit contact to database"));
				iContactClientSession[i]->CommitContactL(KOpenContactId1);
				}
			break;

		case EOpenTwoContactsForEdit:
			for (TInt i = 0; i < numDatabases; i++)
				{
				test.Next(_L("Commit 2 contacts to database"));
				iContactClientSession[i]->CommitContactL(KOpenContactId1);
				iContactClientSession[i]->CommitContactL(KOpenContactId2);
				}
			break;

		case EContactsAsyncFind:
			for (TInt i = 0; i < numDatabases; i++)
				{
				test.Next(_L("Complete Async Find on database"));
				iContactClientSession[i]->CompleteAsyncFindL();
				}
			break;

		case EContactsActiveCompact:
			for (TInt i = 0; i < numDatabases; i++)
				{
				test.Next(_L("Complete Active Compact on database"));
				iContactClientSession[i]->CompleteActiveCompactL();
				}
			break;

		case EContactsActiveRecover:
			for (TInt i = 0; i < numDatabases; i++)
				{
				test.Next(_L("Complete Active Recover on database"));
				iContactClientSession[i]->CompleteActiveRecoverL();
				}
			break;

		case EContactsIdleSorter:
			// nothing to do for this Use Case
			break;
		}
	}



// support methods for testing .Ini file Backup and Restore

// any test case action required immediately before Backup start notifiction
void CBackupTestFramework::PreBackupNotificationActionsL()
	{
	const TInt numDatabases = iContactClientSession.Count();

	// specific test case behaviour
	switch (iTestCase->iActivity)
		{
		case EIdleClient:
        case ERestoreCorruptDbTest:
		case EOpenLocalView:
		case EOpenRemoteView:
		case EOpenOneContactForEdit:
		case EOpenTwoContactsForEdit:
		case EContactsAsyncFind:
		case EContactsActiveCompact:
		case EContactsActiveRecover:
		case EContactsIdleSorter:
			// nothing to do for this Use Case
			break;

		case EContactsIniFileTest:
			// make change to Contacts .ini file that should be Backed-up
			for (TInt i = 0; i < numDatabases; i++)
				{
				// read from each db
				test.Next(_L("Set Speed Dial 1 for database"));
				iContactClientSession[i]->SetSpeedDialL(KSpeedDialContactId, KSpeedDialPositionOne);
				}
			break;
		}
	}


// any test case action required after Backup completion
void CBackupTestFramework::PostBackupActionsL()
	{
	const TInt numDatabases = iContactClientSession.Count();

	// specific test case behaviour
	switch (iTestCase->iActivity)
		{
		case EIdleClient:
        case ERestoreCorruptDbTest:
		case EOpenLocalView:
		case EOpenRemoteView:
		case EOpenOneContactForEdit:
		case EOpenTwoContactsForEdit:
		case EContactsAsyncFind:
		case EContactsActiveCompact:
		case EContactsActiveRecover:
		case EContactsIdleSorter:
		case EOpenRemoteViewOneContactForEdit:
		case EMultipleOpenOneContactForEdit:

			// nothing to do for this Use Case
			break;

		case EContactsIniFileTest:
			// check Contacts .ini is correct
			for (TInt i = 0; i < numDatabases; i++)
				{
				// read from each db
				test.Next(_L("Check Speed Dial 1 still set for database"));
				iContactClientSession[i]->CheckSpeedDialSetL(KSpeedDialContactId, KSpeedDialPositionOne);
				}
			break;
		}
	}


// any test case action required immediately before Restore start notifiction
void CBackupTestFramework::PreRestoreNotificationActionsL()
	{
	const TInt numDatabases = iContactClientSession.Count();

	// specific test case behaviour
	switch (iTestCase->iActivity)
		{
		case EIdleClient:
        case ERestoreCorruptDbTest:
		case EOpenLocalView:
		case EOpenRemoteView:
		case EOpenOneContactForEdit:
		case EOpenTwoContactsForEdit:
		case EContactsAsyncFind:
		case EContactsActiveCompact:
		case EContactsActiveRecover:
		case EContactsIdleSorter:
		case EOpenRemoteViewOneContactForEdit:
		case EMultipleOpenOneContactForEdit:

			// nothing to do for this Use Case
			break;

		case EContactsIniFileTest:
			// make change to Contacts .ini file before Restore
			for (TInt i = 0; i < numDatabases; i++)
				{
				// read from each db
				test.Next(_L("Remove Speed Dial 1 from database"));
				iContactClientSession[i]->RemoveSpeedDialL(KSpeedDialContactId, KSpeedDialPositionOne);
				}
			break;
		}
	}

// any test case action required after Restore completion
void CBackupTestFramework::PostRestoreActionsL()
	{
	const TInt numDatabases = iContactClientSession.Count();

	// specific test case behaviour
	switch (iTestCase->iActivity)
		{
		case EIdleClient:
        case ERestoreCorruptDbTest:
		case EOpenLocalView:
		case EOpenRemoteView:
		case EOpenOneContactForEdit:
		case EOpenTwoContactsForEdit:
		case EContactsAsyncFind:
		case EContactsActiveCompact:
		case EContactsActiveRecover:
		case EContactsIdleSorter:
		case EOpenRemoteViewOneContactForEdit:
		case EMultipleOpenOneContactForEdit:

			// nothing to do for this Use Case
			break;

		case EContactsIniFileTest:
			// check Restored Contacts .ini file is the same as was Backed-up
			for (TInt i = 0; i < numDatabases; i++)
				{
				// read from each db
				test.Next(_L("Check Restored Speed Dial 1 from database"));
				iContactClientSession[i]->CheckSpeedDialSetL(KSpeedDialContactId, KSpeedDialPositionOne);
				}
			break;
		}
	}




// Backup and Restore test with chosen Use Case
void CBackupTestFramework::BackupRestoreTestL()
	{
	// need to do type conversion in 2 steps
	TPtrC title(iTestCase->iTestTitle);
	test.Next(title);


	// start backup & restore tests in Active Scheduler
	iTestStep = EPreBackup;
	After(0);
	CActiveScheduler::Start();

	// ensure databases closed & release resources
	iContactClientSession.ResetAndDestroy();

	// any error from active scheduler?
	User::LeaveIfError(iTestError);
	}



void CBackupTestFramework::RunL()
	{
	TBool waitForAsyncRequest = EFalse;
	
	if (iStatus.Int() != KErrCancel)
		{
		switch (iTestStep)
			{
		// Backup test
		case EPreBackup:
			test.Start(_L("Backup test"));

			test.Start(_L("Prepare Backup test case, open database(s) etc..."));
			waitForAsyncRequest = PrepareBackupClientTestCaseL(iStatus);

			// reset count number of Backup notifications
			iClientNotifications = 0;
			iViewUnavailableCount = 0;
			break;
				
		case ENotifyBackupStart:
			// any test case action required immediately before Backup start notifiction
			PreBackupNotificationActionsL();

			if(conn::EBackupIncrement == iTestCase->iBackupIncType)
				{
				test.Next(_L("notify start of incremental backup"));
				iBackupHelper->StartBackupL(conn::EBURBackupPartial, conn::EBackupIncrement);
				}
			else
				{
				test.Next(_L("notify start of backup"));
				iBackupHelper->StartBackupL(conn::EBURBackupFull, conn::EBackupBase);
				}

			break;

		case ECheckBackupStartNotifications:
			if(conn::EBackupIncrement == iTestCase->iBackupIncType)
				{
				test.Next(_L("check number of incremental backup start notifications"));					
				}
			else
				{
				test.Next(_L("check number of backup start notifications"));	
				}
			TEST_CONDITION(iContactClientSession.Count() == iClientNotifications);

			// test case has views?
			if ((iTestCase->iActivity == EOpenLocalView) || (iTestCase->iActivity == EOpenRemoteView))
				{
				if (iTestCase->iCloseForBackup)
					{
					// Contacts clients close for Backup or Restore
					test.Next(_L("check not too many Contact View unavailable notifications"));
					TEST_CONDITION((iTestCase->iNumDatabases * iTestCase->iClientsPerDatabase) >= iViewUnavailableCount);
					}
				else
					{
					// Contacts clients open for Backup or Restore
					test.Next(_L("check the number of Contact View unavailable notifications"));
					TEST_CONDITION((iTestCase->iNumDatabases * iTestCase->iClientsPerDatabase) == iViewUnavailableCount);
					}
				}
			break;

		case EDoBackup:
			if(conn::EBackupIncrement == iTestCase->iBackupIncType)
				{
				test.Next(_L("attempt incremental backup of database(s)"));					
				}
			else
				{
				test.Next(_L("attempt backup of database(s)"));		
				}

			// Clients have not closed for Backup?
			if (iTestCase->iCloseForBackup != EAllCloseForBackup)
				{
				const TInt numDatabases = iContactClientSession.Count();

				// find open database sessions
				test.Next(_L("Check that new Read and Open.(Write) operations cannot start"));
				for (TInt i = 0; i < numDatabases; i++)
					{
					if (! iContactClientSession[i]->IsCloseForBackup())
					    {
					    test.Next(_L("check that database read is locked"));
					    TRAPD(error, iContactClientSession[i]->ReadContactL());
					    TEST_CONDITION(KErrLocked == error);

					    test.Next(_L("check that database write is locked"));
					    TRAP(error, iContactClientSession[i]->OpenContactL(KOpenContactId3));
					    TEST_CONDITION(KErrLocked == error);

					    test.Next(_L("check that phone number lookup (database read) is locked"));
					    TRAP(error, iContactClientSession[i]->FindPhoneNumberL());
					    TEST_CONDITION(KErrLocked == error);
					    }
					}
				}

			if(iTestCase->iActivity == EContactsIniFileTest)
				{
			    test.Next(_L("checking that backup of cntmodel.ini file succeeds"));
		 	    TEST_CONDITION(iBackupHelper->SimulateIniBackup());
				}

			if (iTestCase->iExpectedBackupSuccess)
				{
				test.Next(_L("checking that backup of databases succeeds"));
				TEST_CONDITION(iBackupHelper->SimulateDbBackup());
				}
			else
				{
				test.Next(_L("checking that backup of databases fails"));
				TEST_CONDITION(! iBackupHelper->SimulateDbBackup());
				}

			// reset count for end of backup notifications		
			iClientNotifications = 0;
			iViewReadyCount = 0;
			break;
			
		case ENotifyBackupEnd:
			test.Next(_L("notify end of backup"));
			iBackupHelper->EndBackupL();
			break;

		case ECheckBackupEndNotifications:
			// if database connections are kept open
			if (iTestCase->iCloseForBackup == EAllOpenForBackup)
				{
				test.Next(_L("check number of backup end notifications"));
				TEST_CONDITION(iContactClientSession.Count() == iClientNotifications);

				// test case kept views open?
				if ((iTestCase->iActivity == EOpenLocalView) || (iTestCase->iActivity == EOpenRemoteView))
					{
					test.Next(_L("check the number of Contact View ready notifications"));
					TEST_CONDITION((iTestCase->iNumDatabases * iTestCase->iClientsPerDatabase) == iViewReadyCount);
					}
				}
			break;

		case EPostBackup:
			test.Next(_L("post backup verify database(s) useable"));
			if (iTestCase->iCloseForBackup != EAllOpenForBackup)
				{
				ReconnectBackupClientTestCaseL();
				}
			else
				{
				CheckConnectionAfterBackupForTestCaseL();
				}

			// any test case action required after Backup completion
			PostBackupActionsL();
			break;
			
		case EFinishedBackup:
			test.Next(_L("Cleanup all client resources for test case"));
			// cleanup after backup test
			iContactClientSession.ResetAndDestroy();
			test.End();
			break;

		// Successful Restore test
		case EPreRestore:
			test.Next(_L("Restore test"));

			test.Start(_L("pre-restore access database(s)"));
			waitForAsyncRequest = PrepareBackupClientTestCaseL(iStatus);

			// reset count of Restore notifications
			iClientNotifications = 0;
			iViewUnavailableCount = 0;
			break;
			
		case ENotifyRestoreStart:
			// any test case action required immediately before Restore start notifiction
			PreRestoreNotificationActionsL();

			test.Next(_L("notify start of restore"));
			iBackupHelper->StartRestoreL();
			break;

		case ECheckRestoreStartNotifications:
			test.Next(_L("check number of restore start notifications"));
			TEST_CONDITION(iContactClientSession.Count() == iClientNotifications);

			// test case has views?
			if ((iTestCase->iActivity == EOpenLocalView) || (iTestCase->iActivity == EOpenRemoteView))
				{
				if (iTestCase->iCloseForBackup == EAllOpenForBackup)
					{
					// Contacts clients open for Backup or Restore
					test.Next(_L("check the number of Contact View unavailable notifications"));
					TEST_CONDITION((iTestCase->iNumDatabases * iTestCase->iClientsPerDatabase) == iViewUnavailableCount);
					}
				else
					{
					// Contacts clients close for Backup or Restore
					test.Next(_L("check not too many Contact View unavailable notifications"));
					TEST_CONDITION((iTestCase->iNumDatabases * iTestCase->iClientsPerDatabase) >= iViewUnavailableCount);
					}
				}
			break;

		case EDoRestore:
			test.Next(_L("attempt restore of database(s)"));

			// Clients have not closed for Backup?
				if (iTestCase->iCloseForBackup == EAllOpenForBackup)

				{
				const TInt numDatabases = iContactClientSession.Count();

				// find all open database sessions
				for (TInt i = 0; i < numDatabases; i++)
					{
					test.Next(_L("check that database read is Locked"));
					TRAPD(error, iContactClientSession[i]->ReadContactL());
					TEST_CONDITION(KErrLocked == error);

					test.Next(_L("check that database write is locked"));
					TRAP(error, iContactClientSession[i]->OpenContactL(KOpenContactId3));
					TEST_CONDITION(KErrLocked == error);

				    test.Next(_L("check that phone number lookup (database read) is locked"));
				    TRAP(error, iContactClientSession[i]->FindPhoneNumberL());
				    TEST_CONDITION(KErrLocked == error);
					}
				}
 			if(iTestCase->iActivity == EContactsIniFileTest)
				{
			    test.Next(_L("checking that restore of ini file succeeds"));
			    TEST_CONDITION(iBackupHelper->SimulateIniRestore());
				}

			if (iTestCase->iExpectedBackupSuccess)
				{
				if (iTestCase->iActivity == ERestoreCorruptDbTest)
					{
					test.Next(_L("checking that restore of databases fails on the corrupted one"));
					TEST_CONDITION(iBackupHelper->SimulateDamagedDbRestore());
					}
				else
					{
    				test.Next(_L("checking that restore of databases succeeds"));
    				TEST_CONDITION(iBackupHelper->SimulateDbRestore());
                    }
				}
			else
				{
				test.Next(_L("checking that restore of databases fails"));
				TEST_CONDITION(! iBackupHelper->SimulateDbRestore());
				}

			// reset count for end of Restore notifications
			iClientNotifications = 0;
			iViewReadyCount = 0;
			break;
			
		case ENotifyRestoreEnd:
			test.Next(_L("notify end of restore"));
			iBackupHelper->EndRestoreL();
			break;

		case ECheckRestoreEndNotifications:
			// if database connections are kept open
			if (iTestCase->iCloseForBackup == EAllOpenForBackup)
				{
				test.Next(_L("check number of restore end notifications"));
				TEST_CONDITION(iContactClientSession.Count() == iClientNotifications);

				// test case kept views open?
				if ((iTestCase->iActivity == EOpenLocalView) || (iTestCase->iActivity == EOpenRemoteView))
					{
					test.Next(_L("check the number of Contact View ready notifications"));
					TEST_CONDITION((iTestCase->iNumDatabases * iTestCase->iClientsPerDatabase) == iViewReadyCount);
					}
				}
			break;

		case EPostRestore:
			test.Next(_L("post-restore verify database(s) useable"));
			if (iTestCase->iCloseForBackup)
				{
				ReconnectBackupClientTestCaseL();
				}
			else
				{
				CheckConnectionAfterBackupForTestCaseL();
				}

			// any test case action required after Restore completion
			PostRestoreActionsL();
			break;

		case EFinishedRestore:
			test.Next(_L("Cleanup all client resources for test case"));
			// cleanup after backup test
			iContactClientSession.ResetAndDestroy();
			// end x.y.z restore test
			test.End();
			// end x.y test case
			test.End();

            // overwrite corrupted database, other tests don't use it
            if(iTestCase->iActivity == ERestoreCorruptDbTest)
                {			
                // Copy a non-corrupted db over the corrupted one for other tests to use.
                iBackupHelper->SimulateDbRestore();
                }

			// All Done
			CActiveScheduler::Stop();
			return;
			}


		// no pause required between steps?
		if (waitForAsyncRequest)
			// waits for an asynchronous request to complete
			{
			SetActive();
			}
		else if ((iTestStep == EPreBackup) || (iTestStep == EPreRestore))
			{
			// start of Backp or Restore test cycle - allow contacts client to settle (e.g. contacts view to sort)
			test.Printf(_L("Wait %d ms to allow contacts client to settle (e.g. contacts view to sort)\n"), KWaitForClientToSettle);
			After(KWaitForClientToSettle);
			}
		else if ((iTestStep == EPostBackup) || (iTestStep == EPostRestore))
			{
			// end of Backup or Restore test cycle - allow all system components to settle
			test.Printf(_L("Wait %d ms to allow all system components to settle\n"), KWaitForSystemToSettle);
			After(KWaitForSystemToSettle);
			}
		else if ((iTestStep == ENotifyBackupStart) || (iTestStep == ENotifyBackupEnd) || (iTestStep == ENotifyRestoreStart) || (iTestStep == ENotifyRestoreEnd))
			{
			// allow notification to propagate
			test.Printf(_L("Wait %d ms to allow notification to propagate\n"), KWaitForBackupNotification);
			After(KWaitForBackupNotification);
			}
		else
			{
			// minimum wait required
			After(1);
			}
			
		// next step
		iTestStep = (TBackupRestoreSteps) (iTestStep + 1);
		}
	}


TInt CBackupTestFramework::RunError(TInt aError)
	{
	// RunL is verbose and prints details of each step
	// so just print error info
	test.Printf(_L("Backup and Restore test error %d (at step %d)\n\r"), aError, iTestStep);
	
	// and state info
	const TInt clientCount = iContactClientSession.Count();
	for (TInt j = 0; j < clientCount; j++)
		{
		test.Printf(_L("client %i, IsOpen = %i, name \"%S\"\n\r"), 
			j, iContactClientSession[j]->IsOpen(), &iContactClientSession[j]->DatabaseName());
		}
	
	// propagate error
	iTestError = aError;
	
	CActiveScheduler::Stop();
	return KErrNone;
	}


/////////////////

CContactsClient* CBackupTestFramework::NewDatabaseClientL(const TDesC& aDatabaseName, TBool aCloseForBackup)
	{
	test.Printf(_L("open database \"%S\"\n\r"), &aDatabaseName);

	// open a Contacts Model client for test case
	CContactsClient* newClient = CContactsClient::NewLC(aDatabaseName, this, *this, aCloseForBackup);
	CleanupStack::Check(newClient);

	// remember for later cleanup
	iContactClientSession.AppendL(newClient);
	CleanupStack::Pop(newClient);
	return newClient;
	}


void CBackupTestFramework::ContactsBackupRestoreObserver(CContactsClient& aContactClient, const TBool aRestore, const TBool aStart)
	{
	iClientNotifications ++;
	
	// test case should respond to Backup / Restore notification ?
	if (aStart && aContactClient.IsCloseForBackup())
		{
		test.Next(aRestore ? _L("Restore start notification - closing client") : _L("Backup start notification - closing client"));
		aContactClient.CloseViews();
		aContactClient.StartActiveClose();	
		}
	}



/*
 Contact Views become EUnavailable when Backup or Restore start,
 if the View is kept open it becomes EReady again afterwards.
 */
void CBackupTestFramework::HandleContactViewEvent(const CContactViewBase& /*aView*/,const TContactViewEvent& aEvent)
	{
	if (aEvent.iEventType == TContactViewEvent::EUnavailable)
		{
		iViewUnavailableCount++;
		// reset Ready count for end of Backup or Restore
		iViewReadyCount = 0;
		}
	else if (aEvent.iEventType == TContactViewEvent::EReady)
		{
		iViewReadyCount++;
		}
	}




////////////////////////////////////////////////////////////


LOCAL_C void TestCondition(TBool aCondition, TInt aLineNumber)
	{
	// if the test is about to fail, cleanup files first
	if (!aCondition)
		{
		CBackupTestConductor::DeleteDatabases();
		}
	test.operator()(aCondition, aLineNumber);
	}


LOCAL_C void DoMainL(CActiveScheduler* scheduler)
    {
	CActiveScheduler::Install(scheduler);

	CBackupTestConductor* tester = CBackupTestConductor::NewL();
	CleanupStack::PushL(tester);

 	tester->RunTestsL();
	CleanupStack::PopAndDestroy(tester); 
	}
/**

@SYMTestCaseID     PIM-T-CNT-BACKUP-0001

*/

GLDEF_C TInt E32Main()
	{
	__UHEAP_MARK;
	test.Title();
	test.Start(_L("SYMTestCaseID:PIM-T-CNT-BACKUP-0001 Contacts Backup and Restore"));
	CActiveScheduler* scheduler = new CActiveScheduler;
	test(scheduler != NULL);
	CTrapCleanup* theCleanup = CTrapCleanup::New();
	User::LeaveIfError(TheFsSession.Connect());

	test.Printf(_L("SECURE_DATA mode\r\n"));
	User::After(KWaitForSystemToSettle);

	TRAPD(ret,DoMainL(scheduler));
	if (ret != KErrNone)
		{
		test.Printf(_L("Something in the test left with error code %d\n"), ret);
		}
	TEST_CONDITION(ret == KErrNone);

	TheFsSession.Close();
	delete theCleanup;	
	delete scheduler;
	test.End();
	test.Close();
	__UHEAP_MARKEND;
	return(KErrNone);
    }