summaryrefslogtreecommitdiff
path: root/wia/ProdScan/MiniDrv.cpp
blob: 3a00291bf69b2465de4d487003b96e8c306ba7a0 (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
/**************************************************************************
*
*  Copyright � Microsoft Corporation
*
*  Title: MiniDrv.cpp
*
*  Description: This file contains the IWiaMiniDrv interface implementation
*               for the Production Scanner Driver Sample, plus C++ constructor and
*               destructor code for the main driver's objects, CWiaDriver.
*
***************************************************************************/

#include "stdafx.h"

HINSTANCE g_hInst = NULL;

/**************************************************************************\
*
* CWiaDriver constructor
*
\**************************************************************************/

CWiaDriver::CWiaDriver(
    _In_opt_ LPUNKNOWN punkOuter) :
    m_cRef(1),
    m_punkOuter(NULL),
    m_pIDrvItemRoot(NULL),
    m_lClientsConnected(0),
    m_bstrDeviceID(NULL),
    m_bstrRootFullItemName(NULL),
    m_pIStiDevice(NULL),
    m_hDeviceKey(NULL),
    m_bFeederStarted(FALSE)
{
    //
    // See if we are aggregated. If we are (almost always the case)
    // save the pointer to the controlling IUnknown, so subsequent
    // calls will be delegated. If not, set the same pointer to "this":
    //
    if (punkOuter)
    {
        m_punkOuter = punkOuter;
    }
    else
    {
        //
        // This cast is needed in order to point to right virtual table:
        //
        m_punkOuter = reinterpret_cast<IUnknown*>(static_cast<INonDelegatingUnknown*>(this));
    }

    memset(m_wszDevicePath, 0, sizeof(m_wszDevicePath));


    //
    // Warning: do not initialize the entire contents of m_config and m_status to 0,
    // this will erase the function pointer tables for the CBasicDynamicArray members!
    //

    m_hrLastEdviceError = STI_ERROR_NO_ERROR;

    m_hWiaEvent = NULL;
    m_hWiaEventStoredCopy = NULL;
    m_bstrScanAvailableItem = NULL;

    //
    // IStiUSD::Initialize not executed yet:
    //
    m_bInitialized = FALSE;

    //
    // Initialize the critical section for DestroyDriverItemTree:
    //
    InitializeCriticalSection(&m_csDestroyDriverItemTree);

    WIAS_TRACE((g_hInst, "Driver object (%p, process: %u) created", this, GetCurrentProcessId()));
}

/**************************************************************************\
*
* CWiaDriver destructor
*
\**************************************************************************/

CWiaDriver::~CWiaDriver()
{
    DWORD dwProcessId = GetCurrentProcessId();
    DWORD dwThreadId = GetCurrentThreadId();

    WIAS_TRACE((g_hInst, "Destroying driver object (%p, process: %u, thread: %u)..",
        this, dwProcessId, dwThreadId));

    //
    // Free the memory allocated for the global device ID and root item name:
    //
    if (m_bstrDeviceID)
    {
        SysFreeString(m_bstrDeviceID);
        m_bstrDeviceID = NULL;
    }

    if (m_bstrRootFullItemName)
    {
        SysFreeString(m_bstrRootFullItemName);
        m_bstrRootFullItemName = NULL;
    }

    //
    // Free WIA_FORMAT_INFO arrays:
    //
    m_tFormatInfo.Destroy();
    m_tFormatInfoImprinterEndorser.Destroy();
    m_tFormatInfoBarcodeReader.Destroy();
    m_tFormatInfoPatchCodeReader.Destroy();
    m_tFormatInfoMicrReader.Destroy();

    //
    // Free cached driver capability array:
    //
    m_tCapabilityManager.Destroy();

    //
    // Unlink and release the cached IWiaDrvItem root item interface:
    //
    DestroyDriverItemTree();

    //
    // The driver item tree is destroyed, the critical section can be deleted.
    // Make sure there is no concurrent thread releasing the Root item from
    // within IWiaMiniDrv::drvUnInitializeWia and delete the critical section:
    //
    EnterCriticalSection(&m_csDestroyDriverItemTree);
    LeaveCriticalSection(&m_csDestroyDriverItemTree);
    DeleteCriticalSection(&m_csDestroyDriverItemTree);

    if (m_bstrScanAvailableItem)
    {
        SysFreeString(m_bstrScanAvailableItem);
        m_bstrScanAvailableItem = NULL;
    }

    //
    // The WIA service may release the driver object during a scanner status update
    // operation, for example following an unexpected device disconnect event.
    // When this happens we must wait for the critical section to be released before
    // deleting it, otherwise the thread owning the CS may remain in an undefined state:
    //

    m_bInitialized = FALSE;

    WIAS_TRACE((g_hInst, "Driver object (%p, process: %u, thread: %u) destroyed", this, dwProcessId, dwThreadId));
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvInitializeWia. Initializes the mini-driver in
* the context of a new WIA application session and creates if needed the
* unique Driver Item Tree describing the item architecture and item names
* that the WIA service will use to create duplicate Application Item Trees
* for each new WIA application session opened with the driver. When the WIA
* service executes this method the driver must receive a character string
* containing the device�s unique identifier along with the IStiDevice COM
* interface pointer describing the current device. The driver must create
* the driver item tree if it hasn�t been built yet. Finally, the driver
* must return back to the WIA service the pointer to the Root item in the
* Driver Item Tree.
*
* Parameters:
*
*    pWiasContext         - pointer to the item context
*    lFlags               - reserved (set to 0)
*    bstrDeviceID         - string containing the device's unique identifier
*    bstrRootFullItemName - string containing the full name of the root item
*    pStiDevice           - points to an IStiDevice interface
*    pIUnknownOuter       - (optional) to receive an IUnknown interface address
*    ppIDrvItemRoot       - receives the address of the IWiaDrvItem interface
*                           for the root item
*    ppIUnknownInner      - unsupported and always set to NULL (all this driver's WIA
*                           functionality is covered through its IWiaMiniDrv interface)
*    plDevErrVal          - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvInitializeWia(
    _Inout_   BYTE*         pWiasContext,
              LONG          lFlags,
    _In_      BSTR          bstrDeviceID,
    _In_      BSTR          bstrRootFullItemName,
    _In_      IUnknown*     pStiDevice,
    _In_      IUnknown*     pIUnknownOuter,
    _Out_     IWiaDrvItem** ppIDrvItemRoot,
    _Out_     IUnknown**    ppIUnknownInner,
    _Out_     LONG*         plDevErrVal)
{
    UNREFERENCED_PARAMETER(pIUnknownOuter);
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = S_OK;

    //
    // (1/2) Uncomment the code below to enable a basic safety guard against premature
    // drvInitializeWia call made by WIA Service before IStiUSD::Initialize completes:
    //
    // If IWiaMiniDrv::drvInitializeWia is called before IStiUSD::Initialize
    // is complete wait up to 1 minute (10 msec x 6000 times) and retry:
    //
    // const LONG lMaxWaitCycles = 6000;
    // const LONG lWaitInterval = 10;
    // LONG lWaitCycles = 0;
    //

    WIAEX_TRACE_BEGIN;

    if ((!pWiasContext) || (!plDevErrVal))
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    if (SUCCEEDED(hr))
    {
        *plDevErrVal = 0;
        *ppIDrvItemRoot = NULL;
        *ppIUnknownInner = NULL;

        if (!m_bstrDeviceID)
        {
            m_bstrDeviceID = SysAllocString(bstrDeviceID);
            if (!m_bstrDeviceID)
            {
                hr = E_OUTOFMEMORY;
                WIAEX_ERROR((g_hInst, "Failed to allocate BSTR DeviceID string, hr = 0x%08X", hr));
            }
        }
    }

    if (SUCCEEDED(hr))
    {
        if (!m_pIStiDevice)
        {
            m_pIStiDevice = reinterpret_cast<IStiDevice*>(pStiDevice);
        }

        if (!m_bstrRootFullItemName)
        {
            m_bstrRootFullItemName = SysAllocString(bstrRootFullItemName);
            if (!m_bstrRootFullItemName)
            {
                hr = E_OUTOFMEMORY;
                WIAEX_ERROR((g_hInst, "Failed to allocate BSTR Root full item name string, hr = 0x%08X", hr));
            }
        }
    }

    if (SUCCEEDED(hr))
    {
        if (!m_pIDrvItemRoot)
        {
            //
            // (2/2) Uncomment the code below to enable a basic safety guard against premature
            // drvInitializeWia call made by WIA Service before IStiUSD::Initialize completes:
            //
            // The WIA service may call IWiaMiniDrv::drvInitializeWia before the
            // IStiUSD::Initialize call is completed. Temporarily block creating the Driver Item
            // Tree until IStiUSD::Initialize is complete:
            //
            // if (!m_bInitialized)
            // {
            //     WIAS_TRACE((g_hInst, "Driver not intialized yet, wait.."));
            //
            //     //
            //     // Wait up to 10 msec x 6000 = 1 minute for IStiUSD::Initialize to complete:
            //     //
            //     while ((!m_bInitialized) && ((++lWaitCycles) <= lMaxWaitCycles))
            //     {
            //         Sleep(lWaitInterval);
            //     }
            //
            //     if (m_bInitialized)
            //     {
            //         WIAS_TRACE((g_hInst, "Driver intialized now"));
            //     }
            //     else
            //     {
            //         WIAEX_ERROR((g_hInst, "Maxmimum timeout reached, driver still not initialized"));
            //     }
            // }
            //

            //
            // Create the Driver Item Tree matching the current scanner configuration:
            //
            hr = BuildDriverItemTree();
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the Driver Item Tree, hr = 0x%08X", hr));
            }
        }
        else
        {
            //
            // The Driver Item Tree already exists. The root item of this item tree
            // should be returned to the WIA service:
            //
            hr = S_OK;
        }
    }

    //
    // Increment the client connection count only when the driver has
    // successfully created all the necessary Driver Item Tree items:
    //
    if (SUCCEEDED(hr))
    {
        *ppIDrvItemRoot = m_pIDrvItemRoot;
        InterlockedIncrement(&m_lClientsConnected);
        WIAS_TRACE((g_hInst,"drvInitializeWia, %d client(s) are currently connected to this driver",  m_lClientsConnected));
    }


    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvInitializeWia 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvInitItemProperties. The WIA service builds the
* Application Item Tree and then asks the driver to initialize each item
* executing IWiaMiniDvr::drvInitItemProperties on each before to hand the
* entire tree over to the application (when completing the IWiaDevMgr::
* CreateDevice or IWiaDevMgr2::CreateDevice call the application makes
* to open a new WIA session). When this method is called the driver is given
* the context of the Application Tree Item to be initialized. The driver must
* populate the item with WIA properties, fully initialized with their names,
* access flags, valid and current values.
*
* This driver supports to create and initialize one of each of the following items:
*
* Root (WIA_CATEGORY_ROOT)
* Flatbed (WIA_CATEGORY_FLATBED, no children)
* Feeder (WIA_CATEGORY_FEEDER, no children)
* Auto (WIA_CATEGORY_AUTO)
* Imprinter (WIA_CATEGORY_IMPRINTER)
* Endorser (WIA_CATEGORY_ENDORSER)
* Barcode Reader (WIA_CATEGORY_BARCODE_READER)
* Patch Code Reader (WIA_CATEGORY_PATCH_CODE_READER)
* MICR Reader (WIA_CATEGORY_MICR_READER)
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvInitItemProperties(
    _Inout_ BYTE* pWiasContext,
            LONG  lFlags,
    _Out_   LONG* plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = S_OK;
    LONG lItemFlags  = 0;

    WIAEX_TRACE_BEGIN;

    if ((!pWiasContext) || (!plDevErrVal))
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    if (SUCCEEDED(hr))
    {
        *plDevErrVal = 0;

        //
        // Read WIA_IPA_ITEM_FLAGS to identify the item to be initialized:
        //
        hr = wiasReadPropLong(pWiasContext, WIA_IPA_ITEM_FLAGS, &lItemFlags, NULL, TRUE);
        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to read WIA_IPA_ITEM_FLAGS property, hr = 0x%08X", hr));
        }
    }

    if (SUCCEEDED(hr))
    {
        if (lItemFlags & WiaItemTypeRoot)
        {
            //
            // This is the Root item, initialize the Root item properties as well as the
            // Root mini-driver item context containing the scan destination names:
            //

            WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for Root.."));

            hr = InitializeRootItemProperties(pWiasContext);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to initialize root item properties, hr = 0x%08X", hr));
            }
        }
        else if ((lItemFlags & WiaItemTypeProgrammableDataSource) &&
            (lItemFlags & WiaItemTypeTransfer) &&
            (lItemFlags & WiaItemTypeFile))
        {
            //
            // This is a child programmable data source item - detect which one from the item name:
            //

            IWiaDrvItem *pIWiaDrvItem = NULL;
            BSTR bstrItemName = NULL;

            hr = wiasGetDrvItem(pWiasContext, &pIWiaDrvItem);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to retrieve the current driver item to initialize, hr = 0x%08X", hr));
            }

            if (SUCCEEDED(hr))
            {
                hr = pIWiaDrvItem->GetItemName(&bstrItemName);
                if (FAILED (hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to get the item name, hr = 0x%08X", hr));
                }
            }

            if (SUCCEEDED(hr))
            {
                if (!wcscmp(WIA_DRIVER_FLATBED_NAME, bstrItemName))
                {
                    WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for Flatbed.."));

                    hr = InitializeChildItemProperties(pWiasContext, FLAT);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to initialize the flatbed item's property set, hr = 0x%08X", hr));
                    }
                }
                else if (!wcscmp(WIA_DRIVER_FEEDER_NAME, bstrItemName))
                {
                    WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for Feeder.."));

                    hr = InitializeChildItemProperties(pWiasContext, FEED);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to initialize the feeder item's property set, hr = 0x%08X", hr));
                    }
                }
                else if (!wcscmp(WIA_DRIVER_AUTO_NAME, bstrItemName))
                {
                    WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for Auto.."));

                    hr = InitializeChildItemProperties(pWiasContext, AUTO_SOURCE);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to initialize the automatic input source item's property set, hr = 0x%08X", hr));
                    }
                }
                else if (!wcscmp(WIA_DRIVER_IMPRINTER_NAME, bstrItemName))
                {
                    WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for Imprinter.."));

                    hr = InitializeChildItemProperties(pWiasContext, IMPRINTER);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to initialize the imprinter item's property set, hr = 0x%08X", hr));
                    }
                }
                else if (!wcscmp(WIA_DRIVER_ENDORSER_NAME, bstrItemName))
                {
                    WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for Endorser.."));

                    hr = InitializeChildItemProperties(pWiasContext, ENDORSER);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to initialize the endorser item's property set, hr = 0x%08X", hr));
                    }
                }
                else if (!wcscmp(WIA_DRIVER_BARCODE_READER_NAME, bstrItemName))
                {
                    WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for Barcode Reader.."));

                    hr = InitializeChildItemProperties(pWiasContext, BARCODE_READER);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to initialize the barcode reader item's property set, hr = 0x%08X", hr));
                    }
                }
                else if (!wcscmp(WIA_DRIVER_PATCH_CODE_READER_NAME, bstrItemName))
                {
                    WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for Patch Code Reader.."));

                    hr = InitializeChildItemProperties(pWiasContext, PATCH_CODE_READER);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to initialize the patch code reader item's property set, hr = 0x%08X", hr));
                    }
                }
                else if (!wcscmp(WIA_DRIVER_MICR_READER_NAME, bstrItemName))
                {
                    WIAS_TRACE((g_hInst,"IWiaMiniDrv::drvInitItemProperties called for MICR Reader.."));

                    hr = InitializeChildItemProperties(pWiasContext, MICR_READER);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to initialize the MICR reader item's property set, hr = 0x%08X", hr));
                    }
                }
                else
                {
                    hr = E_INVALIDARG;
                    WIAEX_ERROR((g_hInst, "Unsupported item (item name: %ws), hr = 0x%08X", bstrItemName, hr));
                }

                if (bstrItemName)
                {
                    SysFreeString(bstrItemName);
                }
            }
        }
        else if (lItemFlags & WiaItemTypeGenerated)
        {
            hr = E_INVALIDARG;
            WIAEX_ERROR((g_hInst, "WiaItemTypeGenerated items are not supported by this driver, hr = 0x%08X", hr));
        }
        else
        {
            hr = E_INVALIDARG;
            WIAEX_ERROR((g_hInst, "Unsupported item (item flags: 0x%X), hr = 0x%08X", lItemFlags, hr));
        }
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvInitItemProperties 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvValidateItemProperties. The WIA Service calls
* IWiaMinIDrv::drvValidateItemProperties for properties that an application
* requested to be changed through a IWiaPropertyStorage::WriteMultiple call.
* The driver should validate each individual set request against the set of
* valid property values in the current context and if validation is successful
* it must update all dependent properties.
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    nPropSpec    - indicates the number of properties in the pPropSpec array
*    pPropSpec    - list of PROPSPEC elements for the properties to be validated
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvValidateItemProperties(
    _Inout_                      BYTE     *pWiasContext,
                                 LONG      lFlags,
                                 ULONG     nPropSpec,
    _In_reads_(nPropSpec) const PROPSPEC *pPropSpec,
    _Out_                        LONG     *plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = S_OK;
    WIA_PROPERTY_CONTEXT PropertyContext = {};
    PROPID *pPropID = NULL;
    BOOL bPropertyContext = FALSE;
    LONG lDocumentHandlingSelect = FLAT;
    LONG lItemType = 0;

    WIAEX_TRACE_BEGIN;

    if ((!pWiasContext) || (!pPropSpec) || (!plDevErrVal) || (!nPropSpec))
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    if (SUCCEEDED(hr))
    {
        *plDevErrVal = 0;

        hr = wiasGetItemType(pWiasContext, &lItemType);
        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to get item type, hr = 0x%08X", hr));
        }
    }

    if (SUCCEEDED(hr))
    {
        if (lItemType & WiaItemTypeRoot)
        {
            //
            // Root item properties for this sample driver do not need any additional validation:
            //
            hr = S_OK;
        }
        else
        {
            GUID guidItemCategory = {};

            //
            // Read WIA_IPA_ITEM_CATEGORY to figure out which child item this is
            // (the item names can be also used for this identification purpose,
            // and should be used if there is more than one item with the same
            // item category):
            //
            hr = wiasReadPropGuid(pWiasContext, WIA_IPA_ITEM_CATEGORY, &guidItemCategory, NULL, TRUE);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Error reading current WIA_IPA_ITEM_CATEGORY, hr = 0x%08X", hr));
            }

            //
            // We need to create an array of property IDs for the properties to be added to the default
            // ones existing in the property context to be built with wiasCreatePropContext
            //
            if (SUCCEEDED(hr))
            {
                pPropID = (PROPID*) CoTaskMemAlloc(sizeof(PROPID) * nPropSpec);
                if (pPropID)
                {
                    for (ULONG i = 0; i < nPropSpec; i++)
                    {
                        pPropID[i] = pPropSpec[i].propid;
                    }
                }
                else
                {
                    hr = E_OUTOFMEMORY;
                    WIAEX_ERROR((g_hInst, "Out of memory, hr = 0x%08X", hr));
                }
            }

            //
            // Create a propery context for the properties being validated:
            //
            if (SUCCEEDED(hr))
            {
                if (IsEqualGUID(WIA_CATEGORY_FLATBED, guidItemCategory))
                {
                    lDocumentHandlingSelect = FLAT;
                }
                else if (IsEqualGUID(WIA_CATEGORY_FEEDER, guidItemCategory))
                {
                    lDocumentHandlingSelect = FEED;
                }
                else if (IsEqualGUID(WIA_CATEGORY_AUTO, guidItemCategory))
                {
                    lDocumentHandlingSelect = AUTO_SOURCE;
                }
                else if (IsEqualGUID(WIA_CATEGORY_IMPRINTER, guidItemCategory))
                {
                    lDocumentHandlingSelect = IMPRINTER;
                }
                else if (IsEqualGUID(WIA_CATEGORY_ENDORSER, guidItemCategory))
                {
                    lDocumentHandlingSelect = ENDORSER;
                }
                else if (IsEqualGUID(WIA_CATEGORY_BARCODE_READER, guidItemCategory))
                {
                    lDocumentHandlingSelect = BARCODE_READER;
                }
                else if (IsEqualGUID(WIA_CATEGORY_PATCH_CODE_READER, guidItemCategory))
                {
                    lDocumentHandlingSelect = PATCH_CODE_READER;
                }
                else if (IsEqualGUID(WIA_CATEGORY_MICR_READER, guidItemCategory))
                {
                    lDocumentHandlingSelect = MICR_READER;
                }

                hr = wiasCreatePropContext(nPropSpec, (PROPSPEC*)pPropSpec, nPropSpec, pPropID, &PropertyContext);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to create WIA property context to validate %u properties, hr = 0x%08X", nPropSpec, hr));
                }
                else
                {
                    bPropertyContext = TRUE;
                }
            }

            //
            // Validate format properties and update as necessary:
            //
            // WIA_IPA_DATATYPE
            // WIA_IPA_DEPTH
            // WIA_IPA_CHANNELS_PER_PIXEL
            // WIA_IPA_BITS_PER_CHANNEL
            // WIA_IPA_FORMAT
            // WIA_IPA_FILENAME_EXTENSION
            // WIA_IPA_TYMED
            // WIA_IPA_COMPRESSION
            //
            if (SUCCEEDED(hr))
            {
                hr = ValidateFormatProperties(pWiasContext, &PropertyContext, lDocumentHandlingSelect);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to validate format properties, hr = 0x%08X", hr));
                }
            }

            if ((FLAT == lDocumentHandlingSelect) || (FEED == lDocumentHandlingSelect))
            {
                //
                // Validate scan region/document size properties:
                //
                // WIA_IPS_PAGE_SIZE
                // WIA_IPS_ORIENTATION
                // WIA_IPS_PAGE_WIDTH
                // WIA_IPS_PAGE_HEIGHT
                // WIA_IPS_XPOS
                // WIA_IPS_YPOS
                // WIA_IPS_XEXTENT
                // WIA_IPS_YEXTENT
                // WIA_IPS_XRES
                // WIA_IPS_YRES
                // WIA_IPS_XSCALING
                // WIA_IPS_YSCALING
                // WIA_IPS_LONG_DOCUMENT
                //
                if (SUCCEEDED(hr))
                {
                    hr = ValidateRegionProperties(pWiasContext, &PropertyContext, lDocumentHandlingSelect);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to validate region properties, hr = 0x%08X", hr));
                    }
                }

                //
                // Validate image information properties:
                //
                // WIA_IPA_PIXELS_PER_LINE
                // WIA_IPA_NUMBER_OF_LINES
                // WIA_IPA_BYTES_PER_LINE
                //
                if (SUCCEEDED(hr))
                {
                    hr = ValidateImageInfoProperties(pWiasContext, &PropertyContext, lDocumentHandlingSelect);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to validate image information properties, hr = 0x%08X", hr));
                    }
                }

                //
                // Validate color drop properties:
                //
                // WIA_IPS_COLOR_DROP_RED
                // WIA_IPS_COLOR_DROP_GREEN and
                // WIA_IPS_COLOR_DROP_BLUE
                //
                if (SUCCEEDED(hr))
                {
                    hr = ValidateColorDropProperties(pWiasContext, &PropertyContext, lDocumentHandlingSelect);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to validate color drop properties, hr = 0x%08X", hr));
                    }
                }

                //
                // Validate other feeder specific properties:
                //
                // WIA_IPS_DOCUMENT_HANDLING_SELECT
                // WIA_IPS_PAGES
                //
                if (SUCCEEDED(hr) && (FEED == lDocumentHandlingSelect))
                {
                    hr = ValidateFeedProperties(pWiasContext, &PropertyContext);
                    if (FAILED(hr))
                    {
                        WIAEX_ERROR((g_hInst, "Failed to validate feeder specific properties, hr = 0x%08X", hr));
                    }
                }
            }
            else if ((IMPRINTER == lDocumentHandlingSelect) || (ENDORSER == lDocumentHandlingSelect))
            {
                hr = ValidateImprinterEndorserProperties(pWiasContext, &PropertyContext, lDocumentHandlingSelect);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to validate imprinter/endorser specific properties, hr = 0x%08X", hr));
                }
            }
            else if (BARCODE_READER == lDocumentHandlingSelect)
            {
                hr = ValidateBarcodeReaderProperties(pWiasContext, &PropertyContext);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to validate barcode reader specific properties, hr = 0x%08X", hr));
                }
            }
            else if (PATCH_CODE_READER == lDocumentHandlingSelect)
            {
                hr = ValidatePatchCodeReaderProperties(pWiasContext, &PropertyContext);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to validate patch code reader specific properties, hr = 0x%08X", hr));
                }
            }
            else if (MICR_READER == lDocumentHandlingSelect)
            {
                hr = ValidateMicrReaderProperties(pWiasContext, &PropertyContext);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to validate MICR reader specific properties, hr = 0x%08X", hr));
                }
            }

            //
            // Validate all changed properties against their (for some of the above properties) updated valid values:
            //
            if (SUCCEEDED(hr))
            {
                hr = wiasValidateItemProperties(pWiasContext, nPropSpec, pPropSpec);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to validate properties using wiasValidateItemProperties, hr = 0x%08X", hr));
                }
            }

            //
            // Free the property context created, if any:
            //
            if (bPropertyContext)
            {
                HRESULT FreePropContextHR = wiasFreePropContext(&PropertyContext);
                if (FAILED(FreePropContextHR))
                {
                    WIAEX_ERROR((g_hInst, "wiasFreePropContext failed, hr = 0x%08X", FreePropContextHR));
                }
            }
        }
    }

    if (pPropID)
    {
        CoTaskMemFree(pPropID);
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvValidateItemProperties 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvWriteItemProperties. When this method is called
* the driver is given the chance to send to the scanner device the settings
* dictated by the current property values.
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    pmdtc        - the device transfer context
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvWriteItemProperties(
    _Inout_  BYTE*                     pWiasContext,
             LONG                      lFlags,
    _In_     PMINIDRV_TRANSFER_CONTEXT pmdtc,
    _Out_    LONG*                     plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = S_OK;
    LONG lItemType = 0;

    WIAEX_TRACE_BEGIN;

    if ((!pWiasContext) || (!pmdtc) || (!plDevErrVal))
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    if (SUCCEEDED(hr))
    {
        *plDevErrVal = 0;

        hr = wiasGetItemType(pWiasContext, &lItemType);
        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to get item type, hr = 0x%08X", hr));
        }
    }

    if (SUCCEEDED(hr) && (lItemType & WiaItemTypeRoot))
    {
        hr = E_FAIL;
        WIAEX_ERROR((g_hInst, "Acquisitions are not supported from the Root item, hr = 0x%08X", hr));
    }

    //
    // Apply to the device the scan settings described by the current WIA property configuration.
    // Note that this is not the best time to ask the scanner device to validate settings: validation
    // should be performed during IWiaMiniDrv/CWiaDriver::drvValidateItemProperties.
    //
    // ...
    //

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvWriteItemProperties 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvReadItemProperties. Reads the device item
* properties. When a client application tries to read a WIA item's properties
* the WIA service will first notify the driver by calling this method.
* The driver should then update any property values that need to be updated
* in real-time from the device every time the application attempts to read
* them (e.g. WIA_DPS_DOCUMENT_HANDLING_STATUS).
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    nPropSpec    - number of properties in pPropSpec array
*    pPropSpec    - list of properties to be read
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvReadItemProperties(
    _In_  BYTE*           pWiasContext,
          LONG            lFlags,
          ULONG           nPropSpec,
    _In_  const PROPSPEC* pPropSpec,
    _Out_ LONG*           plDevErrVal)
{
    UNREFERENCED_PARAMETER(nPropSpec);
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = S_OK;
    LONG lItemFlags  = 0;

    //
    // Omitted on pupose, not really usefull without full property information:
    //
    // WIAEX_TRACE_BEGIN;
    //

    if ((!pWiasContext) || (!pPropSpec) || (!plDevErrVal))
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    if (SUCCEEDED(hr))
    {
        *plDevErrVal = 0;

        hr = wiasReadPropLong(pWiasContext, WIA_IPA_ITEM_FLAGS, &lItemFlags, NULL, TRUE);
        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to read WIA_IPA_ITEM_FLAGS property, hr = 0x%08X", hr));
        }
    }

    if (SUCCEEDED(hr))
    {
        //
        // The following properties require to be updated at run-time:
        //
        // For the Root item:
        //
        // WIA_DPS_DOCUMENT_HANDLING_STATUS  (*)
        // WIA_DPA_CONNECT_STATUS (*)
        // WIA_DPS_SCAN_AVAILABLE_ITEM
        //
        // * - not updated by this sample driver since no HW device connection exists,
        //     but should be updated by a real scanner driver
        //
        // For the Flatbed and Feeder items:
        //
        // None
        //

        if (lItemFlags & WiaItemTypeRoot)
        {
            //
            // Update WIA_DPS_SCAN_AVAILABLE_ITEM with the last globally stored
            // (per driver instance) item name signaled with an unconsumed scan ready event:
            //
            hr = UpdateScanAvailableItemProperty(pWiasContext);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to update the WIA_DPS_SCAN_AVAILABLE_ITEM property (%ws), hr = 0x%08X",
                    m_bstrScanAvailableItem ? m_bstrScanAvailableItem : L"<empty string>", hr));
            }
        }
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvReadItemProperties 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvLockWiaDevice. The IWiaMiniDrv::drvLockWiaDevice
* method locks the hardware device so that only the current minidriver can
* access it. This sample driver returns S_OK without doing anything special.
* Note that the WIA Service expects this method to succeed for a properly
* installed driver and a working scanner device. See also IStiUSD::LockDevice.
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK
*
\**************************************************************************/

