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

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <initguid.h>
#include "stdafx.h"
#include <strsafe.h>
#include <limits.h>

HINSTANCE g_hInst = NULL;

///////////////////////////////////////////////////////////////////////////////
// WIA driver GUID
///////////////////////////////////////////////////////////////////////////////

// {EEA1E6F7-A59C-487a-BFFA-BD8AA99FE501}
DEFINE_GUID(CLSID_WIADriver, 0xeea1e6f7, 0xa59c, 0x487a, 0xbf, 0xfa, 0xbd, 0x8a, 0xa9, 0x9f, 0xe5, 0x3);

#define HANDLED_PRIVATE_STATUS_ERROR_1      MAKE_HRESULT(SEVERITY_ERROR,   FACILITY_ITF, 1001)
#define UNHANDLED_PRIVATE_STATUS_ERROR_1    MAKE_HRESULT(SEVERITY_ERROR,   FACILITY_ITF, 1002)
#define UNHANDLED_PRIVATE_STATUS_MESSAGE_1  MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_ITF, 1001)


///////////////////////////////////////////////////////////////////////////
// Construction/Destruction Section
///////////////////////////////////////////////////////////////////////////

CWIADriver::CWIADriver(_In_opt_ LPUNKNOWN punkOuter) : m_cRef(1),
    m_punkOuter(NULL),
    m_pIDrvItemRoot(NULL),
    m_lClientsConnected(0),
    m_pFormats(NULL),
    m_ulNumFormats(0),
    m_bstrDeviceID(NULL),
    m_bstrRootFullItemName(NULL),
    m_ulImageLibraryToken(0),
    m_pIStiDevice(NULL)
{
    if(punkOuter)
    {
        m_punkOuter = punkOuter;
    }
    else
    {
        m_punkOuter = reinterpret_cast<IUnknown*>(static_cast<INonDelegatingUnknown*>(this));
    }

    memset(m_wszStoragePath,0,sizeof(m_wszStoragePath));

    //
    // Intialize GDI+ image library for image manipulation
    //

    Gdiplus::GdiplusStartupInput gdiplusStartupInput;
    if(GdiplusStartup(&m_ulImageLibraryToken, &gdiplusStartupInput, NULL) != Gdiplus::Ok)
    {
        WIAS_ERROR((g_hInst, "GDI+ image library could not be initialized"));
    }
}

CWIADriver::~CWIADriver()
{
    if(m_bstrDeviceID)
    {
        SysFreeString(m_bstrDeviceID);
        m_bstrDeviceID = NULL;
    }

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

    //
    // Free cached driver capability array
    //

    m_CapabilityManager.Destroy();

    //
    // Free cached driver format array
    //

    if(m_pFormats)
    {
        WIAS_TRACE((g_hInst,"Deleting WIA format array memory"));
        delete [] m_pFormats;
        m_pFormats = NULL;
        m_ulNumFormats = 0;
    }

    //
    // Unlink and release the cached IWiaDrvItem root item interface.
    //

    DestroyDriverItemTree();

    //
    // Unintialize/shutdown GDI+ image library
    //

    if(m_ulImageLibraryToken)
    {
        Gdiplus::GdiplusShutdown(m_ulImageLibraryToken);
        m_ulImageLibraryToken = 0;
    }
}

///////////////////////////////////////////////////////////////////////////
// Standard COM Section
///////////////////////////////////////////////////////////////////////////

HRESULT CWIADriver::QueryInterface(REFIID riid, _COM_Outptr_ LPVOID * ppvObj)
{
    if (ppvObj == NULL)
    {
        return E_INVALIDARG;
    }
    *ppvObj = NULL;

    if(!m_punkOuter)
    {
        return E_NOINTERFACE;
    }
    return m_punkOuter->QueryInterface(riid,ppvObj);
}
ULONG CWIADriver::AddRef()
{
    if(!m_punkOuter)
    {
        return 0;
    }
    return m_punkOuter->AddRef();
}
ULONG CWIADriver::Release()
{
    if(!m_punkOuter)
    {
        return 0;
    }
    return m_punkOuter->Release();
}

///////////////////////////////////////////////////////////////////////////
// IStiUSD Interface Section (for all WIA drivers)
///////////////////////////////////////////////////////////////////////////

HRESULT CWIADriver::Initialize(_In_     PSTIDEVICECONTROL pHelDcb,
                                        DWORD             dwStiVersion,
                               _In_     HKEY              hParametersKey)
{
    UNREFERENCED_PARAMETER(dwStiVersion);

    HRESULT hr = E_INVALIDARG;
    if((pHelDcb)&&(hParametersKey))
    {
        //
        // Open DeviceData section in the registry
        //

        HKEY hDeviceDataKey = NULL;
        if(RegOpenKeyEx(hParametersKey,REG_ENTRY_DEVICEDATA,0,KEY_QUERY_VALUE|KEY_READ,&hDeviceDataKey) == ERROR_SUCCESS)
        {
            DWORD dwSize = sizeof(m_wszStoragePath);
            DWORD dwType = REG_SZ;
            if(RegQueryValueEx(hDeviceDataKey,REG_ENTRY_STORAGEPATH,NULL,&dwType,(BYTE*)m_wszStoragePath,&dwSize) == ERROR_SUCCESS)
            {
                WIAS_TRACE((g_hInst,"WIA storage path = %ws",m_wszStoragePath));
                hr = S_OK;
            }
            else
            {
                WIAS_ERROR((g_hInst, "Failed to read (%ws) entry under %ws section of device registry",REG_ENTRY_STORAGEPATH,REG_ENTRY_DEVICEDATA));
            }

            hr = S_OK;

            //
            // close open DeviceData registry key
            //

            RegCloseKey(hDeviceDataKey);
            hDeviceDataKey = NULL;
        }

        hr = m_CapabilityManager.Initialize(g_hInst);
        if(FAILED(hr))
        {
            WIAS_ERROR((g_hInst, "Failed to initialize the WIA driver capability manager object, hr = 0x%lx",hr));
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

HRESULT CWIADriver::GetCapabilities(_Out_ PSTI_USD_CAPS pDevCaps)
{
    HRESULT hr = E_INVALIDARG;
    if(pDevCaps)
    {
        memset(pDevCaps, 0, sizeof(STI_USD_CAPS));
        pDevCaps->dwVersion     = STI_VERSION_3;
        pDevCaps->dwGenericCaps = STI_GENCAP_WIA                    |
                                  STI_USD_GENCAP_NATIVE_PUSHSUPPORT |
                                  STI_GENCAP_NOTIFICATIONS          |
                                  STI_GENCAP_POLLING_NEEDED;

        WIAS_TRACE((g_hInst,"========================================================"));
        WIAS_TRACE((g_hInst,"STI Capabilities information reported to the WIA Service"));
        WIAS_TRACE((g_hInst,"Version:     0x%lx",pDevCaps->dwVersion));
        WIAS_TRACE((g_hInst,"GenericCaps: 0x%lx", pDevCaps->dwGenericCaps));
        WIAS_TRACE((g_hInst,"========================================================"));

        hr = S_OK;
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

HRESULT CWIADriver::GetStatus(_Inout_ PSTI_DEVICE_STATUS pDevStatus)
{
    HRESULT hr = E_INVALIDARG;
    if(pDevStatus)
    {
        //
        // assume successful status checks
        //

        hr = S_OK;

        if(pDevStatus->StatusMask & STI_DEVSTATUS_ONLINE_STATE)
        {
            //
            // check if the device is ON-LINE
            //

            WIAS_TRACE((g_hInst,"Checking device online status..."));
            pDevStatus->dwOnlineState = 0L;

            if(SUCCEEDED(hr))
            {
                pDevStatus->dwOnlineState |= STI_ONLINESTATE_OPERATIONAL;
                WIAS_TRACE((g_hInst,"The device is online"));
            }
            else
            {
                WIAS_TRACE((g_hInst,"The device is offline"));
            }
        }

        if(pDevStatus->StatusMask & STI_DEVSTATUS_EVENTS_STATE)
        {
            //
            // check for polled events
            //

            pDevStatus->dwEventHandlingState &= ~STI_EVENTHANDLING_PENDING;

            hr = S_FALSE; // no are events detected

            if(hr == S_OK)
            {
                pDevStatus->dwEventHandlingState |= STI_EVENTHANDLING_PENDING;
                WIAS_TRACE((g_hInst,"The device reported a polled event"));
            }
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}
HRESULT CWIADriver::DeviceReset()
{
    return S_OK;
}
HRESULT CWIADriver::Diagnostic(_Out_ LPDIAG pBuffer)
{
    HRESULT hr = E_INVALIDARG;
    if(pBuffer)
    {
        memset(pBuffer,0,sizeof(DIAG));
        hr = S_OK;
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}
HRESULT CWIADriver::Escape(                              STI_RAW_CONTROL_CODE EscapeFunction,
                           _In_reads_bytes_(cbInDataSize)     LPVOID               lpInData,
                                                         DWORD                cbInDataSize,
                           _Out_writes_bytes_(dwOutDataSize)   LPVOID               pOutData,
                                                         DWORD                dwOutDataSize,
                           _Out_                         LPDWORD              pdwActualData)
{
    UNREFERENCED_PARAMETER(EscapeFunction);
    UNREFERENCED_PARAMETER(lpInData);
    UNREFERENCED_PARAMETER(cbInDataSize);
    UNREFERENCED_PARAMETER(pOutData);
    UNREFERENCED_PARAMETER(dwOutDataSize);
    UNREFERENCED_PARAMETER(pdwActualData);

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}
HRESULT CWIADriver::GetLastError(_Out_ LPDWORD pdwLastDeviceError)
{
    HRESULT hr = E_INVALIDARG;
    if(pdwLastDeviceError)
    {
        *pdwLastDeviceError = 0;
        hr = S_OK;
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}
HRESULT CWIADriver::LockDevice()
{
    return S_OK;
}
HRESULT CWIADriver::UnLockDevice()
{
    return S_OK;
}
HRESULT CWIADriver::RawReadData(_Out_writes_bytes_(*lpdwNumberOfBytes)      LPVOID       lpBuffer,
                                _Out_                                 LPDWORD      lpdwNumberOfBytes,
                                _Out_                                 LPOVERLAPPED lpOverlapped)
{
    UNREFERENCED_PARAMETER(lpBuffer);
    UNREFERENCED_PARAMETER(lpdwNumberOfBytes);
    UNREFERENCED_PARAMETER(lpOverlapped);

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}
HRESULT CWIADriver::RawWriteData(_In_reads_bytes_(dwNumberOfBytes)    LPVOID       lpBuffer,
                                                                 DWORD        dwNumberOfBytes,
                                                                 _Out_ LPOVERLAPPED lpOverlapped)
{
    UNREFERENCED_PARAMETER(lpBuffer);
    UNREFERENCED_PARAMETER(dwNumberOfBytes);
    UNREFERENCED_PARAMETER(lpOverlapped);

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}
HRESULT CWIADriver::RawReadCommand(_Out_writes_bytes_(*lpdwNumberOfBytes) LPVOID       lpBuffer,
                                   _Out_                            LPDWORD      lpdwNumberOfBytes,
                                   _Out_                            LPOVERLAPPED lpOverlapped)
{
    UNREFERENCED_PARAMETER(lpBuffer);
    UNREFERENCED_PARAMETER(lpdwNumberOfBytes);
    UNREFERENCED_PARAMETER(lpOverlapped);

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}
HRESULT CWIADriver::RawWriteCommand(_In_reads_bytes_(dwNumberOfBytes) LPVOID       lpBuffer,
                                                                 DWORD        dwNumberOfBytes,
                                                                 _Out_ LPOVERLAPPED lpOverlapped)
{
    UNREFERENCED_PARAMETER(lpBuffer);
    UNREFERENCED_PARAMETER(dwNumberOfBytes);
    UNREFERENCED_PARAMETER(lpOverlapped);

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}

HRESULT CWIADriver::SetNotificationHandle(_In_ HANDLE hEvent)
{
    UNREFERENCED_PARAMETER(hEvent);

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}
HRESULT CWIADriver::GetNotificationData(_In_ LPSTINOTIFY lpNotify)
{
    UNREFERENCED_PARAMETER(lpNotify);

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}
HRESULT CWIADriver::GetLastErrorInfo(_Out_ STI_ERROR_INFO *pLastErrorInfo)
{
    HRESULT hr = E_INVALIDARG;
    if(pLastErrorInfo)
    {
        memset(pLastErrorInfo,0,sizeof(STI_ERROR_INFO));
        hr = S_OK;
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

/////////////////////////////////////////////////////////////////////////
// IWiaMiniDrv Interface Section (for all WIA drivers)                 //
/////////////////////////////////////////////////////////////////////////

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(lFlags);
    UNREFERENCED_PARAMETER(pIUnknownOuter);

    HRESULT hr = S_OK;
    if((pWiasContext)&&(plDevErrVal)&&(ppIDrvItemRoot))
    {
        *plDevErrVal = 0;
        *ppIDrvItemRoot = NULL;
        *ppIUnknownInner = NULL;

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

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

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

        if(SUCCEEDED(hr))
        {
            if(!m_pIDrvItemRoot)
            {
                hr = BuildDriverItemTree();
            }
            else
            {

                //
                // A WIA item tree already exists.  The root item of this item tree
                // should be returned to the WIA service.
                //

                hr = S_OK;
            }
        }

        //
        // Make PREfast happy by inspecting m_pIDrvItemRoot.
        // PREfast doesn't seem to figure out that m_pIDrvItemRoot is set by
        // BuildDriverTree()'s call to waisCreateDrvItem() only on success.
        //

        if(SUCCEEDED(hr) && !m_pIDrvItemRoot)
        {
            hr = E_UNEXPECTED;
            WIAS_ERROR((g_hInst, "Missing driver item tree root unexpected, hr = 0x%lx",hr));
        }

        //
        // Only increment the client connection count, when the driver
        // has successfully created all the necessary WIA items for
        // a client to use.
        //

        if(SUCCEEDED(hr))
        {
            *ppIDrvItemRoot = m_pIDrvItemRoot;
            InterlockedIncrement(&m_lClientsConnected);
            WIAS_TRACE((g_hInst,"%d client(s) are currently connected to this driver.",m_lClientsConnected));
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

UINT CWIADriver::GetBitmapResourceIDFromCategory(const GUID &guidItemCategory)
{
    UINT uiBitmapResourceID = 0;

    if (guidItemCategory == WIA_CATEGORY_FLATBED)
    {
        uiBitmapResourceID = IDB_FLATBED;
    }
    else if (guidItemCategory == WIA_CATEGORY_FEEDER)
    {
        uiBitmapResourceID = IDB_FEEDER;
    }
    else if (guidItemCategory == WIA_CATEGORY_FILM)
    {
        uiBitmapResourceID = IDB_FILM;
    }
    else
    {
        uiBitmapResourceID = IDB_FLATBED;
    }

    return uiBitmapResourceID;
}


/*++

Routine Name:        CWIADriver::DownloadRawHeader

Routine Description: Builds and downloads to the specified ouput stream the WIA Raw Format header.
                     It should be called only from within CWIADriver::DownloadToStream
                     after WiaDevice::InitializeForDownload was executed
Arguments:
                     pDestination      - the output stream (same as used in DownloadToStream)
                     pWiasContext      - WIA service context, passed by caller (DownloadToStream)
                     pmdtc             - the stream WIA mini-driver context (see DownloadToStream)

Return Value:
                     HRESULT (S_OK in case the operation succeeds)
Last Error:
                     -
++*/
HRESULT
CWIADriver::DownloadRawHeader(
    _In_    IStream                     *pDestination,
    _Inout_ BYTE                        *pWiasContext,
    _In_    PMINIDRV_TRANSFER_CONTEXT   pmdtc
    )
{
    HRESULT hr = S_OK;
    LONG lValue = 0;
    WIA_RAW_HEADER& RawHeader = m_WiaDevice.m_RawHeader;

    //
    // Verify input parameters:
    //
    if((!pDestination) || (!pmdtc))
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameter(s) for DownloadRawHeader, hr: 0x%X", hr));
    }

    if(S_OK == hr)
    {
        //
        // The 'WRAW' 4 ASCII character signature is required at the begining of all WIA Raw transfers:
        //
        const char szSignature[] = "WRAW";
        memcpy(&RawHeader.Tag, szSignature, sizeof(DWORD));

        //
        // Fill in the fields describing version identity for this header:
        //
        RawHeader.Version = 0x00010000;
        RawHeader.HeaderSize = sizeof(WIA_RAW_HEADER);

        //
        // Fill in all the fields that we can retrieve directly from the current MINIDRV_TRANSFER_CONTEXT:
        //
        RawHeader.XRes = pmdtc->lXRes;
        RawHeader.YRes = pmdtc->lYRes;
        RawHeader.XExtent = pmdtc->lWidthInPixels;
        RawHeader.YExtent = pmdtc->lLines;
        RawHeader.BitsPerPixel = pmdtc->lDepth;
        RawHeader.Compression = pmdtc->lCompression;

        //
        // Raw data: the offset is the size of the header (we don't have a color palette in this case):
        //
        RawHeader.RawDataOffset = RawHeader.HeaderSize;

        //
        // Notes:
        //
        // RawHeader.RawDataSize is filled in already by CWiaDevice::InitializeForDownload
        // Same for RawHeader.BytesPerLine.
        //
    }

    //
    // The remaining fields have to be filled in reading the rescctive current property values:
    //

    //
    // The pixel/data type is described by WIA_IPA_FORMAT:
    //
    if(S_OK == hr)
    {
        hr = wiasReadPropLong(pWiasContext, WIA_IPA_FORMAT, &lValue, NULL, true);
        if(S_OK == hr)
        {
            RawHeader.DataType = lValue;
        }
        else
        {
            WIAS_ERROR((g_hInst, "wiasReadPropLong(WIA_IPA_FORMAT) failed, hr: 0x%X", hr));
        }
    }

    //
    // The number of channels per pixel is described by WIA_IPA_CHANNELS_PER_PIXEL:
    //
    if(S_OK == hr)
    {
        hr = wiasReadPropLong(pWiasContext, WIA_IPA_CHANNELS_PER_PIXEL, &lValue, NULL, true);
        if(S_OK == hr)
        {
            RawHeader.ChannelsPerPixel = lValue;
        }
        else
        {
            WIAS_ERROR((g_hInst, "wiasReadPropLong(WIA_IPA_CHANNELS_PER_PIXEL) failed, hr: 0x%X", hr));
        }
    }

    //
    // The photometric interpretation is described by WIA_IPS_PHOTOMETRIC_INTERP:
    //
    if(S_OK == hr)
    {
        hr = wiasReadPropLong(pWiasContext, WIA_IPS_PHOTOMETRIC_INTERP, &lValue, NULL, true);
        if(S_OK == hr)
        {
            RawHeader.PhotometricInterp = lValue;
        }
        else
        {
            WIAS_ERROR((g_hInst, "wiasReadPropLong(WIA_IPS_PHOTOMETRIC_INTERP) failed, hr: 0x%X", hr));
        }
    }

    //
    // The discrete bits per channel table is described by the new WIA_IPA_RAW_BITS_PER_CHANNEL:
    //
    if(S_OK == hr)
    {
        memset(&RawHeader.BitsPerChannel[0], 0, sizeof(RawHeader.BitsPerChannel));

        PROPSPEC ps;
        ps.ulKind = PRSPEC_PROPID;
        ps.propid = WIA_IPA_RAW_BITS_PER_CHANNEL;
        PROPVARIANT pv = {0};

        hr = wiasReadMultiple(pWiasContext, 1, &ps, &pv, NULL);
        if(S_OK == hr)
        {
            ULONG ulItemCount = (pv.caub.cElems > 8) ? 8 : pv.caub.cElems;
            for(ULONG i = 0; i < ulItemCount; i++)
            {
                RawHeader.BitsPerChannel[i] = *(BYTE *)((BYTE *)pv.caub.pElems + i * sizeof(BYTE));
            }
        }
    }

    //
    // In the case of this sample the image data is retrieved from a resource bitmap.
    //
    // Important: this bitmap must be initialized by the WiaDevice::InitializeForDownload
    // before calling this function.
    //
    if(S_OK == hr)
    {
        if(!m_WiaDevice.InitializedForDownload())
        {
            //
            // S_FALSE returned from this function would be interpreted as a cancel request:
            //
            hr = E_INVALIDARG;
            WIAS_ERROR((g_hInst, "Bitmap not initialized correctly, hr: 0x%X", hr));
        }
    }

    if(S_OK == hr)
    {
        //
        // For the line order use the BitmapData object initialized for the sample bitmap that
        // we are using: the "Stride" field value sign indicates the line order:
        //
        RawHeader.LineOrder = ((m_WiaDevice.GetBitmapData())->Stride < 0) ?
            WIA_LINE_ORDER_BOTTOM_TO_TOP : WIA_LINE_ORDER_TOP_TO_BOTTOM;

        //
        // We won't be using a color palette here but it would be possible to try to retrieve
        // the color palette, if any, from the DIB header describing the sample bitmap:
        //
        RawHeader.PaletteSize = 0;
        RawHeader.PaletteOffset = 0;
    }

    //
    // Write the header to the stream provided to us:
    //
    ULONG ulBytesWritten = 0;
    if(S_OK == hr)
    {
        hr = pDestination->Write(&RawHeader, RawHeader.HeaderSize, &ulBytesWritten);
    }

    return hr;
}



HRESULT CWIADriver::DownloadToStream(           LONG                           lFlags,
                                     _In_       BYTE                           *pWiasContext,
                                     _In_       PMINIDRV_TRANSFER_CONTEXT      pmdtc,
                                     const      GUID                           &guidItemCategory,
                                     const      GUID                           &guidFormatID,
                                     __callback IWiaMiniDrvTransferCallback    *pTransferCallback,
                                     _Out_      LONG                           *plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr                  = S_OK;
    BSTR    bstrItemName        = NULL;
    BSTR    bstrFullItemName    = NULL;
    UINT    uiBitmapResourceID  = GetBitmapResourceIDFromCategory(guidItemCategory);

    if (plDevErrVal)
    {
        *plDevErrVal = 0;
    }

    //
    // A maximum of 10 image transfers (including final and preview scans) can be requested
    // from the Feeder item before the driver will return WIA_ERROR_PAPER_EMPTY. In order to
    // reset the counter (used only for the Feeder item) the application must change a Feeder
    // item property current value or reload the driver.
    //
    // IMPORTANT:
    //
    // Legacy WIA applications such as Scan Wizard requires WIA_ERROR_PAPER_EMPTY
    // (as the return code for IWiaMiniDrv::drvAcquireItemData) in order to stop
    // normally a Feeder acquisition sequence.
    //
    WIA_DRIVER_ITEM_CONTEXT *pWiaDriverItemContext = NULL;
    hr = wiasGetDriverItemPrivateContext(pWiasContext, (BYTE**)&pWiaDriverItemContext);
    if ((!pWiaDriverItemContext) && (SUCCEEDED(hr)))
    {
        hr = E_POINTER;
    }
    if (FAILED(hr))
    {
        WIAS_ERROR((g_hInst, "Failed to get private driver item context data, hr = 0x%lx", hr));
    }

    const ULONG ulMaxTransfers = 10;
    if ((SUCCEEDED(hr)) && (IsEqualGUID(WIA_CATEGORY_FEEDER, guidItemCategory)))
    {
        //
        // Limit the number of "continuous" transfers from the Feeder item -
        // without this Scan Wizard would not stop requesting transfers:
        //
        if (pWiaDriverItemContext->ulFeederTransferCount >= ulMaxTransfers)
        {
            hr = WIA_ERROR_PAPER_EMPTY;
        }
    }

    if (S_OK == hr)
    {
        //  Get the item name
        hr = wiasReadPropStr(pWiasContext, WIA_IPA_ITEM_NAME, &bstrItemName, NULL, TRUE);
        if (SUCCEEDED(hr))
        {
            //  Get the full item name
            hr = wiasReadPropStr(pWiasContext, WIA_IPA_FULL_ITEM_NAME, &bstrFullItemName, NULL, TRUE);
            if (SUCCEEDED(hr))
            {
                //  Get the destination stream
                IStream *pDestination = NULL;
                _Analysis_assume_nullterminated_(bstrItemName);
                hr = pTransferCallback->GetNextStream(0, bstrItemName, bstrFullItemName, &pDestination);
                if (hr == S_OK)
                {
                    WiaTransferParams *pParams = (WiaTransferParams*)CoTaskMemAlloc(sizeof(WiaTransferParams));
                    if (pParams)
                    {
                        memset(pParams, 0, sizeof(WiaTransferParams));
                        BYTE    *pBuffer        = NULL;
                        ULONG   ulBufferSize    = 0;
                        hr = AllocateTransferBuffer(pWiasContext, &pBuffer, &ulBufferSize);
                        if (SUCCEEDED(hr))
                        {
                            if ((S_OK == hr) && (guidItemCategory != WIA_CATEGORY_FINISHED_FILE) && (WIA_CATEGORY_FOLDER != guidItemCategory))
                            {
                                LONG    lErrorHandling = ERROR_HANDLING_NONE;

                                hr = wiasReadPropLong(pWiasContext, MY_WIA_ERROR_HANDLING_PROP, &lErrorHandling, NULL, TRUE);

                                BOOL    bSendWarmingUpMsg       = lErrorHandling & ERROR_HANDLING_WARMING_UP;
                                BOOL    bSendCoverOpenMsg       = lErrorHandling & ERROR_HANDLING_COVER_OPEN;
                                BOOL    bSendPrivateErrorMsg    = lErrorHandling & ERROR_HANDLING_PRIVATE_ERROR;
                                BOOL    bSendUnhandledStatusMsg = lErrorHandling & ERROR_HANDLING_UNHANDLED_STATUS;
                                BOOL    bSendUnhandledErrorMsg  = lErrorHandling & ERROR_HANDLING_UNHANDLED_ERROR;

                                //  We need to initialize our device object for each item we transfer.
                                //  Each item may have it's own selection area, data type and so on.
                                hr = m_WiaDevice.InitializeForDownload(pWiasContext,
                                                                    g_hInst,
                                                                    uiBitmapResourceID,
                                                                    guidFormatID);

                                if ((S_OK == hr) && bSendWarmingUpMsg)
                                {
                                    //
                                    // Send non-modal warming up message. To be catched by default UI
                                    // unless application handles it (WiaPreview does not handle this
                                    // message).
                                    //
                                    // Sending "update messages" makes it possible for a user to cancel transfer
                                    // and also for an error handler to provide progress dialog.
                                    //
                                    for (int i = 0; i < 10 ; i++)
                                    {
                                        pParams->lMessage           = WIA_TRANSFER_MSG_DEVICE_STATUS;
                                        pParams->hrErrorStatus      = WIA_STATUS_WARMING_UP;
                                        pParams->lPercentComplete   = i * 10;
                                        pParams->ulTransferredBytes = 0;

                                        hr = pTransferCallback->SendMessage(0, pParams);

                                        if (S_OK != hr)
                                        {
                                            break;
                                        }

                                        Sleep(500);
                                    }
                                }

                                if (S_OK == hr)
                                {
                                    BOOL    bProblemFixed = FALSE;

                                    //  Data transfer loop
                                    //  Read from device
                                    ULONG   ulBytesRead         = 0;
                                    LONG    lPercentComplete    = 0;

                                    if (bSendUnhandledStatusMsg)
                                    {
                                        //
                                        // Send "special" unhandled status message
                                        //
                                        pParams->lMessage           = WIA_TRANSFER_MSG_DEVICE_STATUS;
                                        pParams->hrErrorStatus      = UNHANDLED_PRIVATE_STATUS_MESSAGE_1;
                                        pParams->lPercentComplete   = 0;
                                        pParams->ulTransferredBytes = 0;

                                        hr = pTransferCallback->SendMessage(0, pParams);
                                    }

                                    if ((S_OK == hr) && bSendUnhandledErrorMsg)
                                    {

                                        //
                                        // Since none handles this device error it will cause our transfer to be
                                        // be aborted.
                                        //
                                        pParams->lMessage           = WIA_TRANSFER_MSG_DEVICE_STATUS;
                                        pParams->hrErrorStatus      = UNHANDLED_PRIVATE_STATUS_ERROR_1;
                                        pParams->lPercentComplete   = 0;
                                        pParams->ulTransferredBytes = 0;

                                        hr = pTransferCallback->SendMessage(0, pParams);
                                    }

                                    if ((S_OK == hr) && bSendCoverOpenMsg)
                                    {
                                        pParams->lMessage           = WIA_TRANSFER_MSG_DEVICE_STATUS;
                                        pParams->hrErrorStatus      = WIA_ERROR_COVER_OPEN;
                                        pParams->lPercentComplete   = 0;
                                        pParams->ulTransferredBytes = 0;

                                        hr = pTransferCallback->SendMessage(0, pParams);
                                    }

                                    //
                                    // If this is a Raw format transfer we should transfer the raw header first.
                                    // WiaDevice::InitializeForDownload suceedeed and it is safe to execute
                                    // now DownloadRawHeader:
                                    //
                                    if((S_OK == hr) && (IsEqualGUID(guidFormatID, WiaImgFmt_RAW)))
                                    {
                                        hr = DownloadRawHeader(pDestination, pWiasContext, pmdtc);

                                        if(S_OK == hr)
                                        {
                                            WIA_RAW_HEADER& RawHeader = m_WiaDevice.m_RawHeader;
                                            lPercentComplete  = (LONG)((((float)RawHeader.HeaderSize /
                                                (float)(RawHeader.RawDataSize + RawHeader.HeaderSize + RawHeader.PaletteSize))) * 100.0f);

                                            pParams->lMessage            = WIA_TRANSFER_MSG_STATUS;
                                            pParams->lPercentComplete    = lPercentComplete;
                                            pParams->ulTransferredBytes += RawHeader.HeaderSize;

                                            hr = pTransferCallback->SendMessage(0, pParams);
                                        }
                                    }

                                    while((S_OK == hr) &&
                                        ((hr = m_WiaDevice.GetNextBand(pBuffer, ulBufferSize, &ulBytesRead, &lPercentComplete, guidFormatID)) == S_OK))
                                    {
                                        ULONG   ulBytesWritten = 0;
                                        LARGE_INTEGER li = {0};

                                        //
                                        // Write to stream after seeking to end of stream as it could
                                        // be randomized intially or during the callback
                                        //
                                        hr = pDestination->Seek(li, STREAM_SEEK_END, NULL);

                                        if (S_OK == hr)
                                        {
                                            hr = pDestination->Write(pBuffer, ulBytesRead, &ulBytesWritten);
                                        }

                                        if (S_OK == hr)
                                        {
                                            //
                                            // Make progress callback
                                            //
                                            pParams->lMessage            = WIA_TRANSFER_MSG_STATUS;
                                            pParams->lPercentComplete    = lPercentComplete;
                                            pParams->ulTransferredBytes += ulBytesWritten;

                                            hr = pTransferCallback->SendMessage(0, pParams);
                                            if (FAILED(hr))
                                            {
                                                WIAS_ERROR((g_hInst, "Failed to send progress notification during download, hr = 0x%lx",hr));
                                                break;
                                            }
                                            else if (S_FALSE == hr)
                                            {
                                                //
                                                // Transfer cancelled
                                                //
                                                break;
                                            }
                                            else if (S_OK != hr)
                                            {
                                                WIAS_ERROR((g_hInst, "SendMessage returned unknown Success value, hr = 0x%lx",hr));
                                                hr = E_UNEXPECTED;
                                                break;
                                            }

                                            if ((lPercentComplete > 50) && !bProblemFixed)
                                            {

                                                if (bSendPrivateErrorMsg)
                                                {
                                                    //
                                                    // Send "special" driver status message that only our error handling extension knows about
                                                    //
                                                    pParams->lMessage                       = WIA_TRANSFER_MSG_DEVICE_STATUS;
                                                    pParams->hrErrorStatus                  = HANDLED_PRIVATE_STATUS_ERROR_1;

                                                    hr = pTransferCallback->SendMessage(0, pParams);
                                                }

                                                if (S_OK == hr)
                                                {
                                                    bProblemFixed = TRUE;
                                                }
                                            }
                                        }
                                    }

                                    if ((pWiaDriverItemContext) && (IsEqualGUID(WIA_CATEGORY_FEEDER, guidItemCategory)))
                                    {
                                        //
                                        // Increment the feeder transfer counter for both preview and final scans:
                                        //
                                        if (pWiaDriverItemContext->ulFeederTransferCount < ulMaxTransfers)
                                        {
                                            pWiaDriverItemContext->ulFeederTransferCount += 1;
                                        }
                                    }

                                    if (WIA_STATUS_END_OF_MEDIA == hr)
                                    {
                                        hr = S_OK;
                                    }

                                    m_WiaDevice.UninitializeForDownload();
                                }
                                else
                                {
                                    WIAS_ERROR((g_hInst, "Failed to initialize device for download, hr = 0x%lx",hr));
                                }
                            }
                            else
                            {
                                IStream *pStorageDataStream = NULL;

                                hr = SHCreateStreamOnFile(pWiaDriverItemContext->bstrStorageDataPath,STGM_READ,&pStorageDataStream);

                                if(SUCCEEDED(hr))
                                {
                                    STATSTG statstg = {0};
                                    ULONG ulTotalBytesToWrite = 0;

                                    hr = pStorageDataStream->Stat(&statstg,  STATFLAG_NONAME);

                                    if (SUCCEEDED(hr))
                                    {
                                        ulTotalBytesToWrite = statstg.cbSize.LowPart;

                                        if (!ulTotalBytesToWrite)
                                        {
                                            hr = E_UNEXPECTED;
                                            WIAS_ERROR((g_hInst, "Storage item has zero size, hr = %#x", hr));
                                        }
                                    }

                                    if (SUCCEEDED(hr))
                                    {
                                        ULONG ulBytesRead      = 0;
                                        ULONG ulTotalBytesWritten = 0;
                                        LONG  lPercentComplete = -1;

                                        while((SUCCEEDED(pStorageDataStream->Read(pBuffer, ulBufferSize, &ulBytesRead)) && ulBytesRead))
                                        {
                                            //
                                            // Write to stream
                                            //
                                            ULONG   ulBytesWritten = 0;
                                            hr = pDestination->Write(pBuffer, ulBytesRead, &ulBytesWritten);

                                            if (SUCCEEDED(hr))
                                            {
                                                ulTotalBytesWritten += ulBytesWritten;
                                                lPercentComplete = (LONG)((((float)ulTotalBytesWritten/(float)ulTotalBytesToWrite)) * 100.0f);

                                                //
                                                // Make progress callback
                                                //
                                                pParams->lMessage            = WIA_TRANSFER_MSG_STATUS;
                                                pParams->lPercentComplete    = lPercentComplete;
                                                pParams->ulTransferredBytes += ulBytesWritten;

                                                hr = pTransferCallback->SendMessage(0, pParams);
                                                if (hr != S_OK)
                                                {
                                                    if (FAILED(hr))
                                                    {
                                                        WIAS_ERROR((g_hInst, "Failed to send progress notification during download, hr = 0x%lx",hr));
                                                    }
                                                    else if (S_FALSE == hr)
                                                    {
                                                        WIAS_TRACE((g_hInst, "Download was cancelled"));
                                                    }
                                                    else
                                                    {
                                                        WIAS_ERROR((g_hInst, "SendMessage returned unknown Success value, hr = 0x%lx",hr));
                                                        hr = E_UNEXPECTED;
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                    }

                                    pStorageDataStream->Release();
                                    pStorageDataStream = NULL;
                                }
                                else
                                {
                                    WIAS_ERROR((g_hInst, "Failed to create a source stream on storage item data content file (%ws), hr = 0x%lx",pWiaDriverItemContext->bstrStorageDataPath,hr));
                                }
                            }
                            FreeTransferBuffer(pBuffer);
                        }
                        else
                        {
                            WIAS_ERROR((g_hInst, "Failed to allocate memory for transfer buffer, hr = 0x%lx",hr));
                        }
                        CoTaskMemFree(pParams);
                        pParams = NULL;
                    }
                    else
                    {
                        hr = E_OUTOFMEMORY;
                        WIAS_ERROR((g_hInst, "Failed to allocate memory for WiaTransferParams structure, hr = 0x%lx",hr));
                    }
                    pDestination->Release();
                    pDestination = NULL;
                }
                else if(!((S_FALSE == hr) || (WIA_STATUS_SKIP_ITEM == hr)))
                {
                    WIAS_ERROR((g_hInst, "GetNextStream returned unknown Success value, hr = 0x%lx",hr));
                    hr = E_UNEXPECTED;
                }
                else
                {
                    WIAS_ERROR((g_hInst, "Failed to get the destination stream for download, hr = 0x%lx",hr));
                }

                SysFreeString(bstrFullItemName);
                bstrFullItemName = NULL;
            }
            else
            {
                WIAS_ERROR((g_hInst, "Failed to read the WIA_IPA_FULL_ITEM_NAME property, hr = 0x%lx",hr));
            }
            SysFreeString(bstrItemName);
            bstrItemName = NULL;
        }
        else
        {
            WIAS_ERROR((g_hInst, "Failed to read the WIA_IPA_ITEM_NAME property, hr = 0x%lx",hr));
        }
    }
    return hr;
}

HRESULT CWIADriver::UploadFromStream(           LONG                           lFlags,
                                     _In_       BYTE                           *pWiasContext,
                                                const GUID                     &guidItemCategory,
                                     __callback IWiaMiniDrvTransferCallback    *pTransferCallback,
                                     _Out_      LONG                           *plDevErrVal)
{
    UNREFERENCED_PARAMETER(guidItemCategory);

    HRESULT hr = S_OK;
    BSTR bstrItemName = NULL;
    BSTR bstrFullItemName = NULL;

    if (plDevErrVal)
    {
        *plDevErrVal = 0;
    }

    //  Get the item name
    hr = wiasReadPropStr(pWiasContext, WIA_IPA_ITEM_NAME, &bstrItemName, NULL, TRUE);
    if (SUCCEEDED(hr))
    {
        //  Get the full item name
        hr = wiasReadPropStr(pWiasContext, WIA_IPA_FULL_ITEM_NAME, &bstrFullItemName, NULL, TRUE);
        if (SUCCEEDED(hr))
        {
            //  Get the source stream
            IStream *pSourceStream = NULL;
            _Analysis_assume_nullterminated_(bstrItemName);
            hr = pTransferCallback->GetNextStream(lFlags, bstrItemName, bstrFullItemName, &pSourceStream);
            if (S_OK == hr)
            {
                hr = wiasReadPropStr(pWiasContext,WIA_IPA_ITEM_NAME,&bstrItemName,NULL,TRUE);
                if(SUCCEEDED(hr))
                {
                    STATSTG statstg = {0};

                    hr = pSourceStream->Stat(&statstg, STATFLAG_NONAME);
                    if(SUCCEEDED(hr))
                    {
                        WiaTransferParams *pParams = (WiaTransferParams*)CoTaskMemAlloc(sizeof(WiaTransferParams));
                        if (pParams)
                        {
                            memset(pParams, 0, sizeof(WiaTransferParams));

                            hr = m_WiaDevice.Upload(bstrItemName, statstg.cbSize.LowPart, pSourceStream,pTransferCallback, pParams,m_wszStoragePath);
                            if(SUCCEEDED(hr))
                            {
                                // Succeeded with upload.  We expect the App to do a synchronize to get the new items,
                                // so there's nothing further we need to do.

                                //
                                // TBD: Ideal case would be to create a WIA driver item, and link it to the existing
                                //      application item.  This will also be the place that a item created/added event
                                //      would be sent to the other clients, allowing them to reenumerate and pick up the
                                //      freshly uploaded item.
                                //
                            }
                            else
                            {
                                WIAS_ERROR((g_hInst, "Failed to upload data to the device, hr = 0x%lx",hr));
                            }

                            CoTaskMemFree(pParams);
                            pParams = NULL;
                        }
                        else
                        {
                            hr = E_OUTOFMEMORY;
                            WIAS_ERROR((g_hInst, "Failed to allocate memory for WiaTransferParams structure, hr = 0x%lx",hr));
                        }
                    }
                    else
                    {
                        WIAS_ERROR((g_hInst, "Failed to call IStream::Stat on application provided stream, hr = 0x%lx",hr));
                    }
                    SysFreeString(bstrItemName);
                    bstrItemName = NULL;
                }
                else
                {
                    WIAS_ERROR((g_hInst, "Failed to read WIA_IPA_ITEM_NAME property, hr = 0x%lx",hr));
                }

                pSourceStream->Release();
                pSourceStream = NULL;
            }
            else if(!((S_FALSE == hr) ||(WIA_STATUS_SKIP_ITEM == hr)))
            {
                WIAS_ERROR((g_hInst, "GetNextStream returned unknown Success value, hr = 0x%lx",hr));
                hr = E_UNEXPECTED;
            }
            else
            {
                WIAS_ERROR((g_hInst, "Failed to get the source stream for upload, hr = 0x%lx",hr));
            }

            SysFreeString(bstrFullItemName);
            bstrFullItemName = NULL;
        }
        else
        {
            WIAS_ERROR((g_hInst, "Failed to read the WIA_IPA_FULL_ITEM_NAME property, hr = 0x%lx",hr));
        }
        SysFreeString(bstrItemName);
        bstrItemName = NULL;
    }
    else
    {
        WIAS_ERROR((g_hInst, "Failed to read the WIA_IPA_ITEM_NAME property, hr = 0x%lx",hr));
    }

    return hr;
}

HRESULT CWIADriver::drvAcquireItemData(_In_    BYTE                      *pWiasContext,
                                               LONG                      lFlags,
                                       _In_    PMINIDRV_TRANSFER_CONTEXT pmdtc,
                                       _Out_   LONG                      *plDevErrVal)
{
    HRESULT hr                  = E_INVALIDARG;
    GUID    guidItemCategory    = GUID_NULL;
    GUID    guidFormatID        = GUID_NULL;

    if((pWiasContext)&&(pmdtc)&&(plDevErrVal))
    {
        *plDevErrVal = 0;

        //
        // Read the current transfer format that we are requested to use:
        //
        guidFormatID = pmdtc->guidFormatID;

        //
        // Read the WIA item category, to decide which data transfer handler should
        // be used.
        //
        hr = wiasReadPropGuid(pWiasContext,WIA_IPA_ITEM_CATEGORY,&guidItemCategory,NULL,TRUE);
        if (SUCCEEDED(hr))
        {
            //
            //  Check what kind of data transfer is requested.  This driver
            //  supports 2 transfer modes:
            //  1.  Stream-based download
            //  2.  Stream-based upload
            //

            if (lFlags & WIA_MINIDRV_TRANSFER_DOWNLOAD)
            {
                // This is stream-based download
                IWiaMiniDrvTransferCallback *pTransferCallback = NULL;
                hr = GetTransferCallback(pmdtc, &pTransferCallback);
                if (SUCCEEDED(hr))
                {
                    LONG lStreamsToDownload = 0;
                    LONG lStreamCount = 0;

                    if (!IsEqualGUID(guidItemCategory, WIA_CATEGORY_FEEDER))
                    {
                        lStreamsToDownload = 1;
                    }
                    else
                    {
                        hr = wiasReadPropLong(pWiasContext, WIA_IPS_PAGES, &lStreamsToDownload, NULL, TRUE);
                        if (FAILED(hr))
                        {
                            WIAS_ERROR((g_hInst, "drvAcquireItemData: failure reading WIA_IPS_PAGES property for Feeder item, hr = 0x%lx", hr));
                        }
                        else if (ALL_PAGES == lStreamsToDownload)
                        {
                            //
                            // When WIA_IPS_PAGES is set to 0 (ALL_PAGES) meaning "scan as many documents
                            // as there may be loaded into the feeder"
                            // We assume 5 pages are in feeder
                            //
                            lStreamsToDownload = 5;
                        }
                    }

                    //
                    // We support only TYMED_FILE for WIA_IPA_TYMED so we should call DownloadToStream
                    // for each individual image transfer. If WIA_IPA_TYMED would support and would be
                    // set to TYMED_MULTIPAGE_FILE then all images acquired in a continous sequence should
                    // be transferred to the same strem (GetNextStream called just once):
                    //
                    while ((SUCCEEDED(hr)) && (lStreamCount < lStreamsToDownload))
                    {
                        //
                        // DownloadToStream writes its own trace message in case of failure:
                        //
                        hr = DownloadToStream(lFlags, pWiasContext, pmdtc, guidItemCategory, guidFormatID, pTransferCallback, plDevErrVal);
                        lStreamCount++;
                    }

                    pTransferCallback->Release();
                    pTransferCallback = NULL;
                }
                else
                {
                    WIAS_ERROR((g_hInst, "Could not get our IWiaMiniDrvTransferCallback for download"));
                }
            }
            else if (lFlags & WIA_MINIDRV_TRANSFER_UPLOAD)
            {
                //
                // We only want to do "Upload" if category of the item is WIA_CATEGORY_FINISHED_FILE and it is not the root storage item:
                //
                LONG    lItemType = 0;

                hr = wiasGetItemType(pWiasContext,&lItemType);
                if (SUCCEEDED(hr))
                {
                    if ((guidItemCategory == WIA_CATEGORY_FINISHED_FILE) && !(lItemType & WiaItemTypeStorage))
                    {
                        // This is stream-based upload
                        IWiaMiniDrvTransferCallback *pTransferCallback = NULL;
                        hr = GetTransferCallback(pmdtc, &pTransferCallback);
                        if (SUCCEEDED(hr))
                        {
                            hr = UploadFromStream(lFlags, pWiasContext, guidItemCategory, pTransferCallback, plDevErrVal);
                            pTransferCallback->Release();
                            pTransferCallback = NULL;
                        }
                        else
                        {
                            WIAS_ERROR((g_hInst, "Could not get our IWiaMiniDrvTransferCallback for upload"));
                        }
                    }
                    else
                    {
                        hr = E_INVALIDARG;
                        WIAS_ERROR((g_hInst, "Cannot do Upload to selected item, hr = 0x%lx",hr));
                    }
                }
                else
                {
                    WIAS_ERROR((g_hInst, "Failed to get the WIA item type, hr = 0x%lx",hr));
                }
            }
            else
            {
                // This should not happen!
                hr = E_INVALIDARG;
            }
        }
        else
        {
            WIAS_ERROR((g_hInst, "Failed to read the WIA_IPA_ITEM_CATEGORY property, hr = 0x%lx",hr));
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}
HRESULT CWIADriver::drvInitItemProperties(_Inout_   BYTE *pWiasContext,
                                                    LONG lFlags,
                                          _Out_     LONG *plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr          = E_INVALIDARG;
    LONG    lItemFlags  = 0;
    if((pWiasContext)&&(plDevErrVal))
    {
        *plDevErrVal = 0;

        //
        // Initialize individual storage item properties using the CWIAStorage object
        //
        hr = wiasReadPropLong(pWiasContext,WIA_IPA_ITEM_FLAGS,&lItemFlags,NULL,TRUE);
        if(SUCCEEDED(hr))
        {
            if((lItemFlags & WiaItemTypeRoot))
            {
                //
                // Add any root item properties needed.
                //
                hr = InitializeRootItemProperties(pWiasContext);
                if(FAILED(hr))
                {
                    WIAS_ERROR((g_hInst, "Failed to initialize generic WIA root item properties, hr = 0x%lx",hr));
                }
            }
            else
            {
                //
                // Add any non-root item properties needed.
                //
                GUID guidItemCategory = GUID_NULL;

                //
                // Use the WIA category setting to determine what type of property
                // set should be created for this WIA item.
                //
                if((lItemFlags & WiaItemTypeGenerated) == FALSE)
                {
                    //
                    // Item is not a generated item, assume that this was created by this WIA driver
                    // and the WIA_ITEM_CATEGORY setting can be read from the WIA_DRIVER_ITEM_CONTEXT
                    // structure stored with the WIA driver item.
                    //

                    WIA_DRIVER_ITEM_CONTEXT *pWiaDriverItemContext = NULL;
                    hr = wiasGetDriverItemPrivateContext(pWiasContext,(BYTE**)&pWiaDriverItemContext);
                    if(SUCCEEDED(hr) && (pWiaDriverItemContext))
                    {
                        guidItemCategory = pWiaDriverItemContext->guidItemCategory;
                    }
                    else
                    {
                        //
                        // This WIA item has no item context and will receive default item
                        // property initialization.  This allows applications to create child items
                        // for storing private data.
                        // NOTE: Data transfers on these types of items will probably not succeed since
                        //       the driver does not have a category to help classify the behavior of the
                        //       item.
                        //
                        hr = S_OK;
                    }
                }
                else
                {
                    //
                    // Read the parents WIA_ITEM_CATEGORY property setting to determine this new
                    // child item's category setting.
                    //

                    BYTE *pWiasParentContext = NULL;
                    hr = wiasGetAppItemParent(pWiasContext,&pWiasParentContext);
                    if(SUCCEEDED(hr))
                    {
                        hr = wiasReadPropGuid(pWiasParentContext,WIA_IPA_ITEM_CATEGORY,&guidItemCategory,NULL,TRUE);
                        if(FAILED(hr))
                        {
                            WIAS_TRACE((g_hInst,"The item does not have a category property setting. Assuming that it is unknown."));
                            //
                            // This WIA item has no item category property setting and will receive default item
                            // property initialization.  This allows applications to create child items
                            // for storing private data.
                            // NOTE: Data transfers on these types of items will probably not succeed since
                            //       the driver does not have a category to help classify the behavior of the
                            //       item.
                            //
                            hr = S_OK;
                        }
                    }
                    else
                    {
                        WIAS_ERROR((g_hInst, "Failed to obtain the WIA application item's parent, hr = 0x%lx",hr));
                    }
                }

                if(SUCCEEDED(hr))
                {
                    //
                    // Initialize the WIA item property set according to the category specified
                    //

                    if(guidItemCategory == WIA_CATEGORY_FLATBED)
                    {
                        //
                        // We do not support folder items to be created under the flatbed item:
                        //
                        if ((lItemFlags & WiaItemTypeFolder) && (lItemFlags & WiaItemTypeGenerated))
                        {
                            //
                            // This is a folder item to be created under the base flatbed item, deny the request:
                            //
                            hr = E_INVALIDARG;
                        }

                        if(SUCCEEDED(hr))
                        {
                            hr = InitializeWIAItemProperties(pWiasContext,g_hInst,IDB_FLATBED);
                        }
                        if(FAILED(hr))
                        {
                            WIAS_ERROR((g_hInst, "Failed to initialize the flatbed item's property set. hr = 0x%lx",hr));
                        }
                    }
                    else if(guidItemCategory == WIA_CATEGORY_FEEDER)
                    {
                        hr = InitializeWIAItemProperties(pWiasContext,g_hInst,IDB_FEEDER);
                        if(FAILED(hr))
                        {
                            WIAS_ERROR((g_hInst, "Failed to initialize the feeder item's property set. hr = 0x%lx",hr));
                        }
                    }
                    else if(guidItemCategory == WIA_CATEGORY_FILM)
                    {
                        hr = InitializeWIAItemProperties(pWiasContext,g_hInst,IDB_FILM);
                        if(FAILED(hr))
                        {
                            WIAS_ERROR((g_hInst, "Failed to initialize the film item's property set. hr = 0x%lx",hr));
                        }
                    }
                    else if((guidItemCategory == WIA_CATEGORY_FINISHED_FILE) || (WIA_CATEGORY_FOLDER == guidItemCategory))
                    {
                        hr = InitializeWIAStorageItemProperties(pWiasContext, FALSE,
                            (BOOL)((WIA_CATEGORY_FOLDER == guidItemCategory) && (lItemFlags & WiaItemTypeFolder)));

                        if(FAILED(hr))
                        {
                            WIAS_ERROR((g_hInst, "Failed to initialize the storage item's property set. hr = 0x%lx",hr));
                        }
                    }
                    else
                    {
                        hr = S_OK;
                    }
                }
            }
        }
        else
        {
            WIAS_ERROR((g_hInst, "Failed to read WIA_IPA_ITEM_FLAGS property, hr = 0x%lx",hr));
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }

    if ((FAILED(hr)) && (plDevErrVal))
    {
        *plDevErrVal = (E_INVALIDARG == hr) ? WIA_ERROR_INVALID_COMMAND : WIA_ERROR_GENERAL_ERROR;
    }

    return hr;
}
HRESULT CWIADriver::drvValidateItemProperties(_Inout_   BYTE           *pWiasContext,
                                                        LONG           lFlags,
                                                        ULONG          nPropSpec,
                                              _In_      const PROPSPEC *pPropSpec,
                                              _Out_     LONG           *plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = E_INVALIDARG;
    if((pWiasContext)&&(pPropSpec)&&(plDevErrVal)&&(nPropSpec))
    {
        *plDevErrVal = 0;

        LONG lItemType = 0;
        hr = wiasGetItemType(pWiasContext,&lItemType);
        if(SUCCEEDED(hr))
        {
            if(lItemType & WiaItemTypeRoot)
            {
                //
                // Validate root item property settings, if needed.
                //

                hr = S_OK;
            }
            else
            {
                //
                // Validate child item property settings, if needed.
                //
                LONG                    lScanningSurfaceWidth   = 0;
                LONG                    lScanningSurfaceHeight  = 0;
                GUID                    guidItemCategory        = GUID_NULL;
                GUID                    guidFormat              = GUID_NULL;
                WIA_PROPERTY_CONTEXT    PropertyContext         = {0};
                BOOL                    bUpdateFileExt          = FALSE;

                //
                // Use the WIA item category to help classify and gather WIA item information
                // needed to validate the property set.
                //
                hr = wiasReadPropGuid(pWiasContext,WIA_IPA_ITEM_CATEGORY,&guidItemCategory,NULL,TRUE);
                if(SUCCEEDED(hr))
                {
                    BOOL bValidCategory = FALSE;
                    //
                    // Validate the selection area against the entire scanning surface of the device.
                    // The scanning surface may be different sizes depending on the type of WIA item.
                    // (ie. Flatbed glass platen sizes may be different to film scanning surfaces, and
                    // feeder sizes.)
                    //
                    if((guidItemCategory == WIA_CATEGORY_FLATBED)||(guidItemCategory == WIA_CATEGORY_FILM))
                    {
                        bValidCategory = TRUE;

                        //
                        // Flatbed items and Film items use the same WIA properties to describe their scanning
                        // surface.
                        //
                        hr = wiasReadPropLong(pWiasContext,WIA_IPS_MAX_HORIZONTAL_SIZE,&lScanningSurfaceWidth,NULL,TRUE);
                        if(SUCCEEDED(hr))
                        {
                            hr = wiasReadPropLong(pWiasContext,WIA_IPS_MAX_VERTICAL_SIZE,&lScanningSurfaceHeight,NULL,TRUE);
                            if(FAILED(hr))
                            {
                                WIAS_ERROR((g_hInst, "Failed to read WIA_IPS_MAX_VERTICAL_SIZE property, hr = 0x%lx",hr));
                            }
                        }
                        else
                        {
                            WIAS_ERROR((g_hInst, "Failed to read WIA_IPS_MAX_HORIZONTAL_SIZE property, hr = 0x%lx",hr));
                        }
                    }
                    else if(guidItemCategory == WIA_CATEGORY_FEEDER)
                    {
                        bValidCategory = TRUE;

                        //
                        // Feeder items use a different set of properties to describe the scanning surface.
                        //
                        hr = wiasReadPropLong(pWiasContext,WIA_IPS_MAX_HORIZONTAL_SIZE,&lScanningSurfaceWidth,NULL,TRUE);
                        if(SUCCEEDED(hr))
                        {
                            hr = wiasReadPropLong(pWiasContext,WIA_IPS_MAX_VERTICAL_SIZE,&lScanningSurfaceHeight,NULL,TRUE);
                            if(FAILED(hr))
                            {
                                WIAS_ERROR((g_hInst, "Failed to read WIA_IPS_MAX_VERTICAL_SIZE property, hr = 0x%lx",hr));
                            }
                        }
                        else
                        {
                            WIAS_ERROR((g_hInst, "Failed to read WIA_IPS_MAX_HORIZONTAL_SIZE property, hr = 0x%lx",hr));
                        }
                    }
                    else if((guidItemCategory == WIA_CATEGORY_FINISHED_FILE) || (WIA_CATEGORY_FOLDER == guidItemCategory))
                    {
                        bValidCategory = TRUE;
                        hr = S_OK;
                    }
                    else
                    {
                        hr = S_OK;
                        WIAS_TRACE((g_hInst,"Unknown WIA category read from WIA item, hr = 0x%lx",hr));
                    }

                    if((SUCCEEDED(hr))&&(bValidCategory))
                    {
                        hr = wiasCreatePropContext(nPropSpec,(PROPSPEC*)pPropSpec,0,NULL,&PropertyContext);
                        if(SUCCEEDED(hr))
                        {
                            //
                            // Only perform extent validation for items that contain extent properties.
                            //

                            if((guidItemCategory != WIA_CATEGORY_FINISHED_FILE) && (WIA_CATEGORY_FOLDER != guidItemCategory))
                            {
                                if(SUCCEEDED(hr))
                                {
                                    hr = wiasUpdateValidFormat(pWiasContext,&PropertyContext,(IWiaMiniDrv*)this);
                                    if(FAILED(hr))
                                    {
                                        WIAS_ERROR((g_hInst, "Failed to validate supported formats, hr = %lx",hr));
                                    }
                                }


                                if(SUCCEEDED(hr))
                                {
                                    hr = wiasUpdateScanRect(pWiasContext,&PropertyContext,lScanningSurfaceWidth, lScanningSurfaceHeight);
                                    if(FAILED(hr))
                                    {
                                        WIAS_ERROR((g_hInst, "Failed to validate extent settings. (current selection area), hr = %lx",hr));
                                    }
                                }
                            }

                            HRESULT FreePropContextHR = wiasFreePropContext(&PropertyContext);
                            if(FAILED(FreePropContextHR))
                            {
                                WIAS_ERROR((g_hInst, "wiasFreePropContext failed, hr = 0x%lx",FreePropContextHR));
                            }
                        }
                        else
                        {
                            WIAS_ERROR((g_hInst, "Failed to create WIA property context for validation, hr = 0x%lx",hr));
                        }
                    }
                }

                if (SUCCEEDED(hr) && (guidItemCategory != WIA_CATEGORY_FINISHED_FILE) && (WIA_CATEGORY_FOLDER != guidItemCategory))
                {
                    //
                    // We have several properties dependent on the current image transfer format
                    // (currently this sample supports WiaImgFmt_BMP and WiaImgFmt_RAW):
                    //
                    BOOL bRawFormat = FALSE;
                    hr = wiasReadPropGuid(pWiasContext, WIA_IPA_FORMAT, &guidFormat, NULL, TRUE);
                    if (SUCCEEDED(hr))
                    {
                        bRawFormat = (BOOL)IsEqualGUID(guidFormat, WiaImgFmt_RAW);
                    }

                    //
                    // Update format dependent properties according with the current WIA_IPA_FORMAT value:
                    //
                    BSTR bstrFileExtension = NULL;
                    if(SUCCEEDED(hr))
                    {
                        //
                        // Read the current WIA_IPA_FILENAME_EXTENSION and see if a change is needed:
                        //
                        hr = wiasReadPropStr(pWiasContext, WIA_IPA_FILENAME_EXTENSION, &bstrFileExtension, NULL, TRUE);
                        if(SUCCEEDED(hr))
                        {
                            bUpdateFileExt = (BOOL)(((IsEqualGUID(guidFormat, WiaImgFmt_RAW)) && (wcscmp(bstrFileExtension, TEXT("RAW")))) ||
                                ((IsEqualGUID(guidFormat, WiaImgFmt_BMP)) && (wcscmp(bstrFileExtension, TEXT("BMP")))));
                            SysFreeString(bstrFileExtension);
                            bstrFileExtension = NULL;

                            if(bUpdateFileExt)
                            {
                                if(SUCCEEDED(hr))
                                {
                                    if(bRawFormat)
                                    {
                                        bstrFileExtension = SysAllocString(L"RAW");
                                    }
                                    else
                                    {
                                        bstrFileExtension = SysAllocString(L"BMP");
                                    }

                                    if(bstrFileExtension)
                                    {
                                        hr = wiasWritePropStr(pWiasContext, WIA_IPA_FILENAME_EXTENSION, bstrFileExtension);

                                        SysFreeString(bstrFileExtension);
                                        bstrFileExtension = NULL;

                                        if(FAILED(hr))
                                        {
                                            WIAS_ERROR((g_hInst, "Could not update the file name extension property value, hr = 0x%lx.", hr));
                                        }
                                    }
                                    else
                                    {
                                        hr = E_OUTOFMEMORY;
                                        WIAS_ERROR((g_hInst, "Could not allocate the file name extension property value, hr = 0x%lx.", hr));
                                    }
                                }
                                else
                                {
                                    WIAS_ERROR((g_hInst, "Cannot remove current file name extension property, hr = 0x%lx.", hr));
                                }
                            }
                        }
                    }
                    else
                    {
                        WIAS_ERROR((g_hInst, "Cannot read current format property, hr = 0x%lx.", hr));
                    }
                }
           }

            //
            // Only call wiasValidateItemProperties if the validation above
            // succeeded.
            //
            if(SUCCEEDED(hr))
            {
                hr = wiasValidateItemProperties(pWiasContext,nPropSpec,pPropSpec);
                if(FAILED(hr))
                {
                    WIAS_ERROR((g_hInst, "Failed to validate remaining properties using wiasValidateItemProperties, hr = 0x%lx",hr));
                }
            }
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

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

    HRESULT hr = E_INVALIDARG;
    if ((pWiasContext) && (pmdtc) && (plDevErrVal))
    {
        *plDevErrVal = 0;

        //
        // We have to reset the counter from time to time to allow other
        // acquisitions from the feeder item without to reload the Monster
        // driver and open a new session - we can do this when a property
        // is changed on the Feeder item.
        //
        // (in the case of a driver deserving a real scanner device such a counter
        // would have to be replaced with feeder status checking).
        //
        WIA_DRIVER_ITEM_CONTEXT *pWiaDriverItemContext = NULL;
        hr = wiasGetDriverItemPrivateContext(pWiasContext, (BYTE**)&pWiaDriverItemContext);
        if ((SUCCEEDED(hr)) && (pWiaDriverItemContext))
        {
            pWiaDriverItemContext->ulFeederTransferCount = 0;
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}
HRESULT CWIADriver::drvReadItemProperties(_In_      BYTE           *pWiasContext,
                                                    LONG           lFlags,
                                                    ULONG          nPropSpec,
                                          _In_      const PROPSPEC *pPropSpec,
                                          _Out_     LONG           *plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);
    UNREFERENCED_PARAMETER(nPropSpec);

    HRESULT hr = E_INVALIDARG;
    if((pWiasContext)&&(pPropSpec)&&(plDevErrVal))
    {
        *plDevErrVal = 0;
        hr = S_OK;
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}
HRESULT CWIADriver::drvLockWiaDevice(_In_       BYTE *pWiasContext,
                                                LONG lFlags,
                                     _Out_      LONG *plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    HRESULT hr = E_INVALIDARG;
    if((pWiasContext)&&(plDevErrVal))
    {
        *plDevErrVal = 0;

        if(m_pIStiDevice)
        {
            hr = m_pIStiDevice->LockDevice(DEFAULT_LOCK_TIMEOUT);
        }
        else
        {
            hr = S_OK;
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

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

    HRESULT hr = E_INVALIDARG;
    if((pWiasContext)&&(plDevErrVal))
    {
        *plDevErrVal = 0;

        if(m_pIStiDevice)
        {
            hr = m_pIStiDevice->UnLockDevice();
        }
        else
        {
            hr = S_OK;
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

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

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}
HRESULT CWIADriver::drvGetDeviceErrorStr(         LONG     lFlags,
                                                  LONG     lDevErrVal,
                                         _Out_    LPOLESTR *ppszDevErrStr,
                                         _Out_    LONG     *plDevErr)
{
    UNREFERENCED_PARAMETER(lFlags);
    UNREFERENCED_PARAMETER(lDevErrVal);
    UNREFERENCED_PARAMETER(ppszDevErrStr);
    UNREFERENCED_PARAMETER(plDevErr);

    WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    return E_NOTIMPL;
}
HRESULT CWIADriver::DestroyDriverItemTree()
{
    HRESULT hr = S_OK;

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

        WIAS_TRACE((g_hInst,"Releasing IDrvItemRoot interface"));
        m_pIDrvItemRoot->Release();
        m_pIDrvItemRoot = NULL;
    }

    return hr;
}

HRESULT CWIADriver::BuildDriverItemTree()
{
    HRESULT hr = S_OK;
    if(!m_pIDrvItemRoot)
    {
        LONG lItemFlags = WiaItemTypeFolder | WiaItemTypeDevice | WiaItemTypeRoot;
        BSTR bstrRootItemName = SysAllocString(WIA_DRIVER_ROOT_NAME);
        if(bstrRootItemName)
        {
            //
            // Create a default WIA root item
            //
            hr = wiasCreateDrvItem(lItemFlags,
                                   bstrRootItemName,
                                   m_bstrRootFullItemName,
                                   (IWiaMiniDrv*)this,
                                   0,
                                   NULL,
                                   &m_pIDrvItemRoot);
            //
            // Create child items that represent the data or programmable data sources.
            //
            if(SUCCEEDED(hr))
            {
                hr = CreateWIAFlatbedItem(WIA_DRIVER_FLATBED_NAME,(IWiaMiniDrv*)this,m_pIDrvItemRoot);
                if(FAILED(hr))
                {
                    WIAS_ERROR((g_hInst, "Failed to create WIA flatbed item, hr = 0x%lx",hr));
                }
            }

            if(SUCCEEDED(hr))
            {
                hr = CreateWIAFeederItem(WIA_DRIVER_FEEDER_NAME,(IWiaMiniDrv*)this,m_pIDrvItemRoot);
                if(FAILED(hr))
                {
                    WIAS_ERROR((g_hInst, "Failed to create WIA feeder item, hr = 0x%lx",hr));
                }
            }

            if(SUCCEEDED(hr))
            {
                hr = CreateWIAFilmItem(WIA_DRIVER_FILM_NAME,(IWiaMiniDrv*)this,m_pIDrvItemRoot);
                if(FAILED(hr))
                {
                    WIAS_ERROR((g_hInst, "Failed to create WIA film item, hr = 0x%lx",hr));
                }
            }

            if(SUCCEEDED(hr))
            {
                hr = CreateWIAStorageItem(WIA_DRIVER_STORAGE_NAME,(IWiaMiniDrv*)this,m_pIDrvItemRoot,m_wszStoragePath);
                if(FAILED(hr))
                {
                    WIAS_ERROR((g_hInst, "Failed to create WIA storage item, hr = 0x%lx",hr));
                }
            }

            SysFreeString(bstrRootItemName);
            bstrRootItemName = NULL;
        }
        else
        {
            hr = E_OUTOFMEMORY;
            WIAS_ERROR((g_hInst, "Failed to allocate memory for the root item name, hr = 0x%lx",hr));
        }
    }

    return hr;
}


HRESULT CWIADriver::DoSynchronizeCommand(
    _Inout_ BYTE *pWiasContext)
{
    HRESULT hr = S_OK;

    hr = DestroyDriverItemTree();
    if (SUCCEEDED(hr))
    {
        hr = BuildDriverItemTree();

        //
        //  Queue tree updated event, regardless ofwhether it
        //  succeeded, since we can't guarantee that the tree
        //  was left in the same condition.
        //
        QueueWIAEvent(pWiasContext, WIA_EVENT_TREE_UPDATED);
    }
    else
    {
        WIAS_ERROR((g_hInst, " failed, hr = 0x%lx", hr));
    }

    return hr;
}

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

    HRESULT hr = E_NOTIMPL;

    if (ppWiaDrvItem)
    {
        *ppWiaDrvItem = NULL;
    }

    if (plDevErrVal)
    {
        *plDevErrVal = 0;
    }

    if (pguidCommand)
    {
        if (*pguidCommand == WIA_CMD_SYNCHRONIZE)
        {
            hr = DoSynchronizeCommand(pWiasContext);
        }
    }
    else
    {
        hr = E_NOTIMPL;
        WIAS_ERROR((g_hInst, "This method is not implemented or supported for this driver"));
    }

    return hr;
}

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

    HRESULT hr = E_INVALIDARG;
    if((pcelt)&&(ppCapabilities)&&(plDevErrVal))
    {
        hr = S_OK;

        *pcelt = 0;
        *ppCapabilities = NULL;
        *plDevErrVal = 0;

        if(m_CapabilityManager.GetNumCapabilities() == 0)
        {
            hr = m_CapabilityManager.AddCapability(WIA_EVENT_DEVICE_CONNECTED,
                                                   IDS_EVENT_DEVICE_CONNECTED_NAME,
                                                   IDS_EVENT_DEVICE_CONNECTED_DESCRIPTION,
                                                   WIA_NOTIFICATION_EVENT,
                                                   WIA_ICON_DEVICE_CONNECTED);
            if(SUCCEEDED(hr))
            {
                hr = m_CapabilityManager.AddCapability(WIA_EVENT_TREE_UPDATED,
                                                       IDS_EVENT_TREE_UPDATED_NAME,
                                                       IDS_EVENT_TREE_UPDATED_DESCRIPTION,
                                                       WIA_NOTIFICATION_EVENT,
                                                       WIA_ICON_TREE_UPDATED);
                if(SUCCEEDED(hr))
                {
                    hr = m_CapabilityManager.AddCapability(WIA_EVENT_DEVICE_DISCONNECTED,
                                                           IDS_EVENT_DEVICE_DISCONNECTED_NAME,
                                                           IDS_EVENT_DEVICE_DISCONNECTED_DESCRIPTION,
                                                           WIA_NOTIFICATION_EVENT,
                                                           WIA_ICON_DEVICE_DISCONNECTED);
                    if(SUCCEEDED(hr))
                    {
                        hr = m_CapabilityManager.AddCapability(WIA_CMD_SYNCHRONIZE,
                                                               IDS_CMD_SYNCHRONIZE_NAME,
                                                               IDS_CMD_SYNCHRONIZE_DESCRIPTION,
                                                               0,
                                                               WIA_ICON_SYNCHRONIZE);
                        if(FAILED(hr))
                        {
                            WIAS_ERROR((g_hInst, "Failed to add WIA_CMD_SYNCHRONIZE to capability manager, hr = 0x%lx",hr));
                        }
                    }
                    else
                    {
                        WIAS_ERROR((g_hInst, "Failed to add WIA_EVENT_DEVICE_DISCONNECTED to capability manager, hr = 0x%lx",hr));
                    }
                }
                else
                {
                    WIAS_ERROR((g_hInst, "Failed to add WIA_EVENT_TREE_UPDATED to capability manager, hr = 0x%lx",hr));
                }
            }
            else
            {
                WIAS_ERROR((g_hInst, "Failed to add WIA_EVENT_DEVICE_CONNECTED to capability manager, hr = 0x%lx",hr));
            }
        }

        if(SUCCEEDED(hr))
        {
            if(((ulFlags & WIA_DEVICE_COMMANDS) == WIA_DEVICE_COMMANDS)&&(ulFlags & WIA_DEVICE_EVENTS) == WIA_DEVICE_EVENTS)
            {
                *ppCapabilities = m_CapabilityManager.GetCapabilities();
                *pcelt          = m_CapabilityManager.GetNumCapabilities();
                WIAS_TRACE((g_hInst,"Application is asking for Commands and Events, and we have %d total capabilities",*pcelt));
            }
            else if((ulFlags & WIA_DEVICE_COMMANDS) == WIA_DEVICE_COMMANDS)
            {
                *ppCapabilities = m_CapabilityManager.GetCommands();
                *pcelt          = m_CapabilityManager.GetNumCommands();
                WIAS_TRACE((g_hInst,"Application is asking for Commands, and we have %d",*pcelt));
            }
            else if((ulFlags & WIA_DEVICE_EVENTS) == WIA_DEVICE_EVENTS)
            {
                *ppCapabilities = m_CapabilityManager.GetEvents();
                *pcelt          = m_CapabilityManager.GetNumEvents();
                WIAS_TRACE((g_hInst,"Application is asking for Events, and we have %d",*pcelt));
            }

            WIAS_TRACE((g_hInst,"========================================================"));
            WIAS_TRACE((g_hInst,"WIA driver capability information"));
            WIAS_TRACE((g_hInst,"========================================================"));

            WIA_DEV_CAP_DRV *pCapabilities      = m_CapabilityManager.GetCapabilities();
            LONG            lNumCapabilities    = m_CapabilityManager.GetNumCapabilities();

            for(LONG i = 0; i < lNumCapabilities; i++)
            {
                if(pCapabilities[i].ulFlags & WIA_NOTIFICATION_EVENT)
                {
                    WIAS_TRACE((g_hInst,"Event Name:        %ws",pCapabilities[i].wszName));
                    WIAS_TRACE((g_hInst,"Event Description: %ws",pCapabilities[i].wszDescription));
                }
                else
                {
                    WIAS_TRACE((g_hInst,"Command Name:        %ws",pCapabilities[i].wszName));
                    WIAS_TRACE((g_hInst,"Command Description: %ws",pCapabilities[i].wszDescription));
                }
            }
            WIAS_TRACE((g_hInst,"========================================================"));
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

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

    HRESULT hr = E_INVALIDARG;
    if((pWiasContext)&&(plDevErrVal))
    {
        *plDevErrVal = 0;

        GUID guidWiaItemCategory = GUID_NULL;
        hr = wiasReadPropGuid(pWiasContext,WIA_IPA_ITEM_CATEGORY,&guidWiaItemCategory,NULL,TRUE);
        if(SUCCEEDED(hr))
        {
            if(guidWiaItemCategory == WIA_CATEGORY_FINISHED_FILE)
            {
                WIA_DRIVER_ITEM_CONTEXT *pWiaDriverItemContext = NULL;
                hr = wiasGetDriverItemPrivateContext(pWiasContext,(BYTE**)&pWiaDriverItemContext);
                if(SUCCEEDED(hr))
                {
                    DeleteFile(pWiaDriverItemContext->bstrStorageDataPath);
                }
                else
                {
                    //
                    // If the WIA item does not have a driver item context, then
                    // assume that there is no associated storage data with it.
                    //

                    hr = S_OK;
                }
            }
            else
            {
                //
                // If the WIA item is not of finished file category, then
                // assume that there is no associated storage data with it.
                //

                hr = S_OK;
            }
        }
        else
        {
            WIAS_ERROR((g_hInst, "Failed to read the WIA_IPA_ITEM_CATEGORY property, hr = 0x%lx",hr));
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }

    //
    // Only queue the deleted event, if the deletion was a success
    //

    if(SUCCEEDED(hr))
    {
        QueueWIAEvent(pWiasContext,WIA_EVENT_ITEM_DELETED);
    }

    return hr;
}
HRESULT CWIADriver::drvFreeDrvItemContext(
                                                    LONG  lFlags,
    _Inout_updates_bytes_(sizeof(WIA_DRIVER_ITEM_CONTEXT)) BYTE *pSpecContext,
    _Out_                                           LONG *plDevErrVal)
{
    UNREFERENCED_PARAMETER(lFlags);

    if (plDevErrVal)
    {
        *plDevErrVal = NULL;
    }

    WIA_DRIVER_ITEM_CONTEXT *pWiaDriverItemContext = (WIA_DRIVER_ITEM_CONTEXT*)pSpecContext;
    if(pWiaDriverItemContext)
    {
        // Free allocated BSTR if it exists.
        if(pWiaDriverItemContext->bstrStorageDataPath)
        {
            SysFreeString(pWiaDriverItemContext->bstrStorageDataPath);
            pWiaDriverItemContext->bstrStorageDataPath = NULL;
        }
    }

    return S_OK;
}

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;

    if ((!plDevErrVal) || (!pcelt) || (!ppwfi))
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }

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

        if (m_pFormats)
        {
            delete [] m_pFormats;
            m_pFormats = NULL;
        }

        m_ulNumFormats = DEFAULT_NUM_DRIVER_FORMATS;

        CBasicDynamicArray<GUID> FileFormats;

        //
        // add the default formats to the corresponding arrays
        //
        if (pWiasContext)
        {
            //
            // Create a format list that is specific to the WIA item.
            //
            LONG lItemType = 0;
            hr = wiasGetItemType(pWiasContext, &lItemType);
            if (SUCCEEDED(hr))
            {
                if (lItemType & WiaItemTypeImage)
                {
                    FileFormats.Append(WiaImgFmt_BMP);
                    FileFormats.Append(WiaImgFmt_RAW);
                }
                else
                {
                    FileFormats.Append(WiaImgFmt_UNDEFINED);
                }
            }
            else
            {
                WIAS_ERROR((g_hInst, "Failed to get WIA item type, hr = 0x%lx",hr));
            }
        }
        else
        {
            //
            // Create a default format list
            //
            // For this sample driver we are assuming that the majority of data
            // transferred will be image data, so when a query for formats fails,
            // it is safe to default to DIB and Raw as the formats.
            //
            FileFormats.Append(WiaImgFmt_BMP);
            FileFormats.Append(WiaImgFmt_RAW);
        }

        *pcelt = 0;
        *ppwfi = NULL;

        if (SUCCEEDED(hr))
        {
            m_ulNumFormats = FileFormats.Size();
            m_pFormats = new WIA_FORMAT_INFO[m_ulNumFormats];
            if (m_pFormats)
            {
                //
                // add file (TYMED_FILE) formats to format array
                //
                for (ULONG iIndex = 0; iIndex < m_ulNumFormats; iIndex++)
                {
                    m_pFormats[iIndex].guidFormatID = FileFormats[iIndex];
                    m_pFormats[iIndex].lTymed       = TYMED_FILE;
                }

                *pcelt = m_ulNumFormats;
                *ppwfi = &m_pFormats[0];
            }
            else
            {
                hr = E_OUTOFMEMORY;
                WIAS_ERROR((g_hInst, "Failed to allocate memory for WIA_FORMAT_INFO structure array, hr = 0x%lx",hr));

                m_ulNumFormats = 0;
            }
        }
    }

    return hr;
}

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

    HRESULT hr = E_INVALIDARG;
    if(pEventGUID)
    {
        // TBD: Add any special event handling here.
        //      Power management, canceling pending I/O etc.
        hr = S_OK;
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

HRESULT CWIADriver::drvUnInitializeWia(_Inout_ BYTE *pWiasContext)
{
    HRESULT hr = E_INVALIDARG;
    if(pWiasContext)
    {
        if(InterlockedDecrement(&m_lClientsConnected) < 0)
        {
            WIAS_TRACE((g_hInst, "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,"%d client(s) are currently connected to this driver.",m_lClientsConnected));

        if(m_lClientsConnected == 0)
        {

            //
            // When the last client disconnects, destroy the WIA item tree.
            // This should reduce the idle memory foot print of this driver
            //

            DestroyDriverItemTree();
        }
    }
    else
    {
        hr = E_INVALIDARG;
        WIAS_ERROR((g_hInst, "Invalid parameters were passed, hr = 0x%lx",hr));
    }
    return hr;
}

/////////////////////////////////////////////////////////////////////////
// INonDelegating Interface Section (for all WIA drivers)              //
/////////////////////////////////////////////////////////////////////////

HRESULT CWIADriver::NonDelegatingQueryInterface(REFIID  riid,LPVOID  *ppvObj)
{
    if(!ppvObj)
    {
        WIAS_ERROR((g_hInst, "Invalid parameters were passed"));
        return E_INVALIDARG;
    }

    *ppvObj = NULL;

    if(IsEqualIID( riid, IID_IUnknown ))
    {
        *ppvObj = static_cast<INonDelegatingUnknown*>(this);
    }
    else if(IsEqualIID( riid, IID_IStiUSD ))
    {
        *ppvObj = static_cast<IStiUSD*>(this);
    }
    else if(IsEqualIID( riid, IID_IWiaMiniDrv ))
    {
        *ppvObj = static_cast<IWiaMiniDrv*>(this);
    }
    else
    {
        return E_NOINTERFACE;
    }

    reinterpret_cast<IUnknown*>(*ppvObj)->AddRef();
    return S_OK;
}

ULONG CWIADriver::NonDelegatingAddRef()
{
    return InterlockedIncrement(&m_cRef);
}

ULONG CWIADriver::NonDelegatingRelease()
{
    ULONG ulRef = InterlockedDecrement(&m_cRef);
    if(ulRef == 0)
    {
        delete this;
        return 0;
    }
    return ulRef;
}

/////////////////////////////////////////////////////////////////////////
// IClassFactory Interface Section (for all COM objects)               //
/////////////////////////////////////////////////////////////////////////

class CWIADriverClassFactory : public IClassFactory
{
public:
    CWIADriverClassFactory() : m_cRef(1) {}
    ~CWIADriverClassFactory(){}
    HRESULT __stdcall QueryInterface(REFIID riid, _COM_Outptr_ LPVOID *ppv)
    {
        if(!ppv)
        {
            WIAS_ERROR((g_hInst, "Invalid parameters were passed"));
            return E_INVALIDARG;
        }

        *ppv = NULL;
        HRESULT hr = E_NOINTERFACE;
        if(IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory))
        {
            *ppv = static_cast<IClassFactory*>(this);
            reinterpret_cast<IUnknown*>(*ppv)->AddRef();
            hr = S_OK;
        }
        return hr;
    }
    ULONG __stdcall AddRef()
    {
        return InterlockedIncrement(&m_cRef);
    }
    ULONG __stdcall Release()
    {
        ULONG ulRef = InterlockedDecrement(&m_cRef);
        if(ulRef == 0)
        {
            delete this;
            return 0;
        }
        return ulRef;
    }
#pragma prefast(suppress:__WARNING_INVALID_PARAM_VALUE_2, "Set ppvObject to NULL if failed.")
    HRESULT __stdcall CreateInstance(_In_opt_ IUnknown* pUnkOuter, _In_ REFIID riid, _COM_Outptr_ void** ppvObject)
    {
        if (ppvObject == NULL)
        {
            return E_INVALIDARG;
        }
        *ppvObject = NULL;

        if((pUnkOuter)&&(!IsEqualIID(riid,IID_IUnknown)))
        {
            return CLASS_E_NOAGGREGATION;
        }

        HRESULT hr = E_NOINTERFACE;
#pragma prefast(suppress:__WARNING_ALIASED_MEMORY_LEAK, "pDev is freed on release.")
        CWIADriver *pDev = new CWIADriver(pUnkOuter);
        if(pDev)
        {
            hr = pDev->NonDelegatingQueryInterface(riid,ppvObject);
            pDev->NonDelegatingRelease();
        }
        else
        {
            hr = E_OUTOFMEMORY;
            WIAS_ERROR((g_hInst, "Failed to allocate WIA driver class object, hr = 0x%lx",hr));
        }

        return hr;
    }
    HRESULT __stdcall LockServer(BOOL fLock)
    {
        UNREFERENCED_PARAMETER(fLock);

        return S_OK;
    }
private:
    LONG m_cRef;
};

/////////////////////////////////////////////////////////////////////////
// DLL Entry Point Section (for all COM objects, in a DLL)             //
/////////////////////////////////////////////////////////////////////////

extern "C" __declspec(dllexport) BOOL APIENTRY DllMain(HINSTANCE hinst,DWORD dwReason, _Reserved_ LPVOID lpReserved)
{
    UNREFERENCED_PARAMETER(lpReserved);

    g_hInst = hinst;
    switch(dwReason)
    {
    case DLL_PROCESS_ATTACH:
        DisableThreadLibraryCalls(hinst);
        break;
    }
    return TRUE;
}

extern "C" HRESULT __stdcall DllCanUnloadNow(void)
{
    return S_OK;
}
extern "C" HRESULT __stdcall DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID *ppv)
{
    if(!ppv)
    {
        WIAS_ERROR((g_hInst, "Invalid parameters were passed"));
        return E_INVALIDARG;
    }
    HRESULT hr = CLASS_E_CLASSNOTAVAILABLE;
    *ppv = NULL;
    if(IsEqualCLSID(rclsid, CLSID_WIADriver))
    {
#pragma prefast(suppress:__WARNING_ALIASED_MEMORY_LEAK, "pcf is freed on release.")
        CWIADriverClassFactory *pcf = new CWIADriverClassFactory;
        if(pcf)
        {
            hr = pcf->QueryInterface(riid,ppv);
            pcf->Release();
        }
        else
        {
            hr = E_OUTOFMEMORY;
            WIAS_ERROR((g_hInst, "Failed to allocate WIA driver class factory object, hr = 0x%lx",hr));
        }
    }
    return hr;
}

extern "C" HRESULT __stdcall DllRegisterServer()
{
    return S_OK;
}

extern "C" HRESULT __stdcall DllUnregisterServer()
{
    return S_OK;
}