HRESULT CWiaDriver::drvLockWiaDevice(
   _In_     BYTE* pWiasContext,
            LONG  lFlags,
   _Out_    LONG* plDevErrVal)
{
    UNREFERENCED_PARAMETER(pWiasContext);
    UNREFERENCED_PARAMETER(lFlags);

    *plDevErrVal = 0;

    return S_OK;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvUnLockWiaDevice. The sample driver returns S_OK.
* The WIA Service expects this method to succeed for a properly installed
* driver and a working scanner device). See also IStiUSD::UnlockDevice.
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK
*
\**************************************************************************/

HRESULT CWiaDriver::drvUnLockWiaDevice(
    _In_  BYTE*  pWiasContext,
          LONG   lFlags,
    _Out_ LONG*  plDevErrVal)
{
    UNREFERENCED_PARAMETER(pWiasContext);
    UNREFERENCED_PARAMETER(lFlags);

    *plDevErrVal = 0;

    return S_OK;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvAnalyzeItem. This sample driver returns
* E_NOTIMPL as it does not support image item analysis.
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    E_NOTIMPL
*
\**************************************************************************/

HRESULT CWiaDriver::drvAnalyzeItem(
    _In_  BYTE*  pWiasContext,
          LONG   lFlags,
    _Out_ LONG*  plDevErrVal)
{
    UNREFERENCED_PARAMETER(pWiasContext);
    UNREFERENCED_PARAMETER(lFlags);

    WIAEX_ERROR((g_hInst, "IWiaMiniDrv::drvAnalyzeItem, this method is not implemented or supported for this driver"));

    m_hrLastEdviceError = STIERR_UNSUPPORTED;

    *plDevErrVal = 0;

    return E_NOTIMPL;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvGetDeviceErrorStr. This driver returns
* E_NOTIMPL because no localized text descriptions of the generic errors
* signaled by IWiaMiniDrv calls are available.
*
* Parameters:
*
*    lFlags           - reserved (set to 0)
*    lDevErrVal       - the device error value to be mapped to a string
*    ppszDevErrStr    - receives the address of a string describing the error
*    plDevErr         - a status code for this method
*
* Return Value:
*
*    E_NOTIMPL
*
\**************************************************************************/

HRESULT CWiaDriver::drvGetDeviceErrorStr(
    LONG            lFlags,
    LONG            lDevErrVal,
    _Out_ LPOLESTR* ppszDevErrStr,
    _Out_ LONG*     plDevErr)
{
    UNREFERENCED_PARAMETER(lFlags);
    UNREFERENCED_PARAMETER(lDevErrVal);

    WIAEX_ERROR((g_hInst, "IWiaMiniDrv::drvGetDeviceErrorStr, this method is not implemented or supported for this driver"));

    if (plDevErr)
    {
        *plDevErr = WIA_ERROR_INVALID_COMMAND;
    }

    if (ppszDevErrStr)
    {
        *ppszDevErrStr = NULL;
    }

    m_hrLastEdviceError = STIERR_UNSUPPORTED;

    return E_NOTIMPL;
}

/**************************************************************************\
*
* Helper for CWiaDriver::drvUnInitializeWia. Destroys the Driver Item Tree.
*
* Parameters:
*
*    None
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::DestroyDriverItemTree()
{
    HRESULT hr = S_OK;

    WIAEX_TRACE_BEGIN;

    //
    // By design the WIA service allows an application to release the Root item at the
    // same time as the WIA service releases the WIA driver object following a device
    // disconnection. If there are no other applications connected to the driver the
    // driver would attempt to unlink and release the Root item concurrently from two
    // different threads - one thread executing IWiaMiniDrv::drvUnInitializeWia, the
    // other thread executing INonDelegating::NonDelegatingRelease:
    //
    EnterCriticalSection(&m_csDestroyDriverItemTree);

    if (m_pIDrvItemRoot)
    {
        WIAS_TRACE((g_hInst,"Unlinking WIA item tree"));

        hr = m_pIDrvItemRoot->UnlinkItemTree(WiaItemTypeDisconnected);
        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to unlink WIA item tree before being released, hr = 0x%08X", hr));
        }

        //
        // Proceed releasing the Root item even if the tree could not be unlinked:
        //

        WIAS_TRACE((g_hInst, "Releasing IDrvItemRoot interface"));

        __try
        {
            m_pIDrvItemRoot->Release();
        }
#pragma prefast(suppress:__WARNING_EXCEPTIONEXECUTEHANDLER, "Note that EXCEPTION_EXECUTE_HANDLER may mask exceptions that may be individually handled otherwise")
        __except (EXCEPTION_EXECUTE_HANDLER)
        {
            hr = WIA_ERROR_ITEM_DELETED;
            WIAEX_ERROR((g_hInst, "Exception 0x%08X when calling Release on the Root item, item no longer valid, hr = 0x%08X",
                GetExceptionCode(), hr));
        }

        m_pIDrvItemRoot = NULL;

        //
        // Keep the current scanner configuration data as well as the transfer format
        // information array initialized after it, until the scanner device signals
        // that the configuration has been changed or the driver is unloaded.
        //
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    LeaveCriticalSection(&m_csDestroyDriverItemTree);

    WIAEX_TRACE_FUNC_HR;

    return hr;
}

/**************************************************************************\
*
* Helper for CWiaDriver::drvInitializeWia. Creates the Driver Item Tree.
* Called during IWiaMiniDrv::drvInitializeWia when no Driver Item Tree exists
* and also during IWiaMiniDrv::drvDeviceCommand for WIA_CMD_SYNCHRONIZE and
* WIA_CMD_BUILD_DEVICE_TREE. Note that the scanner configuration can be read
* for the first time (in this driver session) during IStiUSD::Initialize.
*
* Parameters:
*
*    None
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::BuildDriverItemTree()
{
    HRESULT hr = S_OK;
    BSTR bstrRootItemName = NULL;
    WIA_DRIVER_ITEM_CONTEXT *pWiaDriverItemContext = NULL;

    //
    // All child items implemented by this sample driver except the Auto, Barcode, Patch Code and MICR Reader
    // items, support all item flags as the Flatbed and Feeder items do minus the WiaItemTypeImage flag. The
    // Imprinter and Endorser items support the same item flags as Flatbed and Feeder, including WiaItemTypeImage,
    // since these sample Imprinter and Endorser items support graphics data transfers.
    //
    const LONG lRootItemFlags = WiaItemTypeFolder | WiaItemTypeDevice | WiaItemTypeRoot;
    const LONG lCommonChildItemFlags = WiaItemTypeTransfer | WiaItemTypeFile | WiaItemTypeProgrammableDataSource;

    WIAEX_TRACE_BEGIN;

    //
    // The method creates the Driver Item Tree only if it doesn't exist:
    //
    if (!m_pIDrvItemRoot)
    {
        WIAS_TRACE((g_hInst, "Building Driver Item Tree...."));

        if (!m_bInitialized)
        {
            hr = E_UNEXPECTED;
            WIAEX_ERROR((g_hInst, "Driver not fully initialized, cannot create Driver Item Tree, hr = 0x%08X", hr));
        }

        //
        // Reinitialize the WIA_FORMAT_INFO arrays:
        //
        if (SUCCEEDED(hr))
        {
            hr = InitializeFormatInfoArrays();
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to initialize WIA_FORMAT_INFO array, hr = 0x%08X", hr));
            }
        }

        //
        // Create the default WIA root item. Note that we need item context data for the root item as well as children:
        //

        if (SUCCEEDED(hr))
        {
            bstrRootItemName = SysAllocString(WIA_DRIVER_ROOT_NAME);
            if (!bstrRootItemName)
            {
                hr = E_OUTOFMEMORY;
                WIAEX_ERROR((g_hInst, "Failed to allocate memory for the root item name, hr = 0x%08X", hr));
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = wiasCreateDrvItem(lRootItemFlags, bstrRootItemName, m_bstrRootFullItemName,
                (IWiaMiniDrv*)this, sizeof(WIA_DRIVER_ITEM_CONTEXT),
                (BYTE **)&pWiaDriverItemContext, &m_pIDrvItemRoot);
            if (SUCCEEDED(hr) && ((!pWiaDriverItemContext) || (!m_pIDrvItemRoot)))
            {
                hr = E_POINTER;
            }
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the WIA root item (hr = 0x%08X)", hr));
            }
        }

        //
        // Initialize the item context data for the root item:
        //
        if (SUCCEEDED(hr))
        {
            memset(pWiaDriverItemContext, 0, sizeof(WIA_DRIVER_ITEM_CONTEXT));

            //
            // The Root item is not using this image cache as it does not allow uploads (or download transfers):
            //
            pWiaDriverItemContext->m_pUploadedImage = NULL;
        }

        //
        // Create child items that represent programmable data sources:
        //

        if (SUCCEEDED(hr))
        {
            hr = CreateWIAChildItem(WIA_DRIVER_FLATBED_NAME, (IWiaMiniDrv*)this, m_pIDrvItemRoot,
                WiaItemTypeImage | lCommonChildItemFlags, WIA_CATEGORY_FLATBED, NULL);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the Flatbed item, hr = 0x%08X", hr));
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = CreateWIAChildItem(WIA_DRIVER_FEEDER_NAME, (IWiaMiniDrv*)this, m_pIDrvItemRoot,
                WiaItemTypeImage | lCommonChildItemFlags, WIA_CATEGORY_FEEDER, NULL);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the Feeder item, hr = 0x%08X", hr));
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = CreateWIAChildItem(WIA_DRIVER_AUTO_NAME, (IWiaMiniDrv*)this, m_pIDrvItemRoot,
                lCommonChildItemFlags, WIA_CATEGORY_AUTO, NULL);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the Auto item, hr = 0x%08X", hr));
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = CreateWIAChildItem(WIA_DRIVER_IMPRINTER_NAME, (IWiaMiniDrv*)this, m_pIDrvItemRoot,
                WiaItemTypeImage | lCommonChildItemFlags, WIA_CATEGORY_IMPRINTER, NULL);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the Imprinter item, hr = 0x%08X", hr));
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = CreateWIAChildItem(WIA_DRIVER_ENDORSER_NAME, (IWiaMiniDrv*)this, m_pIDrvItemRoot,
                WiaItemTypeImage | lCommonChildItemFlags, WIA_CATEGORY_ENDORSER, NULL);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the Endorser item, hr = 0x%08X", hr));
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = CreateWIAChildItem(WIA_DRIVER_BARCODE_READER_NAME, (IWiaMiniDrv*)this, m_pIDrvItemRoot,
                lCommonChildItemFlags, WIA_CATEGORY_BARCODE_READER, NULL);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the Barcode Reader item, hr = 0x%08X", hr));
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = CreateWIAChildItem(WIA_DRIVER_PATCH_CODE_READER_NAME, (IWiaMiniDrv*)this, m_pIDrvItemRoot,
                lCommonChildItemFlags, WIA_CATEGORY_PATCH_CODE_READER, NULL);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the Path Code Reader item, hr = 0x%08X", hr));
            }
        }

        if (SUCCEEDED(hr))
        {
            hr = CreateWIAChildItem(WIA_DRIVER_MICR_READER_NAME, (IWiaMiniDrv*)this, m_pIDrvItemRoot,
                lCommonChildItemFlags, WIA_CATEGORY_MICR_READER, NULL);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to create the MICR Reader item, hr = 0x%08X", hr));
            }
        }

        if (bstrRootItemName)
        {
            SysFreeString(bstrRootItemName);
        }
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE_FUNC_HR;

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvDeviceCommand. The method IWiaMiniDrv::
* drvDeviceCommand is called by the WIA service to issue a WIA service
* or application generated command to the driver. The WIA service only
* calls the IWiaMiniDrv::drvDeviceCommand method for a command that the
* driver reports to be supported during IWiaMiniDrv::drvGetCapabilities.
* This driver creates or destroys the Driver Item Tree as requested.
*
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    pguidCommand - WIA command GUID
*    ppWiaDrvItem - always set to NULL (this driver does not need to create
*                   an additional item when a WIA command is executed)
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvDeviceCommand(
    _Inout_ BYTE*         pWiasContext,
            LONG          lFlags,
    _In_    const GUID*   pguidCommand,
    _Out_   IWiaDrvItem** ppWiaDrvItem,
    _Out_   LONG*         plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = S_OK;

    WIAEX_TRACE_BEGIN;

    if ((!pWiasContext) || (!pguidCommand) || (!plDevErrVal))
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    //
    // The following commands are supported by this driver:
    //
    // WIA_CMD_SYNCHRONIZE:        deletes and recreates the Driver Item Tree
    // WIA_CMD_DELETE_DEVICE_TREE: deletes the Driver Item Tree
    // WIA_CMD_BUILD_DEVICE_TREE:  creates the Driver Item Tree
    // WIA_CMD_START_FEEDER:       starts the scanner feeder motor, preparing for scan
    // WIA_CMD_STOP_FEEDER:        stops the scanner feeder motor
    //
    if (SUCCEEDED(hr))
    {
        *plDevErrVal = 0;
        *ppWiaDrvItem = NULL;

        if (IsEqualGUID(WIA_CMD_SYNCHRONIZE, *pguidCommand))
        {
            WIAS_TRACE((g_hInst, "WIA_CMD_SYNCHRONIZE"));

            //
            // Delete the current Driver Item Tree:
            //
            hr = DestroyDriverItemTree();
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to delete the current DIT for WIA_CMD_SYNCHRONIZE, hr = 0x%08X", hr));
            }

            //
            // Re-create the Driver Item Tree according with the current device configuration:
            //
            if (SUCCEEDED(hr))
            {
                hr = BuildDriverItemTree();
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to re-create the DIT for WIA_CMD_SYNCHRONIZE, hr = 0x%08X", hr));
                }

                //
                // Queue tree updated event, regardless of whether BuildDriverItemTree succeeded,
                // since we can't guarantee that the tree was left in the same condition:
                //
                QueueWIAEvent(pWiasContext, WIA_EVENT_TREE_UPDATED);
            }
        }
        else if (IsEqualGUID(WIA_CMD_DELETE_DEVICE_TREE, *pguidCommand))
        {
            WIAS_TRACE((g_hInst, "WIA_CMD_DELETE_DEVICE_TREE"));

            if (!m_pIDrvItemRoot)
            {
                hr = E_FAIL;
                WIAEX_ERROR((g_hInst, "WIA_CMD_DELETE_DEVICE_TREE called when no DIT exists, hr = 0x%08X", hr));
            }

            if (SUCCEEDED(hr))
            {
                hr = DestroyDriverItemTree();
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to delete the current DIT for WIA_CMD_DELETE_DEVICE_TREE, hr = 0x%08X", hr));
                }
            }
        }
        else if (IsEqualGUID(WIA_CMD_BUILD_DEVICE_TREE, *pguidCommand))
        {
            WIAS_TRACE((g_hInst, "WIA_CMD_BUILD_DEVICE_TREE"));

            if (m_pIDrvItemRoot)
            {
                hr = E_FAIL;
                WIAEX_ERROR((g_hInst, "WIA_CMD_BUILD_DEVICE_TREE called when DIT already exists, hr = 0x%08X", hr));
            }

            if (SUCCEEDED(hr))
            {
                hr = BuildDriverItemTree();
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to re-create the DIT for WIA_CMD_BUILD_DEVICE_TREE, hr = 0x%08X", hr));
                }

                //
                // Queue tree updated event, regardless ofwhether BuildDriverItemTree succeeded,
                // since we can't guarantee that the tree was left in the same condition:
                //
                QueueWIAEvent(pWiasContext, WIA_EVENT_TREE_UPDATED);
            }
        }
        else if (IsEqualGUID(WIA_CMD_START_FEEDER, *pguidCommand) || IsEqualGUID(WIA_CMD_STOP_FEEDER, *pguidCommand))
        {
            GUID guidItemCategory = GUID_NULL;
            LONG lFeederMotorControl = WIA_FEEDER_CONTROL_AUTO;

            if (IsEqualGUID(WIA_CMD_START_FEEDER, *pguidCommand))
            {
                WIAS_TRACE((g_hInst, "WIA_CMD_START_FEEDER"));
            }
            else
            {
                WIAS_TRACE((g_hInst, "WIA_CMD_STOP_FEEDER"));
            }

            //
            // The feeder motor commands are valid only on the Feeder item:
            //
            hr = wiasReadPropGuid(pWiasContext, WIA_IPA_ITEM_CATEGORY, &guidItemCategory, NULL, TRUE);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Failed to read WIA_IPA_ITEM_CATEGORY, hr = 0x%08X", hr));
            }

            if (SUCCEEDED(hr) && (!IsEqualGUID(guidItemCategory, WIA_CATEGORY_FEEDER)))
            {
                hr = WIA_ERROR_INVALID_COMMAND;
                WIAEX_ERROR((g_hInst, "WIA_CMD_START/STOP_FEEDER commands are valid only on the Feeder item, hr = 0x%08X", hr));
            }

            //
            // WIA_IPS_FEEDER_CONTROL must be set to WIA_FEEDER_CONTROL_MANUAL:
            //
            if (SUCCEEDED(hr))
            {
                hr = wiasReadPropLong(pWiasContext, WIA_IPS_FEEDER_CONTROL, &lFeederMotorControl, NULL, TRUE);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to read WIA_IPS_FEEDER_CONTROL property, hr = 0x%08X", hr));
                }

                if (SUCCEEDED(hr) && (WIA_FEEDER_CONTROL_MANUAL != lFeederMotorControl))
                {
                    hr = WIA_ERROR_INVALID_COMMAND;
                    WIAEX_ERROR((g_hInst, "WIA_CMD_START/STOP_FEEDER commands are valid only when WIA_IPS_FEEDER_CONTROL is set to WIA_FEEDER_CONTROL_MANUAL, hr = 0x%08X", hr));
                }
            }

            if (SUCCEEDED(hr))
            {
                if (IsEqualGUID(WIA_CMD_START_FEEDER, *pguidCommand))
                {
                    hr = StartFeeder();
                }
                else
                {
                    hr = StopFeeder();
                }
            }
        }
        else
        {
            hr = E_NOTIMPL;
            WIAEX_ERROR((g_hInst, "The requested WIA command is not implemented or supported by this driver"));
        }
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvDeviceCommand 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvGetCapabilities. The WIA service calls
* IWiaMiniDrv::drvGetCapabilities to obtain a list of hardware command
* capabilities and/or STI/WIA device events supported by the driver.
*
* Parameters:
*
*    pWiasContext   - pointer to the item context (may be NULL)
*    lFlags         - reserved (set to 0)
*    pcelt          - receives the number of elements in the array
*                     pointed to by the ppCapabilities parameter
*    ppCapabilities - receives the address of the first element
*                     of an array of WIA_DEV_CAP_DRV structures that
*                     contain the GUIDs of events and commands that
*                     the device supports
*    plDevErrVal    - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK if successful, an error HRESULT otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvGetCapabilities(
   _In_opt_  BYTE*             pWiasContext,
             LONG              ulFlags,
   _Out_     LONG*             pcelt,
   _Out_     WIA_DEV_CAP_DRV** ppCapabilities,
   _Out_     LONG*             plDevErrVal)
{
    UNREFERENCED_PARAMETER(pWiasContext);
    UNREFERENCED_PARAMETER(ulFlags);

    HRESULT hr = S_OK;
    BOOL bAddCapabilities = FALSE;
    BOOL bGetCommands = FALSE;
    BOOL bGetEvents = FALSE;

    WIAEX_TRACE_BEGIN;

    //
    // Note that pWiasContext may be NULL when the driver signals an event
    // before the Driver Item Tree is created and WIA service makes this call.
    // It is also unused so we won't verify it:
    //
    if ((!pcelt) || (!ppCapabilities) || (!plDevErrVal))
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    if (SUCCEEDED(hr))
    {
        *plDevErrVal = 0;
        *pcelt = 0;
        *ppCapabilities = NULL;

        bAddCapabilities = (BOOL)(!m_tCapabilityManager.GetNumCapabilities());
    }

    //
    // Add WIA_EVENT_DEVICE_CONNECTED:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_DEVICE_CONNECTED, IDS_EVENT_DEVICE_CONNECTED_NAME, IDS_EVENT_DEVICE_CONNECTED_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_DEVICE_CONNECTED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_DEVICE_CONNECTED to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_DEVICE_DISCONNECTED:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_DEVICE_DISCONNECTED, IDS_EVENT_DEVICE_DISCONNECTED_NAME,
            IDS_EVENT_DEVICE_DISCONNECTED_DESCRIPTION, WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_DEVICE_DISCONNECTED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_DEVICE_DISCONNECTED to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_POWER_SUSPEND:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_POWER_SUSPEND, IDS_EVENT_POWER_SUSPEND_NAME, IDS_EVENT_POWER_SUSPEND_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_DEVICE_DISCONNECTED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_POWER_SUSPEND to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_POWER_RESUME:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_POWER_RESUME, IDS_EVENT_POWER_RESUME_NAME, IDS_EVENT_POWER_RESUME_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_DEVICE_CONNECTED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_POWER_RESUME to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_TREE_UPDATED:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_TREE_UPDATED, IDS_EVENT_TREE_UPDATED_NAME,
            IDS_EVENT_TREE_UPDATED_DESCRIPTION, WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_TREE_UPDATED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_TREE_UPDATED to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // The sample driver does not signal at run time any of the events initialized below:
    //
    // WIA_EVENT_SCAN_IMAGE
    // WIA_EVENT_DEVICE_NOT_READY
    // WIA_EVENT_DEVICE_READY
    // WIA_EVENT_FLATBED_LID_OPEN
    // WIA_EVENT_FLATBED_LID_CLOSED
    // WIA_EVENT_FEEDER_LOADED
    // WIA_EVENT_FEEDER_EMPTIED
    // WIA_EVENT_COVER_OPEN
    // WIA_EVENT_COVER_CLOSED
    //
    // To signal one of these events, set the m_hWiaEvent and then WIA will issue a IStiUSD::GetNotificationData
    // to receive the GUID of the particular event that is signaled:
    //
    //  if (!SetEvent(m_hWiaEvent))
    //  {
    //      dwErr = ::GetLastError();
    //      hr = HRESULT_FROM_WIN32(dwErr);
    //      if (SUCCEEDED(hr))
    //      {
    //          hr = E_FAIL;
    //      }
    //      WIAEX_ERROR((g_hInst, "SetEvent(WiaEvent) failed (0x%08X), hr = 0x%08X", dwErr, hr));
    //  }
    //
    //

    //
    // Add WIA_EVENT_SCAN_IMAGE:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_SCAN_IMAGE, IDS_EVENT_SCAN_IMAGE_NAME, IDS_EVENT_SCAN_IMAGE_DESCRIPTION,
            WIA_NOTIFICATION_EVENT | WIA_ACTION_EVENT, (LPCWSTR)WIA_ICON_SCAN_BUTTON_PRESS);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_SCAN_IMAGE to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_DEVICE_NOT_READY:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_DEVICE_NOT_READY, IDS_EVENT_DEVICE_NOT_READY_NAME, IDS_EVENT_DEVICE_NOT_READY_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_DEVICE_NOT_READY);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_DEVICE_NOT_READY to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_DEVICE_READY:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_DEVICE_READY, IDS_EVENT_DEVICE_READY_NAME, IDS_EVENT_DEVICE_READY_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_DEVICE_READY);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_DEVICE_READY to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_FLATBED_LID_OPEN:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_FLATBED_LID_OPEN, IDS_EVENT_FLATBED_LID_OPEN_NAME, IDS_EVENT_FLATBED_LID_OPEN_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_FLATBED_LID_OPEN);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_FLATBED_LID_OPEN to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_FLATBED_LID_CLOSED:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_FLATBED_LID_CLOSED, IDS_EVENT_FLATBED_LID_CLOSED_NAME, IDS_EVENT_FLATBED_LID_CLOSED_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_FLATBED_LID_CLOSED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_FLATBED_LID_CLOSED to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_FEEDER_LOADED:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_FEEDER_LOADED, IDS_EVENT_FEEDER_LOADED_NAME, IDS_EVENT_FEEDER_LOADED_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_FEEDER_LOADED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_FEEDER_LOADED to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_FEEDER_EMPTIED:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_FEEDER_EMPTIED, IDS_EVENT_FEEDER_EMPTIED_NAME, IDS_EVENT_FEEDER_EMPTIED_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_FEEDER_EMPTIED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_FEEDER_EMPTIED to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_COVER_OPEN:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_COVER_OPEN, IDS_EVENT_COVER_OPEN_NAME, IDS_EVENT_COVER_OPEN_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_COVER_OPEN);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_COVER_OPEN to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_EVENT_COVER_CLOSED:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_EVENT_COVER_CLOSED, IDS_EVENT_COVER_CLOSED_NAME, IDS_EVENT_COVER_CLOSED_DESCRIPTION,
            WIA_NOTIFICATION_EVENT, (LPCWSTR)WIA_ICON_COVER_CLOSED);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_EVENT_COVER_CLOSED to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_CMD_SYNCRONIZE:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_CMD_SYNCHRONIZE, IDS_CMD_SYNCHRONIZE_NAME,
            IDS_CMD_SYNCHRONIZE_DESCRIPTION, 0, (LPCWSTR)WIA_ICON_SYNCHRONIZE);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_CMD_SYNCHRONIZE to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_CMD_DELETE_DEVICE_TREE:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_CMD_DELETE_DEVICE_TREE, IDS_CMD_DELETE_DEVICE_TREE_NAME,
            IDS_CMD_DELETE_DEVICE_TREE_DESCRIPTION, 0, (LPCWSTR)WIA_ICON_DELETE_DEVICE_TREE);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_CMD_DELETE_DEVICE_TREE to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_CMD_BUILD_DEVICE_TREE:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_CMD_BUILD_DEVICE_TREE, IDS_CMD_BUILD_DEVICE_TREE_NAME,
            IDS_CMD_BUILD_DEVICE_TREE_DESCRIPTION, 0, (LPCWSTR)WIA_ICON_BUILD_DEVICE_TREE);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_CMD_BUILD_DEVICE_TREE to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_CMD_START_FEEDER:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_CMD_START_FEEDER, IDS_CMD_START_FEEDER_NAME,
            IDS_CMD_START_FEEDER_DESCRIPTION, 0, (LPCWSTR)WIA_ICON_START_FEEDER);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_CMD_START_FEEDER to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    //
    // Add WIA_CMD_STOP_FEEDER:
    //
    if (SUCCEEDED(hr) && bAddCapabilities)
    {
        hr = m_tCapabilityManager.AddCapability(WIA_CMD_STOP_FEEDER, IDS_CMD_STOP_FEEDER_NAME,
            IDS_CMD_STOP_FEEDER_DESCRIPTION, 0, (LPCWSTR)WIA_ICON_STOP_FEEDER);

        if (FAILED(hr))
        {
            WIAEX_ERROR((g_hInst, "Failed to add WIA_CMD_STOP_FEEDER to the list of capabilities, hr = 0x%08X", hr));
        }
    }

    if (SUCCEEDED(hr))
    {
        bGetCommands = (BOOL)(WIA_DEVICE_COMMANDS == (ulFlags & WIA_DEVICE_COMMANDS));
        bGetEvents = (BOOL)(WIA_DEVICE_EVENTS == (ulFlags & WIA_DEVICE_EVENTS));

        if ((bGetCommands) && (bGetEvents))
        {
            *ppCapabilities = m_tCapabilityManager.GetCapabilities();
            *pcelt = m_tCapabilityManager.GetNumCapabilities();
            WIAS_TRACE((g_hInst, "drvGetCapabilities, application is asking for Commands and Events, we have %d total capabilities", *pcelt));
        }
        else if (bGetCommands)
        {
            *ppCapabilities = m_tCapabilityManager.GetCommands();
            *pcelt = m_tCapabilityManager.GetNumCommands();
            WIAS_TRACE((g_hInst, "drvGetCapabilities, application is asking for Commands, we have %d", *pcelt));
        }
        else if (bGetEvents)
        {
            *ppCapabilities = m_tCapabilityManager.GetEvents();
            *pcelt = m_tCapabilityManager.GetNumEvents();
            WIAS_TRACE((g_hInst,"drvGetCapabilities, application is asking for Events, we have %d", *pcelt));
        }
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvGetCapabilities 0x%08X (%u events, %u commands)",
        hr, m_tCapabilityManager.GetNumEvents(), m_tCapabilityManager.GetNumCommands()));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvDeleteItem. Deletes a driver item. The items
* supported by this sample driver cannot be deleted by the application.
*
* Parameters:
*
*    pWiasContext - pointer to the item context
*    lFlags       - reserved (set to 0)
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    STG_E_ACCESSDENIED to signal access denied (items cannot be deleted)
*
\**************************************************************************/

HRESULT CWiaDriver::drvDeleteItem(
    _Inout_ BYTE* pWiasContext,
            LONG  lFlags,
    _Out_   LONG* plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);
    UNREFERENCED_PARAMETER(pWiasContext);

    HRESULT hr = STG_E_ACCESSDENIED;

    WIAEX_ERROR((g_hInst, "This item cannot be deleted, hr = 0x%08X", hr));

    m_hrLastEdviceError = hr;

    *plDevErrVal = 0;

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvDeleteItem 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvFreeDrvItemContext. When a driver item is
* deleted, the WIA service frees the driver item context. This method
* informs the driver that the context is ready to be freed. The driver
* must free any memory allocated for the given driver item context.
* The driver won�t support items that can be deleted by the application
* but this method is going to be called by the WIA service the entire
* item tree is released at the end of a session.
*
* Parameters:
*
*    lFlags       - reserved (set to 0)
*    pSpecContext - points to a device-specific context
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK
*
\**************************************************************************/

HRESULT CWiaDriver::drvFreeDrvItemContext(
          LONG    lFlags,
    _In_reads_bytes_(sizeof(WIA_DRIVER_ITEM_CONTEXT))
          BYTE    *pSpecContext,
    _Out_ LONG    *plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    *plDevErrVal = 0;

    WIA_DRIVER_ITEM_CONTEXT *pWiaDriverItemContext = (WIA_DRIVER_ITEM_CONTEXT *)pSpecContext;

    if (pWiaDriverItemContext && pWiaDriverItemContext->m_pUploadedImage)
    {
        pWiaDriverItemContext->m_pUploadedImage->Release();
        pWiaDriverItemContext->m_pUploadedImage = NULL;
    }

    WIAS_TRACE((g_hInst, "IWiaMiniDrv::drvFreeDrvItemContext 0x%08X", S_OK));

    //
    // This method must not fail
    //

    return S_OK;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvGetWiaFormatInfo. This method creates an array
* of WIA_FORMAT_INFO structures that describe the media types and image
* formats that the driver supports.
*
* Parameters:
*
*    pWiasContext - points to a device-specific context
*    lFlags       - reserved (set to 0)
*    pcelt        - receives the number of items in the ppwfi array
*    ppwfi        - array of WIA_FORMAT_INFO structures filled on return
*    plDevErrVal  - always set to 0 by this driver (drvGetDeviceErrorStr unsupported)
*
* Return Value:
*
*    S_OK if succeeds, a standard COM error code otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvGetWiaFormatInfo(
    _In_  BYTE*             pWiasContext,
          LONG              lFlags,
    _Out_ LONG*             pcelt,
    _Out_ WIA_FORMAT_INFO** ppwfi,
    _Out_ LONG*             plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = S_OK;
    GUID guidItemCategory = WIA_CATEGORY_ROOT;
    LONG lNumFormats = 0;
    WIA_FORMAT_INFO *pFormatInfo = NULL;

    WIAEX_TRACE_BEGIN;

    if ((!plDevErrVal) || (!pcelt) || (!ppwfi))
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    if (SUCCEEDED(hr))
    {
        *plDevErrVal = 0;
    }

    if (pWiasContext)
    {
        if (SUCCEEDED(hr))
        {
            hr = wiasReadPropGuid(pWiasContext, WIA_IPA_ITEM_CATEGORY, &guidItemCategory, NULL, TRUE);
            if (FAILED(hr))
            {
                WIAEX_ERROR((g_hInst, "Error reading current WIA_IPA_ITEM_CATEGORY, hr = 0x%08X", hr));
            }
        }

        //
        // This method is allowed to be called only on a transfer capable child item:
        //
        if (SUCCEEDED(hr))
        {
            if (IsEqualGUID(WIA_CATEGORY_FEEDER, guidItemCategory))
            {
                WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for the Feeder..", hr));
            }
            else if (IsEqualGUID(WIA_CATEGORY_FLATBED, guidItemCategory))
            {
                WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for the Flatbed..", hr));
            }
            else if (IsEqualGUID(WIA_CATEGORY_AUTO, guidItemCategory))
            {
                WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for the Auto image source..", hr));
            }
            else if (IsEqualGUID(WIA_CATEGORY_IMPRINTER, guidItemCategory))
            {
                WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for the Imprinter..", hr));
            }
            else if (IsEqualGUID(WIA_CATEGORY_ENDORSER, guidItemCategory))
            {
                WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for the Endorser..", hr));
            }
            else if (IsEqualGUID(WIA_CATEGORY_BARCODE_READER, guidItemCategory))
            {
                WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for the Barcode Reader..", hr));
            }
            else if (IsEqualGUID(WIA_CATEGORY_PATCH_CODE_READER, guidItemCategory))
            {
                WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for the Patch Code Reader..", hr));
            }
            else if (IsEqualGUID(WIA_CATEGORY_MICR_READER, guidItemCategory))
            {
                WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for the MICR Reader..", hr));
            }
            else
            {
                if (IsEqualGUID(WIA_CATEGORY_ROOT, guidItemCategory))
                {
                    WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for Root..", hr));
                }
                else
                {
                    WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for an unknown item, assuming Root..", hr));
                }
                guidItemCategory = WIA_CATEGORY_ROOT;
            }
        }
    }
    else
    {
        WIAS_TRACE((g_hInst, "drvGetWiaFormatInfo called for a NULL item context, assuming Root..", hr));
        guidItemCategory = WIA_CATEGORY_ROOT;
    }

    //
    // Check the number of available formats
    //
    if (SUCCEEDED(hr))
    {
        //
        // Note that the format info arrays are initialized on IStiUSD::Initialize
        // so they may be available even before the Driver Item Tree is created:
        //
        if (IsEqualGUID(WIA_CATEGORY_FEEDER, guidItemCategory) ||
            IsEqualGUID(WIA_CATEGORY_FLATBED, guidItemCategory) ||
            IsEqualGUID(WIA_CATEGORY_AUTO, guidItemCategory) ||
            IsEqualGUID(WIA_CATEGORY_ROOT, guidItemCategory))
        {
            lNumFormats = m_tFormatInfo.Size();
            pFormatInfo = (WIA_FORMAT_INFO *)m_tFormatInfo.Array();
        }
        else if (IsEqualGUID(WIA_CATEGORY_IMPRINTER, guidItemCategory) ||
            IsEqualGUID(WIA_CATEGORY_ENDORSER, guidItemCategory))
        {
            lNumFormats = m_tFormatInfoImprinterEndorser.Size();
            pFormatInfo = (WIA_FORMAT_INFO *)m_tFormatInfoImprinterEndorser.Array();
        }
        else if (IsEqualGUID(WIA_CATEGORY_BARCODE_READER, guidItemCategory))
        {
            lNumFormats = m_tFormatInfoBarcodeReader.Size();
            pFormatInfo = (WIA_FORMAT_INFO *)m_tFormatInfoBarcodeReader.Array();
        }
        else if (IsEqualGUID(WIA_CATEGORY_PATCH_CODE_READER, guidItemCategory))
        {
            lNumFormats = m_tFormatInfoPatchCodeReader.Size();
            pFormatInfo = (WIA_FORMAT_INFO *)m_tFormatInfoPatchCodeReader.Array();
        }
        else if (IsEqualGUID(WIA_CATEGORY_MICR_READER, guidItemCategory))
        {
            lNumFormats = m_tFormatInfoMicrReader.Size();
            pFormatInfo = (WIA_FORMAT_INFO *)m_tFormatInfoMicrReader.Array();
        }

        if ((!lNumFormats) || (!pFormatInfo))
        {
            hr = E_FAIL;
            WIAEX_ERROR((g_hInst, "Unexpected, the format array must be initialized first, hr = 0x%08X", hr));
        }
    }

    //
    // Return the requested list:
    //
    if (SUCCEEDED(hr))
    {
        *pcelt = lNumFormats;
        *ppwfi = pFormatInfo;
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvGetWiaFormatInfo 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvNotifyPnpEvent. The WIA service notifies the
* driver of a supported PnP system event by calling this method.
* A real driver could respond to these events for example by releasing and
* redoing its connection with the Hardware device (and possibly signaling
* to a locally connected device that it can enter or resume power saving itself)
* when the computer goes into and exists stand-by and hibernation.
*
* The driver must check the pEventGUID parameter to determine what event
* is being processed. The events that are processed by the driver are:
*
* WIA_EVENT_POWER_SUSPEND       - system is going to suspend/sleep mode
* WIA_EVENT_POWER_RESUME        - system is waking up from suspend/sleep mode
* WIA_EVENT_DEVICE_DISCONNECTED - device is disconnected, driver will be unloaded
* WIA_EVENT_CANCEL_IO           - pending IO is being cancelled
*
* The driver does not execute any special action on the following events:
*
* WIA_EVENT_DEVICE_CONNECTED (*)- driver initialization is being done on IStiUSD::Initialize
*
* (* - The driver logs a trace message following WIA_EVENT_DEVICE_CONNECTED
*      and ensures the current device connection state is correctly recorded)
*
* Parameters:
*
*    pEventGUI    - GUID identifying the event
*    bstrDeviceID - string containing the device's unique identifier
*    ulReserved   - reserved for system use
*
* Return Value:
*
*    S_OK if succeeds, a standard COM error code otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvNotifyPnpEvent(
    _In_ const GUID* pEventGUID,
    _In_ BSTR        bstrDeviceID,
         ULONG       ulReserved)
{
    UNREFERENCED_PARAMETER(ulReserved);

    HRESULT hr = S_OK;

    WIAEX_TRACE_BEGIN;

    if (!pEventGUID)
    {
        hr = E_INVALIDARG;
        WIAEX_ERROR((g_hInst, "Invalid parameter, hr = 0x%08X", hr));
    }

    if (SUCCEEDED(hr))
    {
        if (bstrDeviceID)
        {
            WIAS_TRACE((g_hInst, "PnP event notification received for device ID %ws", bstrDeviceID));
        }

        if (WIA_EVENT_POWER_SUSPEND == *pEventGUID)
        {
            WIAS_TRACE((g_hInst, "WIA_EVENT_POWER_SUSPEND"));

            //
            // Disable WIA events:
            //
            SetNotificationHandle(NULL);
        }
        else if (WIA_EVENT_POWER_RESUME == *pEventGUID)
        {
            WIAS_TRACE((g_hInst, "WIA_EVENT_POWER_RESUME"));

            if ((!m_hWiaEventStoredCopy) || (INVALID_HANDLE_VALUE == m_hWiaEventStoredCopy))
            {
                hr = E_UNEXPECTED;
                WIAEX_ERROR((g_hInst, "Failed to re-enable WIA events for WIA_EVENT_POWER_RESUME, invalid event handle, hr = 0x%08X", hr));
            }

            if (SUCCEEDED(hr))
            {
                //
                // Re-enable WIA events:
                //
                hr = SetNotificationHandle(m_hWiaEventStoredCopy);
                if (FAILED(hr))
                {
                    WIAEX_ERROR((g_hInst, "Failed to re-enable WIA events on WIA_EVENT_POWER_RESUME, hr = 0x%08X", hr));
                }
            }
        }
        else if (WIA_EVENT_DEVICE_CONNECTED == *pEventGUID)
        {
            WIAS_TRACE((g_hInst, "WIA_EVENT_DEVICE_CONNECTED"));

            //
            // When the driver receives this event the driver is already loaded and initialized
            // and a new driver object is already created. Ensure the correct connection state
            // is recorded  - note that this is not required  as when the driver is reloaded
            // SetDeviceConnected(TRUE) is already executed from within the CWiaDriver
            // constructor when the new driver object instance is created.
            //
        }
        else if (WIA_EVENT_DEVICE_DISCONNECTED == *pEventGUID)
        {
            WIAS_TRACE((g_hInst, "WIA_EVENT_DEVICE_DISCONNECTED"));

            //
            // The driver is notified that the scanner device is disconnected and that the WIA
            // service will soon unload the driver. The device communication interface will be
            // uninitialized when the driver will be unloaded. The SetDeviceConnected(FALSE) call
            // below will record the current state so when the device communication interface will
            // be uninitialized (when the driver object will be released by the WIA service before
            // unloading the driver) the driver won't log excessive errors to the WIA trace log
            // when device  operation requests will fail because the device won't be available):
            //

            //
            // Disable WIA events:
            //
            SetNotificationHandle(NULL);
        }
        else if (WIA_EVENT_CANCEL_IO == *pEventGUID)
        {
            WIAS_TRACE((g_hInst, "WIA_EVENT_CANCEL_IO"));
        }
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvNotifyPnpEvent 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Implements IWiaMiniDrv::drvUnInitializeWia. The WIA service calls the
* IWiaMiniDrv::drvUnInitializeWia method when the resources associated
* with an application item tree are no longer needed. The driver must
* free all resources allocated for this application session.
*
* Parameters:
*
*    pWiasContext - points to a device-specific context
*
* Return Value:
*
*    S_OK if succeeds, a standard COM error code otherwise
*
\**************************************************************************/

HRESULT CWiaDriver::drvUnInitializeWia(
    _Inout_ BYTE* pWiasContext)
{
    HRESULT hr = S_OK;

    WIAEX_TRACE_BEGIN;

    //
    // Watch out to not prematurely fail this request... we must
    // succeed freeing resources when this is called no matter what.
    //

    if (InterlockedDecrement(&m_lClientsConnected) < 0)
    {
        WIAS_TRACE((g_hInst,
            "drvUnInitializeWia, the client connection counter decremented below zero. Assuming no clients are currently connected and automatically setting to 0"));
        m_lClientsConnected = 0;
    }

    WIAS_TRACE((g_hInst, "drvUnInitializeWia, %d client(s) are currently connected to this driver",  m_lClientsConnected));

    if (!m_lClientsConnected)
    {
        //
        // When the last client disconnects, destroy the WIA item tree.
        // This should reduce the idle memory foot print of this driver:
        //
        DestroyDriverItemTree();
    }

    if (!pWiasContext)
    {
        WIAEX_ERROR((g_hInst, "drvUnInitializeWia called with NULL item context parameter (!!!); still, request completed, hr = 0x%08X", hr));
    }

    if (FAILED(hr))
    {
        m_hrLastEdviceError = hr;
    }

    WIAEX_TRACE((g_hInst, "IWiaMiniDrv::drvUnInitializeWia 0x%08X", hr));

    return hr;
}

/**************************************************************************\
*
* Helper for CWiaDriver::drvDeviceCommand.Starts the scanner feeder.
*
* Parameters:
*
*    None
*
* Return Value:
*
*    S_OK if successful or an error HRESULT otherwise
*
\**************************************************************************/

HRESULT
CWiaDriver::StartFeeder()
{
    HRESULT hr = S_OK;

    if (!m_bFeederStarted)
    {
        //
        // Start feeder
        //
        // ...
        //

        m_bFeederStarted = TRUE;
        WIAS_TRACE((g_hInst, "Feeder started"));
    }

    return hr;
}

/**************************************************************************\
*
* Helper for CWiaDriver::drvDeviceCommand.Stops the scanner feeder.
*
* Parameters:
*
*    None
*
* Return Value:
*
*    S_OK if successful or an error HRESULT otherwise
*
\**************************************************************************/

HRESULT
CWiaDriver::StopFeeder()
{
    HRESULT hr = S_OK;

    if (m_bFeederStarted)
    {
        //
        // Stop feeder
        //
        // ...
        //

        m_bFeederStarted = FALSE;
        WIAS_TRACE((g_hInst, "Feeder stopped"));
    }

    return hr;
}