Subversion Repository Public Repository

ConnectionOdbcSdk

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

namespace Cisco.UnityConnection.OdbcSdk
{
    /// <summary>
    /// The ConnectionInformixAdoNetDatabaseFunctions class provides a set of routines that make fetching data, converting to data tables (for grid display), 
    /// calling stored procedures and similiar tasks considerably easier and less error prone. 
    /// </summary>
    /// <remarks>
    /// Commonly needed items like finding extensions and aliases of users, checking to see if an extension is valid, doing blocking and background data 
    /// fetches are all provided in this class.  The ConnectionInformixAdoNetDatabaseFunctions class is most often created as an instance member of the 
    /// ConnectionServerOdbc class but can be used stand alone as well - however you must pass in a reference to a ConnectionServerOdbc
    /// when creating the ConnectionInformixAdoNetDatabaseFunctions instance since the connection provided by the ConnectionServerOdbc class is necessary.
    /// </remarks>
    public class ConnectionInformixAdoNetDatabaseFunctions : IDisposable, IConnectionDatabaseFunctions
    {

        #region Logging and Error Events

        /// <summary>
        /// Event handle for external clients to register with so they can get logging events on errors and warnings that happen
        /// within this class.
        /// </summary>
        public event LoggingEventHandler ErrorEvents;

        /// <summary>
        /// Debug events can be registered for and recieved to view raw send/response text
        /// </summary>
        public event LoggingEventHandler DebugEvents;

        /// <summary>
        /// Alternative event handler for logging events that includes the LogEventArgs that include the log string in the 
        /// argument
        /// </summary>
        public delegate void LoggingEventHandler(object sender, LogEventArgs e);

        /// <summary>
        /// If there's one or more clients registered for the ErrorEvent event then issue it here.
        /// </summary>
        /// <param name="pLine">
        /// String to pass back to the receiving method
        /// </param>
        private void RaiseErrorEvent(string pLine)
        {
            //notify registered clients 
            LoggingEventHandler handler = ErrorEvents;

            if (handler != null)
            {
                LogEventArgs oArgs = new LogEventArgs(pLine);
                handler(null, oArgs);
            }
        }

        /// <summary>
        /// If there's one or more clients registerd for the DebugEvents event then issue it here.
        /// </summary>
        /// <param name="pLine">
        /// String to pass back to the receiving method
        /// </param>
        private void RaiseDebugEvent(string pLine)
        {
            if (DebugMode == false) return;

            //notify registered clients
            LoggingEventHandler handler = DebugEvents;

            if (handler != null)
            {
                LogEventArgs oArgs = new LogEventArgs(pLine);
                handler(null, oArgs);
            }
        }

        #endregion


        #region Properties and Fields

        /// <summary>
        /// True if we're in debug mode and raising debug events, false if not
        /// </summary>
        public bool DebugMode { get; set; }

        /// <summary>
        /// When iterating with a recordset if the underlying data is locked with a pending update we may need to wait for the lock to release 
        /// before being able to continue iterating over the data - 10 seconds is a rather long time but just in case.
        /// </summary>
        private const int LockWaitTimeMs = 10000;

        /// <summary>
        /// Informix has a unique format for its date/time fetches that needs to confirm to this or the queries and stored proc calls will fail.
        /// </summary>
        public const string InformixDateFormatString = "yyyy-MM-dd HH:mm:ss";

        /// <summary>
        /// handle to issue commands to the Informix database.  This is shared across several methods in this class and ensures that only one
        /// DB session is in use at a time - while Connection will allow for up to 10 it is too easy to chew through them and run out so I restrict 
        /// all the stored proc and data reader bound fetches/sets to a single session.  Any method that references this command object will have 
        /// a monitor on it ensureing all other access to any other method that also uses it will have to wait.
        /// </summary>
        private readonly IfxCommand _command = new IfxCommand();

        /// <summary>
        /// Used for locking access to methods to a single thread at a time - any method that uses the shared _command object (above) uses this locking
        /// mechanism.
        /// </summary>
        private volatile object _lockCommandObject = new object();

        /// <summary>
        /// Used for starting the creation of a stored proc and is released at the time the proc is called
        /// </summary>
        private volatile object _lockProcBuildObject = new object();


        //used to store the currently built up stored proc to be called
        private string _commandString; 

        //the actual connection we'll be using to do queries against - this is passed in as part of the constructor - wired up by the ConnectionServerOdbc class and 
        //passed in.
        private IfxConnection _iFxConnection;
        
        /// <summary>
        /// The primary location object is used so often for filtering objects it's passed in as part of the constructor so we don't have to go fetch it each time.
        /// This is filled out along with a number of other location items at login time all at once.
        /// </summary>
        public  string PrimaryLocationObjectId {get; private set;}

        /// <summary>
        /// Indicate if the connection is pending, attached or closed
        /// </summary>
        public ConnectionState DatabaseConnectionStatus 
        {
            get
            {
                if (_iFxConnection == null)
                {
                    return ConnectionState.Closed;
                }
                return _iFxConnection.State;
            }
        }

        /// <summary>
        /// name of the server(ip address)
        /// </summary>
        public string DatabaseServerName { get; private set; }

        /// <summary>
        /// Which database are we connected to at the moment.  Can be UnityDirDb, UnityDynDb, UnityRptDb or one of the configured mailbox store databases
        /// (UnityMbxDb1, UnityMbxDb2 etc...)
        /// </summary>
        public string DatabaseName { get; private set; }

        public string LoginName { get; private set; }
        public string Password { get; private set; }

        private readonly string _applicationName;

        private string _greetingsAdministratorRoleObjectId;
        /// <summary>
        /// The greeting administrator role - do a lazy fetch for this if it's searched against.
        /// </summary>
        public string GreetingsAdministratorRoleObjectId
        {
            get
            {
                if (string.IsNullOrEmpty(_greetingsAdministratorRoleObjectId))
                {
                    const string strSql = "SELECT ObjectID FROM vw_role where rolename='Greeting Administrator'";
                    _greetingsAdministratorRoleObjectId = GetSingleValueFromQuery(strSql);
                }
                return _greetingsAdministratorRoleObjectId;
            }
        }


       #endregion


        #region Constructors and Destructors

        /// <summary>
        /// Constructor for class - requires the applciation name which is used for logging purposes.  The application name and the logged in user name
        /// are provided whenever making stored procedure calls so the audit log on Unity Connection is maintained properly.  A meaningful name should
        /// always be provided here for troubleshooting purposes.
        /// </summary>
        public ConnectionInformixAdoNetDatabaseFunctions(string pApplicationName)
        {
            _iFxConnection = null;

            _applicationName = pApplicationName;
        }

        //implement the disposable over rides since we create some disposable objects in this class.
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_iFxConnection!=null) _iFxConnection.Dispose();
                if (_command != null) _command.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion


        #region Attach and Close Connection Methods

        /// <summary>
        /// Initial login to remote Unity Connection database. Defaults to the UnityDirDb database which is the most common but this can 
        /// be overridden with the dynDb, ReportDb or one of the mailbox databases if needed.
        /// </summary>
        public DbFetchResult AttachToDatabase(string pServerName, string pLoginName, string pPassword,string pDatabaseName = "UnityDirDb")
        {
            DbFetchResult res = new DbFetchResult {Successful = false};
             
            try
            {
                IfxConnection conn =new IfxConnection("Host=" + pServerName + ";Server=ciscounity;Service=20532;User ID=" + pLoginName
                                      + "; password=" + pPassword +
                                      "; Database=UnityDirDb;DB_LOCALE=en_us.utf8;CLIENT_LOCALE=en_us.utf8;Protocol=onsoctcp");

                _iFxConnection = new IfxConnection();
                _iFxConnection.ConnectionString = conn.ConnectionString;

                _iFxConnection.Open();
            }

            catch (IfxException ex)
            {
                res.ErrorDetails = GetLoginErrorString(ex);
                return res;
            }
            
            catch (Exception ex)
            {
                res.ErrorDetails = "Failed logging into server:" + ex.Message;
                return res;
            }

            DatabaseServerName = pServerName;
            DatabaseName = pDatabaseName;
            LoginName = pLoginName;
            Password = pPassword;
            
            FillLocationProperties();

            res.Successful = true;
            return res;
        }

        /// <summary>
        /// Change which database is connected - can switch between UnityDirDb, UnityDynDb, UnityRptDb and any of the 
        /// supported mailbox databases (UnityMbxDb1, UnityMbxDb2 etc...) 
        /// </summary>
        public DbFetchResult UpdateDatabaseName(string pDatabaseName)
        {

            DbFetchResult res = new DbFetchResult();
            res.Successful = false;

            //validate the name
            if (string.IsNullOrEmpty(pDatabaseName))
            {
                res.ErrorDetails = "(error) Empty database name passed to ChangeActiveDatabase in clsConnectionServer";
                RaiseErrorEvent(res.ErrorDetails);
                return res;
            }

            if (_iFxConnection == null)
            {
                res.ErrorDetails = "Database not connected";
                return res;
            }

            //make sure the DB name is valid
            switch (pDatabaseName.ToUpper())
            {
                case "UNITYDIRDB":
                case "UNITYDYNDB":
                case "UNITYRPTDB":
                    break;
                case "UNITYMBXDB1":
                case "UNITYMBXDB2":
                case "UNITYMBXDB3":
                case "UNITYMBXDB4":
                case "UNITYMBXDB5":
                case "UNITYMBXDB6":
                    break;
                default:
                    res.ErrorDetails ="(error) Invalid database name passed to ChangeActiveDatabase in clsConnectionServer:" +pDatabaseName;
                    RaiseErrorEvent(res.ErrorDetails);
                    res.Successful = false;
                    return res;
            }

            DatabaseName = pDatabaseName;

            _iFxConnection.Close();
            _iFxConnection.ConnectionString = string.Format("Host={0};Server=ciscounity;Service=20532;User ID={1}; password={2}; " +
                                                           "Database={3};DB_LOCALE=en_us.utf8;CLIENT_LOCALE=en_us.utf8;Protocol=onsoctcp",DatabaseServerName,
                                                           LoginName,Password, DatabaseName);
            try
            {
                _iFxConnection.Open();
            }
            catch (Exception ex)
            {
                res.ErrorDetails = "(error) while changing databases in ChangeActiveDatabase: " + ex;
                RaiseErrorEvent(res.ErrorDetails);
                return res;
            }

            res.Successful = true;
            return res;
        }

        /// <summary>
        /// Close connection to remote database.
        /// </summary>
        public void Disconnect()
        {
            if (_iFxConnection == null)
            {
                return;
            }
            try
            {
                _iFxConnection.Close();
            }
            catch (Exception ex)
            {
                RaiseErrorEvent("Error closing database connection:"+ex);
            }
        }

        #endregion


        #region Helper Methods

        /// <summary>
        /// When we create users in a mailstore we need to force it to reindex (update statistics) or message imports into that mailstore
        /// will grind to a halt.  This is technically true only if the mailstore is completely empty and then you add a bunch of users and then
        /// a bunch of messages - but to be safe we force a reindex after adding users to any mailstore here - it's pretty quick and does no harm at
        /// any rate.
        /// </summary>
        /// <param name="pDatabaseName">
        /// The mailstore name to update - most systems have only one mailstore but it's possible there are up to 5.
        /// </param>
        /// <param name="pServerName"></param>
       /// <param name="pLoginName"></param>
       /// <param name="pPassword"></param>
       /// <returns></returns>
        public DbFetchResult UpdateStatisticsForDatabase(string pDatabaseName, string pServerName, string pLoginName, string pPassword)
        {
            RaiseDebugEvent("[debug] Updating mailstore statistics for: " + pDatabaseName);

            DbFetchResult res = new DbFetchResult();

            if (!ConnectionServerOdbc.IsValidDatabaseName(pDatabaseName))
            {
                res.Successful = false;
                res.ErrorDetails="Invalid database name passed to UpdateStatisticsForDatabase:"+pDatabaseName;
                return res;
            }

            string strLocalConnectionString = string.Format("Host={0};Server=ciscounity;Service=20532;User ID={1}; password={2}; " +
                                                            "Database={3};DB_LOCALE=en_us.utf8;CLIENT_LOCALE=en_us.utf8;Protocol=onsoctcp",
                                                            pServerName, pLoginName, pPassword, pDatabaseName);
            res.SQLQuery = strLocalConnectionString;
            
            using (var oConnection = new IfxConnection(strLocalConnectionString))
            {
                using (var oCommand = new IfxCommand("update statistics", oConnection))
                {
                    try
                    {
                        oConnection.Open();
                        oCommand.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        res.Successful = false;
                        res.ErrorDetails="(error) in UpdateStaticsForMailstore:" + ex;
                        return res;
                    }
                }
            }

            res.Successful = true;
            return res;
        }


        /// <summary>
        /// if there's a login failure via ODBC process the error information we get back from the Informix ODBC driver.
        /// there's some common failure reasons that we can dig out and warn about in a friendly mannor - if it's something else
        /// just pass through what the ODBC driver raises.
        /// </summary>
        public static string GetLoginErrorString(IfxException ex)
        {
            if (ex == null)
            {
                return "";
            }

            string strErrorText = "The login attempt failed." + "\n" + "\n";

            //check system errors returned by Informix - there's a couple of common ones users trip up on a lot.
            if (ex.Errors.Count > 0)
            {
                switch (ex.Errors[0].NativeError)
                {
                    case -908:
                        strErrorText += "System error -908 This usually means the server is not found or that the ODBC Proxy is not enabled or cannot be reached"
                                     + " on port 20532.  Make sure that port is not being blocked, that the database proxy service is currently active and running"
                                     + " and that the server name can be resolved properly from this Windows machine." + "\n";
                        break;
                    case -930:
                        strErrorText += "System error -930 This usually means the server is not found.  Make sure that the server name can be resolved properly from"
                                     + " this Windows machine." + "\n";
                        break;
                    case -11048:
                        strErrorText += "System error -11048 This usually means the ODBC driver is not installed properly or it can sometimes mean the PATH environment"
                                     + " variable is too long - try moving the INFORMIXDIR/bin reference to the beginning of the PATH." + "\n";
                        break;
                    case -27001:
                        strErrorText += "System error -27001 This usually means the user name or password are wrong or that they correspond to a user that does not have"
                                     + " the Remote Database Access role assigned to them or that the user\'s password has expired or is set to require a reset at next"
                                     + " login or the account has been locked." + "\n";
                        break;
                    default:
                        strErrorText += "Error retrned from ODBC Driver=" + ex.Message + "\n";
                        break;
                }
            }
            else
            {
                strErrorText += "Error retrned from ODBC Driver=" + ex.Message + "\n";
            }

            //store the error in the last error slot so the calling party can decide what to do with it - show it as a tool tip in the grid,
            //throw a message box up, passively show it in a status in the toolbar etc...
            strErrorText += "\n" + "Make sure Connection has been properly configured to allow for remote logins.  See the \'Troubleshooting Tips\' " +
                             "section in the help file for more details on this and other potential issues that could cause connection failures.";

            return strErrorText;
        }


        /// <summary>
        /// Connection 8.6 and later has a habit of tearing down the ODBC connection out from under you if it's been up to long - even with a 
        /// "keep alive" type ping to make it stay up sometime around 12:30am or so it tends to sweep through and wipe them all out for reasons
        /// that we haven't been able to run down - this method is called if the connection is lost in an attempt to reestablish it.
        /// </summary>
        /// <returns></returns>
        public bool CycleDatabaseConnection()
        {
            RaiseErrorEvent("(warning) attempting to reconnect via ODBC - connection has been lost");
            if (_iFxConnection == null)
            {
                return false;
            }

            try
            {
                _iFxConnection.Close();
                _iFxConnection.Open();
            }
            catch (Exception ex)
            {
                RaiseErrorEvent("(error) failed to reestablish database connectivity in CycleDatabaseConnection:"+ex);
                return false;
            }

            return (_iFxConnection.State == ConnectionState.Open);
        }

        /// <summary>
        /// used for logging output - this dumps the command text (query or stored proc command) along with all the parameter names 
        /// and values seperated by /n/r for easy output to the logs if there's a problem with a query - since we're using parameter 
        /// based queries just the command text itself is not helpful for debugging purposes.
        /// </summary>
        /// <param name="pBaseSqlQuery">
        /// The root query included in the resturn string for easy logging - all the parameters included as items in that query are 
        /// added as seperate lines indented under it so the entire string can easily be dumped to a log or the screen for user 
        /// review
        /// </param>
        /// <param name="pCommand">
        /// The ODBCCommand object - this has all the parameters (name and vlaue) 
        /// </param>
        /// <param name="pIndentString">
        /// The string that preceeds each parameter output - defaults to 4 spaces but you can put something like "---->" or the like to
        /// make the output block stand out more or remove it entirely if this is not for display.
        /// </param>
        /// <returns></returns>
        private string GetFullSQLQueryWithParams(string pBaseSqlQuery, IfxCommand pCommand, string pIndentString = "    ")
        {
            string strTemp = pBaseSqlQuery;

            //if there are parameters put them on using indentation and line feeds to make it log out nicely
            if (pCommand.Parameters.Count > 0)
            {
                strTemp += Environment.NewLine + "Parameters:" + Environment.NewLine;

                //since ODBC params are not named, just pring them out in order
                foreach (IfxParameter oParam in pCommand.Parameters)
                {
                    strTemp += string.Format("{0}{1} = {2}{3}", pIndentString, oParam.ParameterName, oParam.Value, Environment.NewLine);
                }
            }
            return strTemp;
        }


        /// <summary>
        /// General routine to pull a configuration data item out of the vw_Configuration view.
        /// An error is logged only if more than one match is found to a full name (which should never happen) - no error
        /// is logged if no match is found as this may be fine.
        /// </summary>
        /// <param name="pFullConfigurationItemName" type="string">
        /// The full name of the configuration data item to return.  This is usually in the format 'System.Conversations.Notification.AllowDeviceCancel'
        /// </param>
        /// <returns>
        /// An empty string is returned if no match is found, the string value otherwise.
        /// </returns>
        public string GetConfigurationString(string pFullConfigurationItemName)
        {

            if (string.IsNullOrEmpty(pFullConfigurationItemName))
            {
                RaiseErrorEvent("(error) empty full name value passed into GetConfigurationString on ConnectionADONETDatabaseFunctions");
                return "";
            }

            RaiseErrorEvent("[debug] GetConfigurationString param pFullConfigurationItemName=" + pFullConfigurationItemName);

            //pull the data from the configuration view
            return GetSingleValueFromQuery("SELECT Value FROM vw_Configuration WHERE FullName=\'" + pFullConfigurationItemName + "\'");
        }      


        /// <summary>
        /// Generates a new remote file name which reserves a slot for uploading a new greeting or voice name to the Connection server.  This file name 
        /// (which is just a GUID) will hang around for a few hours and then be deleted if it's not used by then.  You must get this reserved before you 
        /// can upload any WAV file to the server via HTTP.
        /// </summary>
        /// <returns>
        /// A GUID representing the new file name slot you can use will be returned.  If an empty string is returned there was an error which is logged. 
        /// There's really not a lot of reasons this can fail, however.
        /// </returns>
        public string GetRemoteFileName()
        {
            string strRemoteFileName;

            if (StartNewCommand("csp_allocatevoicefile",true) == false)
            {
                return "";
            }

            //returns the remote file name as the ObjectID return value (the file name is a GUID)
            DbFetchResult ret = ExecuteProc(out strRemoteFileName,"pFileName");
            if (ret.Successful == false)
            {
                RaiseErrorEvent("(error) failure fetching remote file name in GetRemoteFileName on ConnectionADONETDatabaseFunctions:" + ret.ErrorDetails);
                return "";
            }

            return strRemoteFileName;

        }

        /// <summary>
        /// get the primary locaiton information for the server we're connecting to.  This includes the primary location objectID,
        /// the display name of the location, the domain name it lives in, the server address and the version information.
        /// </summary>
        private void FillLocationProperties()
        {
            DataTable oTableLocations;

            //there should only ever be one row returned from this query - if not we have a problem
            DbFetchResult ret = FillDataTableBlocking("SELECT ObjectId FROM vw_LocalVMS", out oTableLocations);
            if (ret.Successful == false)
            {
                RaiseErrorEvent("(error) fetching location properties in FillLocationProperties on ConnectionServer.cs:" + ret.ErrorDetails);
                return;
            }

            if ((oTableLocations != null) && oTableLocations.Rows.Count == 1)
            {
                PrimaryLocationObjectId = oTableLocations.Rows[0]["ObjectID"].ToString();
            }
        }

        /// <summary>
        /// Used to check if a voice name or greeting file is marked for deletion - in versions of Conneciton after 8.6 this is not strictly
        /// necessary but prior to that voice names show up in views after they're deleted but before the background task removes them from
        /// the system which can cause problems.  This returns TRUE if the file has marked for deleltion, FALSE if it's not.
        /// </summary>
        /// <param name="pStreamFileName" type="string">
        /// The full stream file name (i.e. from vw_Subscriber's "VoiceName" column for instance).
        /// </param>
        /// <returns>
        /// TRUE is returned if the file is marked for deleltion, FALSE if it is not.
        /// </returns>
        public bool IsStreamFileMarkedDeleted(string pStreamFileName)
        {
            DateTime dateTemp;

            string strDate = GetSingleValueFromQuery(@"SELECT TimeDeleted FROM vw_StreamFile WHERE FileName='" + pStreamFileName + "'");

            if (strDate.Length == 0)
                return false;

            if (DateTime.TryParse(strDate, out dateTemp) == false)
            {
                //shouldn't happen
                RaiseErrorEvent("(error) converting date in IsStreamFileMarkedDeleted:" + strDate);
                return false;
            }

            if (dateTemp.CompareTo(DateTime.Now) <= 0)
            {
                //date in DB is older than now - file deleted
                return true;
            }
            
            //date in DB is newer than now - file scheduled to be deleted (?) which isn't really supported...
            return false;
        }


        /// <summary>
        /// Function to put a string together that describes the action of a one key link, after message,  
        /// user exit link, after greeting link etc...  This string is used for display, reporting or 
        /// logging purposes as a quick human-readable description.
        /// </summary>
        /// <param name="pConversationName" type="string">
        /// The conversation name associated with the action.  Can be blank for actions such as "1" for 
        /// hangup or "4" for take message.
        /// </param>
        /// <param name="pAction" type="int">
        /// Action ID assocated with link.  Always required, even for a one key set to ignore (action=0).
        /// </param>
        /// <param name="pDestinationObjectId" type="string">
        /// The destination objectID if the action is set to "2" for goto.  Can be blank for other actions.
        /// </param>
        /// <param name="pMenuEntryObjectId" type="string">
        /// If the action is for a manu entry link this should be provided - required if the key is linked to
        /// an alternate contact number.  Can be blank for after greeting or other actions that are not 
        /// menu entries.
        /// </param>
        /// <returns>
        /// A human readable description of the action.
        /// </returns>
        public string GetActionDescription(string pConversationName, int pAction, string pDestinationObjectId, string pMenuEntryObjectId)
        {
            string strTempString;

            //construct the action string starts with the action value - knock off the easy ones first
            switch (pAction)
            {
                case 0:
                    return "Ignore Key";
                case 1:
                    return "Hang Up";
                case 3:
                    return "Goto Error Greeting";
                case 4:
                    return "Take Message";
                case 5:
                    return "Skip Greeting";
                case 6:
                    return "Repeat Greeting";
                case 8:
                    return "Route from next call routing rule";
                case 7:
                    {
                        //alternate transfer number - fetch the transfer string (if any) from the DB
                        strTempString = GetSingleValueFromQuery(@"SELECT TransferNumber FROM vw_AlternateContactNumber WHERE MenuEntryObjectID='" + pMenuEntryObjectId + "'");

                        if (strTempString.Length == 0)
                            strTempString = "[EMPTY]";

                        return "Transfer to alternate contact number:" + strTempString;
                    }

                case 2:
                    {
                        if (string.IsNullOrEmpty(pConversationName))
                        {
                            return "(error) invalid empty conversaton name passed to GetActionDescription on ConnectionADONETDatabaseFunctions";
                        }
                        //the big one - this is the general "goto" action which is used for many things.
                        string strSql;
                        string strRet;
                        DbFetchResult ret;
                        DataTable dtTemp;
                        switch (pConversationName.ToLower())
                        {
                            case "subsignin":
                                return "Route to user sign in";
                            case "greetingsadministrator":
                                return "Route to Greetings administrator";
                            case "convhotelcheckedout":
                                return "Route to checked out hotel guest conversation";
                            case "convcvmmboxreset":
                                return "Route to Community Voice Mail box reset";

                            //a few of these had different names in Unity versions - I leave the overloads in here even though connection does not have this issue
                            case "avconvsystemtransfer":
                            case "subsystransfer":
                                return "Route to user system transfer";
                            case "systemtransfer":
                                return "Route to system transfer";
                            case "avconveasysignin":
                            case "easysignin":
                                return "Route to easy subscriber sign in";
                            case "transferaltcontactnumber":
                                return "Alternate contact number";
                            case "broadcastmessageadministrator":
                                return "Broadcast message administrator";
                            case "ad":
                                {
                                    //name lookup handler - pull the display name for it to return in description
                                    strSql = @"SELECT DisplayName, DTMFAccessID FROM vw_DirectoryHandler WHERE ObjectID='" + pDestinationObjectId + "'";
                                    ret = FillDataTableBlocking(strSql, out dtTemp, true);
                                    if (ret.Successful == false)
                                    {
                                        return "Invalid Link!";
                                    }

                                    return "Route to name lookup handler:" + dtTemp.Rows[0]["DisplayName"];
                                }
                            case "phtransfer":
                                {
                                    //all references to the "attempt transfer for" call handlers or subscribers use this conversation name.
                                    strSql = @"SELECT DisplayName, Recipient_SubscriberObjectID, isPrimary FROM vw_CallHandler WHERE ObjectID='" + pDestinationObjectId + "'";

                                    ret = FillDataTableBlocking(strSql, out dtTemp, true);

                                    if (ret.Successful == false)
                                    {
                                        return "Invalid Link!";
                                    }

                                    //the value in isPrimary can't be anything other than 0 or 1 (or -1 in Unity) - the FK rules prevent it so this cast should be safe.
                                    if ((Int16)dtTemp.Rows[0]["isPrimary"] != 0)
                                    {
                                        //it's a primary call handler associated with a subscriber - fetch the details of the subscriber
                                        strTempString = GetSingleValueFromQuery(@"SELECT DisplayName from vw_Subscriber WHERE ObjectId='"
                                                      + dtTemp.Rows[0]["Recipient_SubscriberObjectID"] + "'");

                                        if (strTempString.Length > 0)
                                            strRet = "Ring phone for subscriber:" + strTempString;
                                        else
                                            //an empty display name for a subscriber is legal
                                            strRet = "Ring phone for subscriber: (empty)";
                                    }
                                    else
                                    {
                                        //it's a non primary (stand alone or "system") call handler
                                        strRet = "Ring phone for call handler=" + dtTemp.Rows[0]["DisplayName"];
                                    }

                                    return strRet;
                                }

                            case "phgreeting":
                                {
                                    //Send to the greeting for a call handler or subscriber
                                    strSql = @"SELECT DisplayName, isPrimary, Recipient_SubscriberObjectID FROM vw_CallHandler WHERE ObjectID='" + pDestinationObjectId + "'";

                                    ret = FillDataTableBlocking(strSql, out dtTemp, true);

                                    if (ret.Successful == false)
                                    {
                                        return "Invalid Link!";
                                    }

                                    //isPrimary can't be anything but 0 or 1 
                                    if ((Int16)dtTemp.Rows[0]["isPrimary"] != 0)
                                    {
                                        //it's a primary call handler associated with a subscriber - fetch the details of the subscriber
                                        strTempString = GetSingleValueFromQuery(@"SELECT DisplayName from vw_Subscriber WHERE ObjectId='"
                                                                               + dtTemp.Rows[0]["Recipient_SubscriberObjectID"] + "'");

                                        if (strTempString.Length > 0)
                                            strRet = "Send to greeting for subscriber:" + strTempString;
                                        else
                                            //Empty display name is legal for a user, just highly dumb
                                            strRet = "Send to greeting for subscriber: (empty)";
                                    }
                                    else
                                    {
                                        //it's a non primary (stand alone or "system") call handler
                                        strRet = "Send to greeting for call handler=" + dtTemp.Rows[0]["DisplayName"];
                                    }

                                    return strRet;
                                }

                            case "phinterview":
                            case "chinterview":
                                {
                                    //Interview handler link
                                    strSql = @"SELECT DisplayName FROM vw_InterviewHandler WHERE ObjectID='" + pDestinationObjectId + "'";
                                    strTempString = GetSingleValueFromQuery(strSql, true, "Invalid Link!");
                                    return "Send to interviewer:" + strTempString;
                                }

                            default:
                                RaiseErrorEvent("(error) unknown conversation name encountered in ConstructActionDescription on ConnectionADONETDatabaseFunctions:" + pConversationName);
                                return "(error) invalid conversation name:" + pConversationName;
                        }
                    }

                default:
                    {
                        RaiseErrorEvent("(error) unknown action ID encountered in ConstructActionDescription on ConnectionADONETDatabaseFunctions:" + pAction.ToString());
                        return ("(error) invalid action ID:" + pAction.ToString());
                    }
            }
        }


        /// <summary>
        /// Returns true if the conversation name passed in is found in Connection's conversation table - false if not.  Used when restoring from
        /// Unity since a few conversations (hotel, CVM for instance) are not supported in Connection.
        /// </summary>
        /// <param name="pConversationName">
        /// Conversation name to check for.
        /// </param>
        /// <returns>
        /// True if the conversation name exists, false if it does not.
        /// </returns>
        public bool ConnectionConversationNameExists(string pConversationName)
        {
            const string strSql = "SELECT COUNT(*) FROM vw_Conversation WHERE fn_tolower(ConversationName)=?";
            return (GetCount(strSql, pConversationName.ToLower()) > 0);
        }


        #endregion


        #region Stored Procedure Methods

        /// <summary>
        /// Starts a new command for the instance of the DBFunctions class - only a single command can be started, edited and then run per instance so by 
        /// calling this routine any existing command for this instance will be wiped out and a new command structure will be started for the stored
        /// procedure name passed in.
        /// </summary>
        /// <param name="pProcedureName" type="string">
        /// The name of the stored procedure - usually starts with 'csp_'
        /// </param>
        /// <param name="pIncludeAuditInfo" type="bool">
        /// Optional variable, defaults to TRUE.  TRUE means the currently logged in user and applicaiton name will be added to the stored proc
        /// parameters automatically for audit logging purposes.  FALSE prevents this.  FALSE should only be used for the handful of stored 
        /// procedures that do not accept the audit component and alias parameters, in all other cases this should always be included.
        /// </param>
        public bool StartNewCommand(string pProcedureName, bool pIncludeAuditInfo = true)
        {
            RaiseDebugEvent("[debug] enter StartNewCommand");
            if (string.IsNullOrEmpty(pProcedureName))
            {
                RaiseErrorEvent("(error) empty procedure name passed to StartNewCommand on ConnectionADONETDatabaseFunctions");
                return false;
            }

            //make sure once we start building a command string that no other process on another thread starts it's own command - one at a
            //time here... 
            if (Monitor.TryEnter(_lockProcBuildObject, LockWaitTimeMs) == false)
            {
                RaiseErrorEvent("(error) Could not get lock to db access in StartNewCommand");
                return false;
            }

            RaiseDebugEvent("** Proc Monitor lock=1 **");

            _commandString = "execute procedure " + pProcedureName.Trim() + " ( ";

            //a few stored procs don't take these params still.
            if (pIncludeAuditInfo)
            {
                AddCommandParam("pAuditAlias", DbParamType.VarChar, LoginName);
                AddCommandParam("pAuditComponent", DbParamType.VarChar, _applicationName);
            }
            return true;
        }


        /// <summary>
        /// Simple routine for helping to construct command strings for running stored procs in Informix.  Each instance of the DBFunctions class will have 
        /// a single Command string structure that is edited by the AddCommandParam and used when the ExecuteProc function is called.  
        /// This is the default entry point for all param adding - all types can be passed as a string (this is how they come out of data tables and the
        /// data reader objects).  Overloads are provided for passing native types instead which improve efficiency somewhat.
        /// </summary>
        /// <param name="pParamName" type="string">
        /// The name of the parameter, usually starts with a 'p'
        /// </param>
        /// <param name="pIfxType" type="System.Data.Odbc.IfxType">
        /// The IfxType - an auto complete list will be provided.
        /// </param>
        /// <param name="pValue" type="string">
        /// The value to be passed to the stored proc.  All values are passed as strings, including numbers and dates.
        /// </param>
        /// <param name="pAddOnlyIfNonZero">
        /// For numeric valus (int, shortint,long...) this will prevent the value from being added to the list of params if it's zero.  Several parameters
        /// in Connection stored procs do not want to be zero...
        ///  </param>
        public bool AddCommandParam(string pParamName, DbParamType pIfxType, string pValue, bool pAddOnlyIfNonZero = false)
        {
            string strTemp;

            if (string.IsNullOrEmpty(pParamName))
            {
                RaiseErrorEvent("(error) empty pParamName passed to AddCommandParam in ConnectionADONETDatabaseFunctions");
                return false;
            }

            //if the value passed is empty then there's nothing for us to do here - exit
            if (string.IsNullOrEmpty(pValue))
            {
                RaiseErrorEvent("empty pValue passed to AddCommandParam in ConnectionADONETDatabaseFunctions");
                return false;
            }

            //if NULL is passed in, treat it special - don't single quote it - this is how you clear a value
            //in the database - if you pass blank it gets ignored.
            if (String.Compare("NULL", pValue, StringComparison.OrdinalIgnoreCase) == 0)
            {
                if (pIfxType == DbParamType.LVarChar | pIfxType == DbParamType.NVarChar)
                {
                    _commandString = _commandString + pParamName + "=NULL::lvarchar,";
                }
                else
                {
                    _commandString = _commandString + pParamName + "=NULL,";
                }
                    
                return true;
            }

            //based on the ODBC data type passed in, construct the param
            switch (pIfxType)
            {

                case DbParamType.NVarChar:
                case DbParamType.LVarChar:
                    strTemp = pValue.QuerySafe();

                    //you must explicitly cast lvarchar to keep Informix happy
                    _commandString = _commandString + pParamName + "=\'" + strTemp + "\'::lvarchar,";
                    break;
                case DbParamType.Bool:
                    if (pValue.Equals("1"))
                    {
                        _commandString = _commandString + pParamName + "=1,";
                    }
                    else
                    {
                        bool bTemp;
                        if (bool.TryParse(pValue, out bTemp))
                        {
                            if (bTemp)
                                _commandString = _commandString + pParamName + "=1,";
                            else
                                _commandString = _commandString + pParamName + "=0,";
                        }
                        else
                        {
                            RaiseErrorEvent("(error) parsing boolean value in AddCommandParam string version:" + pValue);
                            return false;
                        }
                    }
                    break;
                //The time format for Informix is a little fussy
                case DbParamType.DateTime:
                    DateTime myDate;
                    if (DateTime.TryParse(pValue, out myDate) == false)
                    {
                        RaiseErrorEvent("(error) parsing date value in AddCommandParam string version:"+pValue);
                        return false;
                    }
                    strTemp = String.Format("{0:yyyy-MM-dd hh:mm:ss}", myDate);

                    _commandString = _commandString + pParamName + "=\'" + strTemp + "\'::datetime year to fraction,";
                    break;
                case DbParamType.Int:
                case DbParamType.Long:
                case DbParamType.Short:
                    //check to be sure it's a number value in the string
                    int iTemp;
                    if (int.TryParse(pValue.Trim(), out iTemp) == false)
                    {
                        RaiseErrorEvent("(error) Invalid integer value passed into AddCommandParam - strValue=" + pValue +
                                   ", Param name=" + pParamName);
                        return false;
                    }

                    if (pAddOnlyIfNonZero & iTemp == 0)
                    {
                        return true;
                    }

                    _commandString = _commandString + pParamName + "=" + pValue.Trim() + ",";
                    break;

                default:
                    //if it's a string based item, only add it if the string is not empty.  The Connection stored procs are smart enough to
                    //default to forcing an empty value/NULL value as appropriate if the param is not passed in.
                    strTemp = pValue.QuerySafe();

                    if (pValue.Length > 0)
                    {
                        _commandString = _commandString + pParamName + "=\'" + strTemp + "\',";
                    }
                    break;
            }
            return true;
        }

        /// <summary>
        /// simple overload to allow an integer to be passed to the add command param - will allow assigning values if the type passed in is 
        /// an integer, bigInt, smallInt or boolean.  Boolean will evaluate to true for any value no equal to 0.  Other types will throw an 
        /// error.
        /// </summary>
        /// <param name="pParamName"></param>
        /// <param name="pIfxType"></param>
        /// <param name="pValue"></param>
        /// <param name="pAddOnlyIfNonZero">
        /// Only adds the parameter if it's non zero - false by default.
        /// </param>
        public bool AddCommandParam(string pParamName, DbParamType pIfxType, int pValue, bool pAddOnlyIfNonZero = false)
        {
            if (string.IsNullOrEmpty(pParamName))
            {
                RaiseErrorEvent("(error) empty pParamName passed to AddCommandParam integer type in ConnectionADONETDatabaseFunctions");
                return false;
            }

            if (pAddOnlyIfNonZero & pValue==0)
            {
                return true;
            }

            //up convert to a long and call that version of the overload
            return AddCommandParam(pParamName,pIfxType,(long)pValue);
        }

        /// <summary>
        /// Alternative version of AddCommandParam for integer that only adds the command to the building command call if the value passed in 
        /// is greater than or equal to a specified value that defaults to 0.  Many backup DB params can be -1 for "ignore" which use this 
        /// capability for easy code flow.
        /// </summary>
        /// <param name="pParamName"></param>
        /// <param name="pIfxType"></param>
        /// <param name="pValue"></param>
        /// <param name="pAddOnlyIfGreaterThanOrEqualTo">
        /// Minimum value to allow - if the value is less than this the item is not added to the command call.
        /// </param>
        public bool AddCommandParam(string pParamName, DbParamType pIfxType, long pValue, int pAddOnlyIfGreaterThanOrEqualTo)
        {
            if (string.IsNullOrEmpty(pParamName))
            {
                RaiseErrorEvent("(error) empty pParamName passed to AddCommandParam integer type in ConnectionADONETDatabaseFunctions");
                return false;
            }

            if (pValue < pAddOnlyIfGreaterThanOrEqualTo)
            {
                return true;
            }

            //up convert to a long and call that version of the overload
            return AddCommandParam(pParamName, pIfxType, (long)pValue);
        }


        /// <summary>
        /// simple overload to allow an integer to be passed to the add command param - will allow assigning values if the type passed in is 
        /// an integer, bigInt, smallInt or boolean.  True translates to 1, false translates to 0.
        /// </summary>
        /// <param name="pParamName"></param>
        /// <param name="pIfxType"></param>
        /// <param name="pValue"></param>
        public bool AddCommandParam(string pParamName, DbParamType pIfxType, bool pValue)
        {
            if (string.IsNullOrEmpty(pParamName))
            {
                RaiseErrorEvent("(error) empty pParamName passed to AddCommandParam bolean type in ConnectionADONETDatabaseFunctions");
                return false;
            }

            switch (pIfxType)
            {
                case DbParamType.Int:
                case DbParamType.Long:
                case DbParamType.Short:
                case DbParamType.Bool:
                    if (pValue)
                        _commandString = _commandString + pParamName + "=1,";
                    else
                        _commandString = _commandString + pParamName + "=0,";
                    break;
                default:
                    RaiseErrorEvent("(error) invalid DBType passed to AddcommandParam for boolean value on ConnectionADONetDatabaseFunctions.cs:"
                        + pIfxType.ToString());
                    return false;
            }
            return true;
        }


        /// <summary>
        /// simple overload to allow an long to be passed to the add command param - will allow assigning values if the type passed in is 
        /// an integer, bigInt, smallInt or boolean.  Boolean will evaluate to true for any value no equal to 0.  Other types will throw an 
        /// error.
        /// </summary>
        /// <param name="pParamName"></param>
        /// <param name="pIfxType"></param>
        /// <param name="pValue"></param>
        /// <param name="pAddOnlyIfNonZero"> </param>
        public bool AddCommandParam(string pParamName, DbParamType pIfxType, long pValue, bool pAddOnlyIfNonZero = false)
        {
            if (string.IsNullOrEmpty(pParamName))
            {
                RaiseErrorEvent("(error) empty pParamName passed to AddCommandParam long type in ConnectionADONETDatabaseFunctions");
                return false;
            }

            if (pAddOnlyIfNonZero & pValue == 0)
            {
                return true;
            }


            //based on the ODBC data type passed in, construct the param
            switch (pIfxType)
            {
                case DbParamType.Int:
                case DbParamType.Long:
                case DbParamType.Short:
                    {
                        _commandString = _commandString + pParamName + "=" + pValue.ToString() + ",";
                    }
                    break;
                case DbParamType.Bool:
                    if (pValue == 0)
                        _commandString = _commandString + pParamName + "=0,";
                    else
                        _commandString = _commandString + pParamName + "=1,";
                    break;
                default:
                    RaiseErrorEvent("(error) invalid DBType passed to AddcommandParam for integer value on ConnectionADONetDatabaseFunctions.cs:"
                        + pIfxType.ToString());
                    return false;
            }
            return true;
        }

        /// <summary>
        /// simple overload to allow a DateTime to be passed to the add command param - will allow assigning values if the type passed in is 
        /// a Date.  
        /// </summary>
        /// <param name="pParamName"></param>
        /// <param name="pIfxType"></param>
        /// <param name="pValue"></param>
        public bool AddCommandParam(string pParamName, DbParamType pIfxType, DateTime pValue)
        {
            if (string.IsNullOrEmpty(pParamName))
            {
                RaiseErrorEvent("(error) empty pParamName passed to AddCommandParam Date type in ConnectionADONETDatabaseFunctions");
                return false;
            }


            if (pIfxType != DbParamType.DateTime)
            {
                RaiseErrorEvent("(error) invalid IfxType value passed to AddcommandParam for DateTime value on " +
                           "ConnectionADONetDatabaseFunctions.cs:"+pIfxType.ToString());
                return false;
            }

            //force the date/time into the format Informix likes.
            string strTemp = String.Format("{0:yyyy-MM-dd hh:mm:ss}", pValue);

            _commandString = _commandString + pParamName + "=\'" + strTemp + "\'::datetime year to fraction,";

            return true;
        }


        /// <summary>
        /// simple function to call built up stored proc - this version returns no value (and expects none from the stored proc which can be 
        /// important as some procs fail if you run them expecting a return value or vice versa).
        /// </summary>
        /// <returns>
        ///     True is returned if the stored proc executes, False if an error is thrown.
        /// </returns>
        public DbFetchResult ExecuteProc()
        {
            //strip off trailing comma
            _commandString = _commandString.Remove(_commandString.Length - 1);
            _commandString = _commandString + ")";

            return CallStoredProcNoRet(_commandString);

        }


        /// <summary>
        /// Overload the execut proc function for calling parties that wish to get details back - some procs require you accept a return value
        /// from them to execute cleanly (i.e. most create procs that return an ObjectID for instance).        
        /// </summary>
        /// <param name="pObjectIdReturn" type="string">
        ///  strObjectIDReturn is an out argument that is used to pass back an ObjectID value (assuming one is generated).
        /// </param>
        /// <param name="pObjectIdColumnName" type="string">
        /// strObjectIDColumnName is an optional parameter that you can use to specify which column name in the return set holds the ObjectID.  If 
        /// this is not passed in then the first column found is returned which is usually the only one returned anyway.
        /// Some stored procedures will return multiple columns in the return recordset, however, so passing in the explicit columnd name is necessary.
        /// </param>
        /// <param name="pIgnoreReturnValue">
        /// Some stored procs are poorly designed and require a return value and do not provide a way to suppress FK errors (i.e. such as creating 
        /// a private list member - no way to ignore the error thrown if that member already exists).  One way to deal with this is to call the 
        /// proc with a return value but ignore it - supressing any errors that result from one not being returned.
        ///  </param>
        /// <returns>
        /// A Cisco.Unity.Connection.DBFetchResult - this contains the success boolean flag and a ErrorDetails string for display/logging purposes
        /// if something fails.
        /// </returns>
        public DbFetchResult ExecuteProc(out string pObjectIdReturn, string pObjectIdColumnName = "", bool pIgnoreReturnValue=false)
            
        {
            //strip off trailing comma
            _commandString = _commandString.Remove(_commandString.Length - 1);
            _commandString = _commandString + ")";

            return CallStoredProc(_commandString, out pObjectIdReturn, pObjectIdColumnName,pIgnoreReturnValue);

        }


        /// <summary>
        /// This routine takes a fully qualified command string (includes stored proc names and all params) and calls it on the
        /// remote Informix DB.  TRUE is returned if it execute clean (so far as we know - Informix is tight lipped sometimes) and
        /// FALSE otherwsie.  The runction will attempt to fetch the returned ObjectID value using the name of the param the calling
        /// function passes in - if the param is empty it'll get "field 0" instead and try to pass it back.
        /// All error strings are passed back via the byRef variable strError so the calling routine can log it - this helps prevent issues
        /// with multiple threads using these routines.
        /// </summary>
        /// <param name="pExecuteString" type="string">
        ///  The private string being constructed in this class isntance using the AddCommandParam and StartStoreProc calls.
        /// </param>
        /// <param name="pObjectIdReturn" type="string">
        ///  If the procedure generates a new ObjectID (i.e. a create proc) the value is passed back in this out param.
        /// </param>
        /// <param name="pObjectIdColumnName" type="string">
        ///  strObjectIDColumnName is an optional parameter that you can use to specify which column name in the return set holds the ObjectID.  If 
        ///  this is not passed in then the first column found is returned which is usually the only one returned anyway.
        ///  Some stored proced        
        /// </param>
        /// <param name="pIgnoreReturnValue">
        /// Some stored procs did not bother to provide a "suppress error" option when adding an item that already exists in a collection - most do 
        /// but a few (such as private list member create) do not - these must be called expecting a return value or they don't work but when you 
        /// fetch the return value a FK contraint error is thrown - passing this a "TRUE" will suppress that error for these special cases.
        ///  </param>
        /// <returns>
        ///  A Cisco.Unity.Connection.DBFetchResult - this contains the success boolean flag and a ErrorDetails string for display/logging purposes
        ///  if something fails.
        /// </returns>
        private DbFetchResult CallStoredProc(string pExecuteString, out string pObjectIdReturn, string pObjectIdColumnName = "", 
                                             bool pIgnoreReturnValue=false)
        {
            IfxDataReader drTemp = null;
            DbFetchResult ret = new DbFetchResult();
            pObjectIdReturn = "";

            RaiseDebugEvent("[debug] Entering CallStoredProc in ConnectionADONETDatabaseFunctions, pExecuteString=:" +pExecuteString);

            ret.Successful = true;
            ret.ErrorDetails = "";

            try
            {
                //if we lose our connection notify the user and exit
                if ((_iFxConnection == null) || (_iFxConnection.State != ConnectionState.Open))
                {
                    //make an attempt to reconnect on the fly first
                    if (CycleDatabaseConnection() == false)
                    {
                        ret.ErrorDetails = "ODBC Connection to server is closed.";
                        ret.Successful = false;
                        RaiseErrorEvent("(error) IfxConnection is not open in CallStoredProc");
                        return ret;
                    }
                }

                if (String.IsNullOrEmpty(pExecuteString) || (pExecuteString.Length<24))
                {
                    ret.ErrorDetails =
                        "(error) invalid executeString value passed into CallSToredPRoc on ConnectionODBCDatabseFunctions: empty string";
                    ret.Successful = false;
                    return ret;
                }

                if (Monitor.TryEnter(_lockCommandObject, LockWaitTimeMs) == false)
                {
                    RaiseErrorEvent("(error) Could not get lock to db access in CallStoredProc");
                    ret.ErrorDetails = "Could not get lock for db access";
                    return ret;
                }

                try
                {
                    //we use a single shared ODBC connection for all DB fetches on each DB class instance - Connection limits how many attachments are
                    //allowed at any given time so we need to keep control over that.
                    _command.Parameters.Clear();
                    _command.Connection = _iFxConnection;
                    _command.CommandType = CommandType.Text;
                    _command.CommandText = pExecuteString;

                    //none of our stored procs returns a table - only a single row - most of the time a single value but not always.
                    try
                    {
                        drTemp = _command.ExecuteReader(CommandBehavior.SingleRow);
                        RaiseDebugEvent("[debug] command execution complete");
                    }
                    catch (Exception ex)
                    {
                        //This error comes up often enough and it's harmless - downgrade it to a warning and move on here.
                        //Unfortunately the error number we get back from the ODBC driver is usually just the same one so we need to parse the text of the 
                        //error out to identify it.
                        if (ex.Message.Contains("The credential matches a previous credential"))
                        {
                            ret.Successful = false;
                            ret.ErrorDetails = "(warning) the PIN for the subscriber password matches a previous PIN for this user - the authentication rules do"
                                               + " not allow for this, PIN has not been reset.  Informix return=" +
                                               ex.Message;
                            ret.SQLQuery = GetFullSQLQueryWithParams(pExecuteString, _command);
                        }
                        else
                        {
                            ret.Successful = false;
                            ret.ErrorDetails =
                                "CallStoredProc on ConnectionADONETDatabaseFunctions returned error on execute: \n" +
                                ex.Message;
                            ret.SQLQuery = GetFullSQLQueryWithParams(pExecuteString, _command);
                            RaiseErrorEvent("(error) " + ret.ErrorDetails);
                            if (drTemp != null) drTemp.Close();
                            return ret;
                        }
                    }

                    if (drTemp == null)
                    {
                        //no records returned but no error raised
                        ret.Successful = false;
                        ret.ErrorDetails = "No ObjectID returned in CallStoredProc on ConnectionADONETDatabaseFunctions";
                        ret.SQLQuery = GetFullSQLQueryWithParams(pExecuteString, _command);
                        RaiseErrorEvent("(error) " + ret.ErrorDetails);
                        return ret;
                    }

                    //if an error of any kind came back it's a failure, return.
                    if (ret.Successful == false)
                    {
                        drTemp.Close();
                        return ret;
                    }

                    //oddly enough, if the stored proc ran but a contstraint error was violated, it does not raise an error.  
                    try
                    {
                        ret.Successful = drTemp.Read();
                    }
                    catch (Exception ex)
                    {
                        //if the calling method is not interested in the return value, suppress this error
                        if (!pIgnoreReturnValue)
                        {
                            ret.Successful = false;
                            ret.ErrorDetails = "Stored Procedure raised an error enumerating return values: " +
                                               ex.Message;
                            ret.SQLQuery = GetFullSQLQueryWithParams(pExecuteString, _command);
                        }
                        drTemp.Close();
                        return ret;
                    }

                    //usually when there's a return value there's only one and you just grab it from slot 0.  In a few cases there will
                    //be more than one and you can fetch it by column name if it's passed in.
                    if (pObjectIdColumnName.Length == 0)
                    {
                        try
                        {
                            pObjectIdReturn = drTemp[0].ToString();
                        }
                        catch (Exception ex)
                        {
                            //return the error and log it as well
                            ret.Successful = false;
                            ret.ErrorDetails =
                                "(error) in CallStoredProc fetching return value from stored procedure: " + ex.Message;
                            ret.SQLQuery = GetFullSQLQueryWithParams(pExecuteString, _command);
                            RaiseErrorEvent(ret.ErrorDetails);
                        }
                    }
                    else
                    {
                        pObjectIdReturn = drTemp[pObjectIdColumnName].ToString();
                    }
                    drTemp.Close();

                }
                catch (Exception ex)
                {
                    RaiseErrorEvent("Error executing stored procedure:" + ex);
                }
                finally
                {
                    Monitor.Exit(_lockCommandObject);
                }
            }
            catch (Exception ex)
            {
                RaiseErrorEvent("Error in CallStoredProc:"+ex);
            }
            finally
            {
                //make sure we release the proc build object lock in all cases when this is called
                try
                {
                    Monitor.Exit(_lockProcBuildObject);
                    RaiseDebugEvent("** Proc Monitor lock=0 **");
                }
                catch (Exception ex)
                {
                    RaiseErrorEvent("(error) releasing _lockProcBuildObject in CallStoredProc:"+ex);
                }
            }

            return ret;
    }

        /// <summary>
        /// If a client has started a stored proc and has to abort before completing it then they need to clear
        /// the monitor lock by calling this method
        /// </summary>
        public void ClearProcMonitor()
        {
            RaiseDebugEvent("[debug] enter ClearProcMonitor");
            try
            {
                Monitor.Exit(_lockProcBuildObject);
                RaiseDebugEvent("** Proc Monitor lock=0 **");
            }
            catch (Exception ex)
            {
                RaiseErrorEvent("(error) releasing _lockProcBuildObject in GetProcString:" + ex);
            }
        }

        /// <summary>
        /// If the user is just constructing the stored procedure string for reference (i.e. learning) reasons, finish off the 
        /// stored proc construciton format, return the string and release the monitor lock for adding params.
        /// </summary>
        /// <returns>
        /// Full string showing execution of stored proc with parameters
        /// </returns>
        public string GetProcString()
        {
            RaiseDebugEvent("[debug] enter GetProcString");
            if (string.IsNullOrEmpty(_commandString))
            {
                return "";
            }

            //strip off trailing comma
            _commandString = _commandString.Remove(_commandString.Length - 1);
            _commandString = _commandString + ")";

            try
            {
                Monitor.Exit(_lockProcBuildObject);
                RaiseDebugEvent("** Proc Monitor lock=0 **");
            }
            catch (Exception ex)
            {
                RaiseErrorEvent("(error) releasing _lockProcBuildObject in GetProcString:" + ex);
            }

            return _commandString;
        }

        /// <summary>
        /// This is the same as CallSToredProc, but no ObjectID value is expected to be returned
        /// All error strings are returned via the ByRef variable so the calling routine can log it.
        /// TRUE is returned if all is well, FALSE if there was an error thrown (details in the byref strError)
        /// </summary>
        /// <param name="pExecuteString" type="string">
        /// The private string being constructed in this class isntance using the AddCommandParam and StartStoreProc calls.
        /// </param>
        /// <returns>
        /// A Cisco.Unity.Connection.DBFetchResult - this contains the success boolean flag and a ErrorDetails string for display/logging purposes
        /// if something fails.
        /// </returns>
        private DbFetchResult CallStoredProcNoRet(string pExecuteString)
        {
            var ret = new DbFetchResult { Successful = true, ErrorDetails = "" };

            RaiseDebugEvent("[debug] Entering CallStoredProcNoRet in ConnectionADONETDatabaseFunctions, pExecuteString=:" +
               pExecuteString);

            try
            {
                //if we lose our connection notify the user and exit
                if ((_iFxConnection == null) || (_iFxConnection.State != ConnectionState.Open))
                {
                    //make an attempt to reconnect on the fly first
                    if (CycleDatabaseConnection() == false)
                    {
                        ret.ErrorDetails = "ODBC connection to server is closed.";
                        ret.Successful = false;
                        RaiseErrorEvent("(error) IfxConnection is not open in CallSToredProc_NoRet");
                        return ret;
                    }
                }

                if (String.IsNullOrEmpty(pExecuteString) || pExecuteString.Length<24)
                {
                    ret.ErrorDetails = "(error) invalid executeString value passed into CallSToredPRoc_NoRet";
                    ret.Successful = false;
                    return ret;
                }

                if (Monitor.TryEnter(_lockCommandObject, LockWaitTimeMs) == false)
                {
                    RaiseErrorEvent("(error) Could not get lock to db access in CallStoredProc");
                    ret.ErrorDetails = "Could not get lock for db access";
                    return ret;
                }

                //we use a single shared ODBC connection for all DB fetches on each DB class instance - Connection limits how many attachments are
                //allowed at any given time so we need to keep control over that.
                _command.Parameters.Clear();
                _command.Connection = _iFxConnection;
                _command.CommandType = CommandType.Text;
                _command.CommandText = pExecuteString;

                try
                {
                    _command.ExecuteNonQuery();
                    RaiseDebugEvent("[debug] command execution complete");
                }
                catch (Exception ex)
                {
                    ret.ErrorDetails = "(error) StoredProc returned error on execute: " + ex.Message;
                    ret.Successful = false;
                    ret.SQLQuery = GetFullSQLQueryWithParams(pExecuteString, _command);
                }
                finally
                {
                    Monitor.Exit(_lockCommandObject);
                }
            }
            catch (Exception ex)
            {
                RaiseErrorEvent("Error executing CallSToredProcNoRet:"+ex);
            }
            finally
            {
                //make sure we release the proc build object lock in all cases when this is called
                try
                {
                    Monitor.Exit(_lockProcBuildObject);
                    RaiseDebugEvent("** Proc Monitor lock=0 **");
                }
                catch (Exception ex)
                {
                    RaiseErrorEvent("(error) releasing _lockProcBuildObject in CallSToredProcnoRet:"+ex);
                }
            }
            return ret;

        }


        #endregion


        #region Data Fetch Functions

        //shared helper method for adding parameters of various types passed for parameterized query
        //constructions
        private void AddParameters(IfxCommand pCommand, params object[] pParams)
        {
            if (pParams != null)
            {
                //parameters are positional, not named - just tack them on with no name here, the type is determined on the fly.
                foreach (object oParam in pParams)
                {
                    IfxParameter dbparam = new IfxParameter();

                    if (oParam is IfxParameter)
                    {
                        pCommand.Parameters.Add(oParam);
                    }
                    else if (oParam is string)
                    {
                        dbparam.IfxType = IfxType.NVarChar;
                        dbparam.Value = oParam;
                        pCommand.Parameters.Add(dbparam);
                    }
                    else if (oParam is bool | oParam is int | oParam is short | oParam is long)
                    {
                        pCommand.Parameters.Add("", oParam);
                    }
                    else
                    {
                        pCommand.Parameters.Add("", oParam.ToString());
                    }
                }
            }
        }

        /// <summary>
        /// Allows you to fetch a single value from a table or view.  All values are returned as strings
        /// so it's up to the calling routing to cast it if necessary.
        /// NOTE - the query should return a single value (column) - the first item is always returned regardless.
        /// If you pass TRUE for supress error, no error is logged, just an empty string is returned - this is for 
        /// cases where the calling client wants to just check for the existence of a value without raising an error.
        /// Use the parameterized query format whenever possible!
        /// </summary>
        /// <param name="pQueryString" type="string">
        /// The full SQL query against the UnityDirDB database (talbe or view).  It should return a single value.
        /// </param>
        /// <param name="pSuppressErrorOnNoData" type="bool">
        /// If TRUE no error is raised if the query returns no value.  FALSE will cause those conditions to log
        /// an error.
        /// </param>
        /// <param name="pNoDataReturnString" type="string">
        /// If no data is returned this string value is resturned from the function.  By default this is an empty string 
        /// but you can use "(error)" or "[no data]" or the like depending on the needs.  Saves having to check for empty
        /// string by the client to populate output appropriately for instance.
        /// </param>
        /// <param name="pParams">
        /// list of items to be added as parameters when using a parameterized query.  With ODBC the parameters are not named but just ordered so 
        /// a query that looks like "Select Alias FORM vw_User WHERE IsTemplate=? and ObjectId=?" would take a 0 or 1 followed by an object ID
        /// string as parameters in that order so they get filled in properly.
        /// </param>
        /// <returns>
        /// A string value from the database or the pNoDataReturnString value if no data is returned.
        /// </returns>
        public string GetSingleValueFromQuery(string pQueryString, bool pSuppressErrorOnNoData = false, string pNoDataReturnString = "", params object[] pParams)
        {

            IfxDataReader drTemp = null;

            RaiseDebugEvent(string.Format("[debug] GetSingleValueFromQuery server=[{0}] param pQueryString={1}", DatabaseServerName, pQueryString));

            //if we lose our connection notify the user and exit
            if ((_iFxConnection == null) || (_iFxConnection.State != ConnectionState.Open))
            {
                //make an attempt to reconnect on the fly first
                if ((CycleDatabaseConnection() == false) || _iFxConnection == null)
                {
                    RaiseErrorEvent("(error) IfxConnection is not open in GetSingleValueFromQuery");
                    return "";
                }
            }

            using (IfxCommand oCommand = _iFxConnection.CreateCommand())
            {
                oCommand.Parameters.Clear();
                oCommand.CommandType = CommandType.Text;
                oCommand.Connection = _iFxConnection;
                oCommand.CommandText = pQueryString;

                AddParameters(oCommand, pParams);

                //execute the query
                try
                {
                    drTemp = oCommand.ExecuteReader();
                }
                catch (Exception ex)
                {
                    RaiseErrorEvent("(error) in GetSingleValueFromQuery on ConnectionADONETDatabaseFunctions:" + ex.Message);
                }

                string strRet;
                if (drTemp == null || !drTemp.HasRows || drTemp.Read() == false)
                {
                    if (pSuppressErrorOnNoData == false)
                    {
                        RaiseErrorEvent("(error) Query returned no rows in GetSingleValueFromQuery on ConnectionADONETDatabaseFunctions:" + pQueryString);
                    }
                    strRet = pNoDataReturnString;
                }
                else
                {
                    strRet = drTemp[0].ToString();
                }

                if (drTemp != null) drTemp.Close();
                return strRet;
            }

        }


        /// <summary>
        /// Returns a list of mailstore names that are active on the target connection server.
        /// Returns and empty list if there's an error, returns a list of strings that are the mailstore DB names
        /// otherwise.  There should always be at least one.
        /// </summary>
        /// <returns>
        /// A System.Collections.Generic.List of strings containing all the mailstore names active on the current Connection server.  
        /// By default this is only 1 item but systems support up to 6 currently, more probably to come.
        /// </returns>
        public List<string> GetMailstoresList()
        {
            List<string> retList = new List<string>();
            IfxDataReader drTemp;

            //error executing query
            DbFetchResult ret = FillDataReader("SELECT MailDatabase FROM vw_MailboxStoreMap", out drTemp);
            if (ret.Successful == false)
            {
                RaiseErrorEvent("(error) fetching MailDatabse values from vw_MailboxStoreMap in GetMailstoresList on ConnectionADONETDatabaseFunctions:"+ret.ErrorDetails);
                if (drTemp != null) drTemp.Close();
                return retList;
            }

            //No valid system has zero mailstores
            if (drTemp.Read() == false)
            {
                RaiseErrorEvent("(error) No mailstores found in GetMailstoresList on ConnectionADONETDatabaseFunctions");
                drTemp.Close();
                return retList;
            }

            //add each mailstore name to the list returned
            do
            {
                retList.Add(drTemp[0].ToString());
            } while (drTemp.Read());

            drTemp.Close();
            return retList;
        }


        /// <summary>
        /// returns the primary DTMFAccessID (extenson) for any objectId you pass in if any - blank is returned if no extension is found.
        /// search for contacts, users, call handlers, interview handlers, name lookup handlers or distribution lsits.
        /// </summary>
        /// <param name="pParentObjectId" type="string">
        /// The objectId of the user, handler, contact or public distribution list that you're searching against.
        /// </param>
        /// <returns>
        /// The DTMFAccessID (extension) listed as primary (only users can have alternate extensions) for the ObjectID passed in.  If no extension 
        /// is found a blank string is returned.
        /// </returns>
        public string GetPrimaryDtmfAccessId(string pParentObjectId)
        {
            DataTable dtTemp;

            string strRet = "";

            string strSql = string.Format("SELECT DTMFAccessID FROM vw_DTMFAccessID WHERE " +
                                                   "Parent_ContactObjectID='{0}' OR " +
                                                   "Parent_DistributionListObjectID= '{0}' OR " +
                                                   "Parent_GlobalUserObjectID='{0}' OR " +
                                                   "Parent_HandlerObjectID= '{0}' AND " +
                                                   "IDIndex=0", pParentObjectId);
            
            var res = FillDataTableBlocking(strSql, out dtTemp);
            if (res.Successful == false)
            {
                RaiseErrorEvent("(warning) error finding Primary DTMFAccessId using ParentObjectID=" + pParentObjectId +
                           " in GetPRimaryDTMFAccessID on ConnectionADONETDatabaseFunctions:" + res);
            }
            else
            {
                if (dtTemp.Rows.Count > 0)
                {
                    strRet = dtTemp.Rows[0][0].ToString();
                }
            }
           
            return strRet;
        }


        /// <summary>
        /// Returns the alias of a user or contact - this is useful for getting human readable
        /// identifier information for private list membership data among other things
        /// </summary>
        /// <param name="pObjectId" type="string">
        /// The ObjectID of the user or contact that you're searching against.
        /// </param>
        /// <returns>
        /// The alias string of the user or contact is returned if found.  An empty string is returned otherwise.
        /// </returns>
        public string GetAliasOfObject(string pObjectId)
        {
            string strRet = "";
            DataTable dtTemp;

           const string strSql = "SELECT Alias from vw_Alias WHERE Object_GlobalUserObjectID=? or Object_ContactObjectId=?";
           
           var res= FillDataTableBlocking(strSql, out dtTemp,false,pObjectId,pObjectId);

            if (res.Successful==false)
            {
               RaiseErrorEvent("(error) in GetAliasOfObject in ConnectionADONETDatabaseFunctions:" + res);
            }
            else
            {
                if (dtTemp.Rows.Count > 0)
                {
                    strRet = dtTemp.Rows[0][0].ToString();
                }
            }

            return strRet;
        }


        /// <summary>
        /// Pass in a count query (i.e. "SELECT COUNT(*) FROM vw_user WHERE...") and this routine will return that number as an integer.  
        /// Use the parameterized query format whenever possible!
        /// </summary>
        /// <param name="pCountQueryString" type="string">
        /// Count SQL query string in the form "SELECT COUNT(*) FROM vw_user WHERE..."
        /// </param>
        /// <param name="pParams">
        /// list of items to be added as parameters when using a parameterized query.  With ODBC the parameters are not named but just ordered so a query that 
        /// looks like "Select Alias FORM vw_User WHERE IsTemplate=? and ObjectId=?" would take a 0 or 1 followed by an object ID string as parameters in that order
        /// so they get filled in properly.
        /// </param>
        /// <returns>
        /// 0 is returned if there is an error or no data is found.  The number generated by the count query is returned otherwise.
        /// </returns>
        public int GetCount(string pCountQueryString, params object[] pParams)
        {
            int iTemp;

            RaiseDebugEvent(string.Format("[debug] GetCount server=[{0}] param pCountQueryString={1}", DatabaseServerName, pCountQueryString));

            //if we lose our connection notify the user and exit
           if ((_iFxConnection == null) || (_iFxConnection.State != ConnectionState.Open))
            {
                //make an attempt to reconnect on the fly first
                if (CycleDatabaseConnection() == false)
                {
                    RaiseErrorEvent("(error) IfxConnection is not open in GetCount");
                    return 0;
                }
            }

           if (Monitor.TryEnter(_lockCommandObject, LockWaitTimeMs) == false)
           {
               RaiseErrorEvent("(error) Could not get lock to db access in GetCount");
               return 0;
           }

               _command.Parameters.Clear();
               _command.CommandType = CommandType.Text;
               _command.Connection = _iFxConnection;
               _command.CommandText = pCountQueryString;

               AddParameters(_command, pParams);

               try
               {
                   //the scalar returns decimal - cast it to an Int32 here.
                   object oRet = _command.ExecuteScalar();
                   if (Int32.TryParse(oRet.ToString(), out iTemp) == false)
                   {
                       RaiseErrorEvent("(warning) could not cast value to int in GetCount on ConnectionADODbDatabaseFunctions:"+oRet);
                   }
               }
               catch (Exception ex)
               {
                   RaiseErrorEvent("(error) in GetCount on ConnectionOBECDatabaseFunctions:" + ex.Message);
                   iTemp = 0;
               }
               finally
               {
                   Monitor.Exit(_lockCommandObject);       
               }

            return iTemp;

        }


        /// <summary>
        /// Executes a command against the database that does not return a recordset - this is normally used for UPDATE, INSERT and DELETE requests.  
        /// Note that you should NOT be doing updates and deletes via this command, you should ALWAYS be using stored procedures.  This is provided 
        /// for rare cases when you need to perform such an action but as a rule this should never be called in a production application.
        /// </summary>
        /// <param name="pQueryString">
        /// query to execute
        /// </param>
        /// <param name="pParams">
        /// list of items to be added as parameters when using a parameterized query.  With ODBC the parameters are not named but just ordered so a query that 
        /// looks like "Select COUNT(*) FROM vw_User WHERE IsTemplate=? and ObjectId=?" would take a 0 or 1 followed by an object ID string as parameters in that 
        /// order so they get filled in properly.
        /// </param>
        /// <returns>
        /// Number of records affected by the call.
        /// </returns>
        public int ExecuteNonQuery(string pQueryString, params object[] pParams)
        {
            int iTemp;

            RaiseDebugEvent(string.Format("[debug] ExecuteNonQuery server=[{0}] param pQueryString={1}", DatabaseServerName, pQueryString));

            //if we lose our connection notify the user and exit
            if ((_iFxConnection == null) || (_iFxConnection.State != ConnectionState.Open))
            {
                //make an attempt to reconnect on the fly first
                if (CycleDatabaseConnection() == false)
                {
                    RaiseErrorEvent("(error) IfxConnection is not open in GetCount");
                    return 0;
                }
            }

            if (Monitor.TryEnter(_lockCommandObject, LockWaitTimeMs) == false)
            {
                RaiseErrorEvent("(error) Could not get lock to db access in GetCount");
                return 0;
            }

            _command.Parameters.Clear();
            _command.CommandType = CommandType.Text;
            _command.Connection = _iFxConnection;
            _command.CommandText = pQueryString;

            AddParameters(_command, pParams);

            try
            {
                //the scalar returns decimal - cast it to an Int32 here.
                object oRet = _command.ExecuteNonQuery();
                if (Int32.TryParse(oRet.ToString(), out iTemp) == false)
                {
                    RaiseErrorEvent("(warning) could not cast value to int in GetCount on ConnectionADODbDatabaseFunctions:" + oRet);
                }
            }
            catch (Exception ex)
            {
                RaiseErrorEvent("(error) in ExecuteNonQuery on ConnectionOBECDatabaseFunctions:" + ex.Message);
                iTemp = 0;
            }
            finally
            {
                Monitor.Exit(_lockCommandObject);
            }

            return iTemp;

        }

        /// <summary>
        /// Function that provides a way to look for conflicts for alias and/or extension for users.  This is handy for providing human readable error 
        /// messages when creating new users and there is a conflict with another user.
        /// </summary>
        /// <param name="pAlias" type="string">
        /// The Alias to search against.  If a blank is passed then just the extension is used.  If non blank is passed then an alias match is required.
        /// </param>
        /// <param name="pExtension" type="string">
        /// The Extension (DTMFAccessID) to search against.  Only the primary extension is searched for in this case, not alternates.  If this is passed in
        /// as blank then the alias is the only item searched on.  If it's non blank a match for primary extension is required.
        /// </param>
        /// <param name="pRestrictSearchToLocalOnly" type="bool">
        /// TRUE means restrict searches to users homed on the current Conneciton server, FALSE means check the global (networked) user tables.
        /// </param>
        /// <param name="pMatchCountReturn" type="int">
        /// Returns 0 if no match found, 1 if a single match found and 2 if 2 or more matches are found.
        /// </param>
        /// <param name="pObjectIdReturn" type="string">
        /// The ObjectID of the first user found if one or more matches are found, blank string returned if no match is found.
        /// </param>
        /// <param name="pMatchDescriptionReturn" type="string">
        /// Returns "No match found" if no match and "Multiple users match alias and extension" if 2 or more matches are found.  
        /// Blank is returned for a single match.
        /// </param>
        /// <returns>
        /// TRUE is returned if a match is found for either alias or extension.  FALSE otherwise.  If a single match is found the ObjectID of the 
        /// matching user is passed via the strObjectID ref string.  If multiple matches are found this information is indicated in the 
        /// strMatchDescription ref variable.
        /// </returns>
        public bool FindUserByAliasOrExtension(string pAlias, string pExtension, bool pRestrictSearchToLocalOnly, out int pMatchCountReturn,
                                                            out string pObjectIdReturn, out string pMatchDescriptionReturn)
        {
            string strSql;
            DataTable dtTemp;

            pMatchDescriptionReturn = "Error searching for matches";
            pObjectIdReturn = "";
            pMatchCountReturn = 0;

            if (string.IsNullOrEmpty(pAlias) & string.IsNullOrEmpty(pExtension))
            {
                RaiseErrorEvent("(error) empty alias and extension passed to FindUserByAliasOrExtension");
                return false;
            }

            if ((!string.IsNullOrEmpty(pAlias)) && (!string.IsNullOrEmpty(pExtension)))
            {
                strSql = "SELECT ObjectID FROM vw_GlobalUser WHERE PartitionObjectID IS NOT NULL AND IsTemplate= 0 AND fn_tolower(Alias)::varchar(64) = \'"
                          + pAlias.QuerySafe().ToLower() + "\' AND DTMFAccessID=\'" + pExtension + "\'";
            }
            else if (!string.IsNullOrEmpty(pAlias))
            {
                //just alias passed in
                strSql = "SELECT ObjectID FROM vw_GlobalUser WHERE PartitionObjectID IS NOT NULL AND IsTemplate= 0 AND fn_tolower(Alias)::varchar(64) = \'"
                          + pAlias.QuerySafe().ToLower() + "\'";
            }
            else
            {
                //just extension passed in
                strSql = "SELECT ObjectID FROM vw_GlobalUser WHERE PartitionObjectID IS NOT NULL AND IsTemplate= 0 AND DTMFAccessID=\'" + pExtension + "\'";
            }

            //restrict the search to local users only if instructed
            if (pRestrictSearchToLocalOnly)
            {
                strSql = strSql + " AND LocationObjectID=\'" + PrimaryLocationObjectId + "\'";
            }


            DbFetchResult ret = FillDataTableBlocking(strSql, out dtTemp);
            if (ret.Successful == false)
            {
                RaiseErrorEvent("(error) in fetching users FindUserByAliasOrExtension in ConnectionADONETDatabaseFunctions with query=" + strSql+"\nError="+ret.ErrorDetails);
                return false;
            }

            if (dtTemp == null || dtTemp.Rows.Count==0)
            {
                //not necessarily an error - just return here as a no match
                pMatchDescriptionReturn = "No matches found";
                return false;
            }

            //snag the objectID of the user and return it via the byRef variable
            pObjectIdReturn = dtTemp.Rows[0][0].ToString();

            //ok - we have one row, check to see if there's more
            if (dtTemp.Rows.Count>1)
            {
                //oops - more than one row
                pMatchCountReturn = 2;
                pMatchDescriptionReturn = "Multiple users match alias and extension";
                return false;
            }
            pMatchCountReturn = 1;
            return true;
        }



        /// <summary>
        /// Function that provides a way to look for conflicts for name and/or extension for handlers.  This is handy for providing human readable error 
        /// messages when creating new handlers and there is a conflict with another handler.
        /// </summary>
        /// <param name="pDisplayName" type="string">
        /// The display name to search against.  If a blank is passed then just the extension is used.  If non blank is passed then a name match is required.
        /// </param>
        /// <param name="pExtension" type="string">
        /// The Extension (DTMFAccessID) to search against.  If this is passed in as blank then the name is the only item searched on.  If it's non 
        /// blank a match for primary extension is required.
        /// </param>
        /// <param name="pMatchCountReturn" type="int">
        /// Returns 0 if no match found, 1 if a single match found and 2 if 2 or more matches are found.
        /// </param>
        /// <param name="pObjectIdReturn" type="string">
        ///  The ObjectID of the first handler found if one or more matches are found, blank string returned if no match is found.
        /// </param>
        /// <param name="pMatchDescriptionReturn" type="string">
        ///  Returns "No match found" if no match and "Multiple handlers match name and extension" if 2 or more matches are found.  
        ///  Blank is returned for a single match.
        /// </param>
        /// <returns>
        /// TRUE is returned if a match is found for either name or extension.  FALSE otherwise.  If a single match is found the ObjectID of the 
        /// matching handler is passed via the strObjectID out string.  If multiple matches are found this information is indicated in the 
        /// strMatchDescription out variable.
        /// </returns>
        public bool FindHandlerByNameOrExtension(string pDisplayName, string pExtension, out int pMatchCountReturn,
                                                            out string pObjectIdReturn, out string pMatchDescriptionReturn)
        {
            string strSql;
            DataTable dtTemp;

            pMatchDescriptionReturn = "Error searching for matches";
            pObjectIdReturn = "";
            pMatchCountReturn = 0;

            if (string.IsNullOrEmpty(pDisplayName) & string.IsNullOrEmpty(pExtension))
            {
                RaiseErrorEvent("(error) empty display name and extension passed to FindHandlerByNameOrExtension");
                return false;
            }

            //both name and extension passed in.
            if ((!string.IsNullOrEmpty(pDisplayName)) && (!string.IsNullOrEmpty(pExtension)))
            {
                strSql = string.Format("SELECT ObjectID FROM vw_CallHandler WHERE PartitionObjectID IS NOT NULL AND IsTemplate= 0 and IsPrimary = 0 AND " +
                                       "fn_tolower(DisplayName)::varchar(64) = '{0}'"
                         + " AND DTMFAccessID='{1}'",pDisplayName.QuerySafe().ToLower(), pExtension);
            }
            else if (!string.IsNullOrEmpty(pDisplayName))
            {
                //just display name passed in
                strSql = string.Format("SELECT ObjectID FROM vw_CallHandler WHERE PartitionObjectID IS NOT NULL AND IsTemplate= 0 and IsPrimary = 0 " +
                                       "AND fn_tolower(DisplayName)::varchar(64) = '{0}'"
                         , pDisplayName.QuerySafe().ToLower());
            }
            else
            {
                //just extension passed in
                strSql = string.Format("SELECT ObjectID FROM vw_CallHandler WHERE PartitionObjectID IS NOT NULL AND IsTemplate= 0 and IsPrimary = 0 AND "
                         + " DTMFAccessID='{0}'", pExtension);
            }

            //note that we're not using parameterized queries here - any time you use "fn_tolower" the informix driver has difficulty with parameters - it 
            //throws up a meaningless "unknown sql type" error so in this case we're doing it all inline.
            DbFetchResult ret = FillDataTableBlocking(strSql, out dtTemp);
            if (ret.Successful == false)
            {
                RaiseErrorEvent("(error) in fetching handlers in FindHandlerByNameOrExtension in ConnectionADONETDatabaseFunctions with query=" +
                    strSql + "\nError=" + ret.ErrorDetails);
                return false;
            }

            if (dtTemp == null || dtTemp.Rows.Count==0)
            {
                //not necessarily an error - just return here as a no match
                pMatchDescriptionReturn = "No matches found";
                return false;
            }

            //snag the objectID of the user and return it via the out variable
            pObjectIdReturn = dtTemp.Rows[0][0].ToString();
            pMatchDescriptionReturn = "";
            pMatchCountReturn++;

            //check for more than one match.
            if (dtTemp.Rows.Count>1)
            {
                pMatchDescriptionReturn = "Multiple handlers match name and extension";
                pMatchCountReturn = 2;
                return false;
            }
            return true;
        }


        /// <summary>
        /// Function that provides a way to look for conflicts for name and/or extension for interview handlers.  This is handy for providing human 
        /// readable error messages when creating new handlers and there is a conflict with another handler.
        /// </summary>
        /// <param name="pDisplayName" type="string">
        /// The display name to search against.  If a blank is passed then just the extension is used.  If non blank is passed then a name match is required.
        /// </param>
        /// <param name="pExtension" type="string">
        /// The Extension (DTMFAccessID) to search against.  If this is passed in as blank then the name is the only item searched on.  If it's non 
        /// blank a match for primary extension is required.
        /// </param>
        /// <param name="pMatchCountReturn" type="int">
        /// Returns 0 if no match found, 1 if a single match found and 2 if 2 or more matches are found.
        /// </param>
        /// <param name="pObjectIdReturn" type="string">
        ///  The ObjectID of the first handler found if one or more matches are found, blank string returned if no match is found.
        /// </param>
        /// <param name="pMatchDescriptionReturn" type="string">
        ///  Returns "No match found" if no match and "Multiple handlers match name and extension" if 2 or more matches are found.  
        ///  Blank is returned for a single match.
        /// </param>
        /// <returns>
        /// TRUE is returned if a match is found for either name or extension.  FALSE otherwise.  If a single match is found the ObjectID of the 
        /// matching handler is passed via the strObjectID out string.  If multiple matches are found this information is indicated in the 
        /// strMatchDescription out variable.
        /// </returns>
        public bool FindInterviewHandlerByNameOrExtension(string pDisplayName, string pExtension, out int pMatchCountReturn,
                                                           out string pObjectIdReturn, out string pMatchDescriptionReturn)
        {
            string strSql;
            DataTable dtTemp;

            pMatchDescriptionReturn = "Error searching for matches";
            pObjectIdReturn = "";
            pMatchCountReturn = 0;

            if (string.IsNullOrEmpty(pDisplayName) & string.IsNullOrEmpty(pExtension))
            {
                RaiseErrorEvent("(error) empty alias and extension passed to FindInterviewHandlerByNameOrExtension");
                return false;
            }

            //both name and extension passed in.
            if ((!string.IsNullOrEmpty(pDisplayName)) && (!string.IsNullOrEmpty(pExtension)))
            {
                strSql = string.Format("SELECT ObjectID FROM vw_InterviewHandler WHERE PartitionObjectID IS NOT NULL AND " +
                                       "fn_tolower(DisplayName)::varchar(64) = '{0}'" +
                                        " AND DTMFAccessID='{1}'", pDisplayName.QuerySafe().ToLower(), pExtension);
            }
            else if (!string.IsNullOrEmpty(pDisplayName))
            {
                //just display name passed in
                strSql = string.Format("SELECT ObjectID FROM vw_InterviewHandler WHERE PartitionObjectID IS NOT NULL " +
                                       "AND fn_tolower(DisplayName)::varchar(64) = '{0}'"
                         , pDisplayName.QuerySafe().ToLower());
            }
            else
            {
                //just extension passed in
                strSql = string.Format("SELECT ObjectID FROM vw_InterviewHandler WHERE PartitionObjectID IS NOT NULL AND "
                         + " DTMFAccessID='{0}'", pExtension);
            }

            //note that we're not using parameterized queries here - any time you use "fn_tolower" the informix driver has difficulty with parameters - it 
            //throws up a meaningless "unknown sql type" error so in this case we're doing it all inline.
            DbFetchResult ret = FillDataTableBlocking(strSql, out dtTemp);
            if (ret.Successful == false)
            {
                RaiseErrorEvent("(error) in fetching handlers in FindInterviewHandlerByNameOrExtension in ConnectionADONETDatabaseFunctions with query=" +
                    strSql + "\nError=" + ret.ErrorDetails);
                return false;
            }

            if (dtTemp == null || dtTemp.Rows.Count==0)
            {
                //not necessarily an error - just return here as a no match
                pMatchDescriptionReturn = "No matches found";
                return false;
            }

            //snag the objectID of the user and return it via the out variable
            pObjectIdReturn = dtTemp.Rows[0][0].ToString();
            pMatchDescriptionReturn = "";
            pMatchCountReturn++;

            //check for more than one match.
            if (dtTemp.Rows.Count>1)
            {
                pMatchDescriptionReturn = "Multiple interview handlers match name and extension";
                pMatchCountReturn = 2;
                return false;
            }
            return true;
        }


        /// <summary>
        /// Function that provides a way to look for conflicts for name and/or extension for name lookup handlers.  This is handy for providing human 
        /// readable error messages when creating new handlers and there is a conflict with another handler.
        /// </summary>
        /// <param name="pDisplayName" type="string">
        /// The display name to search against.  If a blank is passed then just the extension is used.  If non blank is passed then a name match is required.
        /// </param>
        /// <param name="pExtension" type="string">
        /// The Extension (DTMFAccessID) to search against.  If this is passed in as blank then the name is the only item searched on.  If it's non 
        /// blank a match for primary extension is required.
        /// </param>
        /// <param name="pMatchCountReturn" type="int">
        /// Returns 0 if no match found, 1 if a single match found and 2 if 2 or more matches are found.
        /// </param>
        /// <param name="pObjectIdReturn" type="string">
        ///  The ObjectID of the first handler found if one or more matches are found, blank string returned if no match is found.
        /// </param>
        /// <param name="pMatchDescriptionReturn" type="string">
        ///  Returns "No match found" if no match and "Multiple handlers match name and extension" if 2 or more matches are found.  
        ///  Blank is returned for a single match.
        /// </param>
        /// <returns>
        /// TRUE is returned if a match is found for either name or extension.  FALSE otherwise.  If a single match is found the ObjectID of the 
        /// matching handler is passed via the strObjectID out string.  If multiple matches are found this information is indicated in the 
        /// strMatchDescription out variable.
        /// </returns>
        public bool FindNameLookupHandlerByNameOrExtension(string pDisplayName, string pExtension, out int pMatchCountReturn,
                                                           out string pObjectIdReturn, out string pMatchDescriptionReturn)
        {
            string strSql;
            DataTable dtTemp;

            pMatchDescriptionReturn = "Error searching for matches";
            pObjectIdReturn = "";
            pMatchCountReturn = 0;

            if (string.IsNullOrEmpty(pDisplayName) & string.IsNullOrEmpty(pExtension))
            {
                RaiseErrorEvent("Empty display name and extension passed to FindNameLookupHandlerByNanmeOrExtension");
                return false;
            }

            //both name and extension passed in.
            if ((!string.IsNullOrEmpty(pDisplayName)) && (!string.IsNullOrEmpty(pExtension)))
            {
                strSql = string.Format("SELECT ObjectID FROM vw_DirectoryHandler WHERE PartitionObjectID IS NOT NULL AND " +
                                       "fn_tolower(DisplayName)::varchar(64) = '{0}'" +
                                        " AND DTMFAccessID='{1}'", pDisplayName.QuerySafe().ToLower(), pExtension);
            }
            else if (!string.IsNullOrEmpty(pDisplayName))
            {
                //just display name passed in
                strSql = string.Format("SELECT ObjectID FROM vw_DirectoryHandler WHERE PartitionObjectID IS NOT NULL " +
                                       "AND fn_tolower(DisplayName)::varchar(64) = '{0}'"
                         , pDisplayName.QuerySafe().ToLower());
            }
            else
            {
                //just extension passed in
                strSql = string.Format("SELECT ObjectID FROM vw_DirectoryHandler WHERE PartitionObjectID IS NOT NULL AND "
                         + " DTMFAccessID='{0}'", pExtension);
            }

            //note that we're not using parameterized queries here - any time you use "fn_tolower" the informix driver has difficulty with parameters - it 
            //throws up a meaningless "unknown sql type" error so in this case we're doing it all inline.
            DbFetchResult ret = FillDataTableBlocking(strSql, out dtTemp);
            if (ret.Successful == false)
            {
                RaiseErrorEvent("(error) in fetching handlers in FindNameLookupHandlerByNameOrExtension in ConnectionADONETDatabaseFunctions with query=" +
                    strSql + "\nError=" + ret.ErrorDetails);
                return false;
            }

            if (dtTemp == null || dtTemp.Rows.Count==0)
            {
                //not necessarily an error - just return here as a no match
                pMatchDescriptionReturn = "No matches found";
                return false;
            }

            //snag the objectID of the user and return it via the out variable
            pObjectIdReturn = dtTemp.Rows[0][0].ToString();
            pMatchDescriptionReturn = "";
            pMatchCountReturn++;

            //check for more than one match.
            if (dtTemp.Rows.Count>1)
            {
                pMatchDescriptionReturn = "Multiple name lookup handlers match name and extension";
                pMatchCountReturn = 2;
                return false;
            }
            return true;
        }


        /// <summary>
        /// Function that provides a way to look for conflicts for name and/or extension for name distribution lists.  This is handy for providing human 
        /// readable error messages when creating new lists and there is a conflict with another list.
        /// </summary>
        /// <param name="pAlias" type="string">
        /// The alias to search against.  If a blank is passed then just the extension is used.  If non blank is passed then an alias match is required.
        /// </param>
        /// <param name="pName">
        /// Display name
        ///  </param>
        /// <param name="pExtension" type="string">
        /// The Extension (DTMFAccessID) to search against.  If this is passed in as blank then the name is the only item searched on.  If it's non 
        /// blank a match for extension is required.
        /// </param>
        /// <param name="pMatchCountReturn" type="int">
        /// Returns 0 if no match found, 1 if a single match found and 2 if 2 or more matches are found.
        /// </param>
        /// <param name="pObjectIdReturn" type="string">
        ///  The ObjectID of the first list found if one or more matches are found, blank string returned if no match is found.
        /// </param>
        /// <param name="pMatchDescriptionReturn" type="string">
        ///  Returns "No match found" if no match and "Multiple lists match name and extension" if 2 or more matches are found.  
        ///  Blank is returned for a single match.
        /// </param>
        /// <param name="pSearchLocalPartitionOnly">
        /// If passed as true the seach for lists is restricted to those owned by the local Connection server, defaults to false which gets all lists
        /// in the directory
        /// </param>
        /// <returns>
        /// TRUE is returned if a match is found for either name or extension.  FALSE otherwise.  If a single match is found the ObjectID of the 
        /// matching list is passed via the strObjectID out string.  If multiple matches are found this information is indicated in the 
        /// strMatchDescription out variable.
        /// </returns>
        public bool FindDistributionListByAliasNameOrExtension(string pAlias, string pName, string pExtension, out int pMatchCountReturn,
                                                           out string pObjectIdReturn, out string pMatchDescriptionReturn, bool pSearchLocalPartitionOnly=false)
        {
            string strSql;
            DataTable dtTemp;

            pMatchDescriptionReturn = "Error searching for matches";
            pObjectIdReturn = "";
            pMatchCountReturn = 0;

            if (string.IsNullOrEmpty(pAlias) & string.IsNullOrEmpty(pName) & string.IsNullOrEmpty(pExtension))
            {
                RaiseErrorEvent("Empty alias, name and extension passed to FindDistributionListByAliasNameOrExtension");
                return false;
            }

            //All three passed in
            if ((!string.IsNullOrEmpty(pAlias)) && (!string.IsNullOrEmpty(pExtension)) && !string.IsNullOrEmpty(pName))
            {
                strSql = string.Format("SELECT ObjectID,Alias FROM vw_DistributionList WHERE PartitionObjectID IS NOT NULL AND " +
                                  "fn_tolower(Alias)::varchar(64) = '{0}' " +
                                  "AND fn_tolower(DisplayName)::varchar(64) = '{1}'" +
                                  " AND DTMFAccessID='{2}'", pAlias.QuerySafe().ToLower(), pName.QuerySafe().ToLower(),
                                  pExtension);
            }
                //just name and alias passed in
            else if ((!string.IsNullOrEmpty(pAlias)) && !string.IsNullOrEmpty(pName))
            {
                strSql =
                    string.Format("SELECT ObjectID,Alias FROM vw_DistributionList WHERE PartitionObjectID IS NOT NULL AND " +
                                  "fn_tolower(Alias)::varchar(64) = '{0}' " +
                                  "AND fn_tolower(DisplayName)::varchar(64) = '{1}'",
                                  pAlias.QuerySafe().ToLower(), pName.QuerySafe().ToLower());
            }
                //alias and extension
            else if ((!string.IsNullOrEmpty(pAlias)) && (!string.IsNullOrEmpty(pExtension)))
            {
                strSql =
                    string.Format("SELECT ObjectID,Alias FROM vw_DistributionList WHERE PartitionObjectID IS NOT NULL AND " +
                                  "fn_tolower(Alias)::varchar(64) = '{0}'" +
                                  " AND DTMFAccessID='{1}'", pAlias.QuerySafe().ToLower(), pExtension);
            }
                //name and extension
            else if ((!string.IsNullOrEmpty(pExtension)) && !string.IsNullOrEmpty(pName))
            {
                strSql = string.Format("SELECT ObjectID,Alias FROM vw_DistributionList WHERE PartitionObjectID IS NOT NULL AND " +
                                  "fn_tolower(DisplayName)::varchar(64) = '{0}'" +
                                  " AND DTMFAccessID='{1}'", pName.QuerySafe().ToLower(),pExtension);
            }
            else if (!string.IsNullOrEmpty(pAlias))
            {
                //just alias passed in
                strSql = string.Format("SELECT ObjectID,Alias FROM vw_DistributionList WHERE PartitionObjectID IS NOT NULL " +
                                       "AND fn_tolower(Alias)::varchar(64) = '{0}'", pAlias.QuerySafe().ToLower());
            }
            else if (!string.IsNullOrEmpty(pName))
            {
                //just name
                strSql = string.Format("SELECT ObjectID,Alias FROM vw_DistributionList WHERE PartitionObjectID IS NOT NULL " +
                                       "AND fn_tolower(DisplayName)::varchar(64) = '{0}'", pName.QuerySafe().ToLower());
            }
            else
            {
                //just extension passed in
                strSql = string.Format("SELECT ObjectID,Alias FROM vw_DistributionList WHERE PartitionObjectID IS NOT NULL AND "
                         + " DTMFAccessID='{0}'", pExtension);
            }

            if (pSearchLocalPartitionOnly)
            {
                strSql += string.Format(" AND LocationObjectId='{0}'",PrimaryLocationObjectId);
            }

            //note that we're not using parameterized queries here - any time you use "fn_tolower" the informix driver has difficulty with parameters - it 
            //throws up a meaningless "unknown sql type" error so in this case we're doing it all inline.
            DbFetchResult ret = FillDataTableBlocking(strSql, out dtTemp);
            if (ret.Successful == false)
            {
                RaiseErrorEvent("(error) in fetching data in FindDistributionListByAliasOrExtension in ConnectionADONETDatabaseFunctions with query=" +
                    strSql + "\nError=" + ret.ErrorDetails);
                return false;
            }

            if (dtTemp == null || dtTemp.Rows.Count==0)
            {
                //not necessarily an error - just return here as a no match
                pMatchDescriptionReturn = "No matches found";
                return false;
            }

            //snag the objectID of the user and return it via the out variable
            pObjectIdReturn = dtTemp.Rows[0]["ObjectID"].ToString();
            pMatchDescriptionReturn = "Distribution List with alias="+dtTemp.Rows[0]["Alias"];
            pMatchCountReturn++;

            //check for more than one match.
            if (dtTemp.Rows.Count>1)
            {
                pMatchDescriptionReturn = "Multiple lists match name and extension";
                pMatchCountReturn = 2;
                return false;
            }
            return true;
        }


        /// <summary>
        /// Function to fill a data reader passed back as an out param from a query against the Connection server passed in.
        /// WARNING: Each data reader that's open will keep it's own DB connection - only a single data reader is allowed per instance of
        /// the ConnectonODBDDatabaseFunctions class - the client needs to close the data reader before opening another one.  It's best to
        /// use a DataSet instead if possible.  DataSets are contained entirely on the client side and do not keep a connection open however
        /// data readers are faster and easier to use for large amount of data.        
        /// Use the parameterized query format whenever possible!
        /// </summary>
        /// <param name="pQueryString" type="string">
        /// Full SQL query string to execute against Connection's database.
        /// </param>
        /// <param name="pDataReader" type="System.Data.Odbc.IfxDataReader">
        /// out param for an IfxDataReader object
        /// </param>
        /// <param name="pFailIfNoData" type="bool">
        /// optional flag that causes the routing to reuturn FALSE if the resulting data reader has no rows.  By default this is FALSE meaning that
        /// so long as the query executes without errors TRUE is returned even if no data was retrieved.        
        /// </param>
        /// <param name="pParams">
        /// list of items to be added as parameters when using a parameterized query.  With ODBC the parameters are not named but just ordered so a 
        /// query that looks like "Select Alias FORM vw_User WHERE IsTemplate=? and ObjectId=?" would take a 0 or 1 followed by an object ID string 
        /// as parameters in that order so they get filled in properly.
        /// </param>
        /// <returns>
        /// A Cisco.Unity.Connection.DBFetchResult - this contains the success boolean flag and a ErrorDetails string for display/logging purposes
        /// if something fails.        
        /// </returns>
        public DbFetchResult FillDataReader(string pQueryString, out IfxDataReader pDataReader, bool pFailIfNoData=false, params object[] pParams)
        {
            DbFetchResult ret = new DbFetchResult {Successful = true, ErrorDetails = "", SQLQuery = ""};

            RaiseDebugEvent(string.Format("[debug] FillDataReader server=[{0}] param pQueryString={1}", DatabaseServerName, pQueryString));

            pDataReader = null;

            //if we lose our connection notify the user and exit
           if ((_iFxConnection == null) || (_iFxConnection.State != ConnectionState.Open))
            {
                //make an attempt to reconnect on the fly first
                if (CycleDatabaseConnection() == false)
                {
                    ret.Successful = false;
                    ret.ErrorDetails = "ODBC Connection to server is closed.";
                    RaiseErrorEvent("(error) IfxConnection is not open in FillDataReader");
                    return ret;
                }
            }

           if (Monitor.TryEnter(_lockCommandObject, LockWaitTimeMs) == false)
           {
               RaiseErrorEvent("(error) Could not get lock for DB access in FillDataReader");
               ret.ErrorDetails = "Timed out waiting for DB lock to free";
               return ret;
           }

           try
           {
               //we use a single _Command object at the class level here to ensure only a single connection is used by any given tool.  If the calling routines
               //try an open multiple data readers at one time instead of using data sets this will throw an error and prevent the tool from chewing through 
               //connections.  
               _command.Parameters.Clear();
               _command.CommandType = CommandType.Text;
               _command.Connection = _iFxConnection;
               _command.CommandText = pQueryString;

               AddParameters(_command, pParams);

               try
               {
                   pDataReader = _command.ExecuteReader();
               }
               catch (Exception ex)
               {
                   ret.Successful = false;
                   ret.ErrorDetails = ex.ToString();
                   ret.SQLQuery = GetFullSQLQueryWithParams(pQueryString, _command);
                   RaiseErrorEvent("(error) in FillDataReader on ConnectionOBECDatabaseFunctions:" + ex.Message);
                   return ret;
               }

               //if the caller asks for empty data to return FALSE take care of that here.
               if (pFailIfNoData && (pDataReader.Read() == false))
               {
                   ret.Successful = false;
                   ret.ErrorDetails = "No data returned on a query that required results";
                   ret.SQLQuery = GetFullSQLQueryWithParams(pQueryString, _command);
               }
           }
           catch (Exception ex)
           {
               RaiseErrorEvent("(error) in FillDataReader on ConnectionOBECDatabaseFunctions:" + ex.Message);
           }
           finally
           {
                Monitor.Exit(_lockCommandObject);
           }

            return ret; 
        }


        /// <summary>
        /// Function to fill a data table passed back via out param with data from a query against the Connection server passed in.   
        /// This routine runs on the main thread and is blocking.
        /// A data table can only pass back information in a single table, it cannot handle multiple selects creating multiple tables. If you
        /// need that kind of additional functionality use the FillDataSet routines instead.
        /// Use the parameterized query formate whenever possible!
        /// </summary>
        /// <param name="pQueryString" type="string">
        /// Full SQL Query to execute on the Connection server's database
        /// </param>
        /// <param name="pDataTable" type="System.Data.DataTable">
        /// dataTable object pasted back as an out param
        /// </param>
        /// <param name="pFailIfNoData" type="bool">
        /// optional flag that causes the routing to reuturn FALSE if the resulting data reader has no rows.  By default this is FALSE meaning that
        /// so long as the query executes without errors TRUE is returned even if no data was retrieved.                
        /// </param>
        /// <param name="pParams">
        /// list of items to be added as parameters when using a parameterized query.  With ODBC the parameters are not named but just ordered so a query that 
        /// looks like "Select Alias FORM vw_User WHERE IsTemplate=? and ObjectId=?" would take a 0 or 1 followed by an object ID string as parameters in that order
        /// so they get filled in properly.
        /// </param>
        /// <returns>
        /// A Cisco.Unity.Connection.DBFetchResult - this contains the success boolean flag and a ErrorDetails string for display/logging purposes
        /// if something fails.
        /// </returns>
        public DbFetchResult FillDataTableBlocking(string pQueryString, out DataTable pDataTable, bool pFailIfNoData = false, params object[] pParams)
        {
            DbFetchResult ret = new DbFetchResult {Successful = true};
            pDataTable = new DataTable();

            RaiseDebugEvent(string.Format("[debug] FillDataTableBlocking server=[{0}] param pQueryString={1}", DatabaseServerName, pQueryString));

            //if we lose our connection notify the user and exit
            if ((_iFxConnection == null) || (_iFxConnection.State != ConnectionState.Open))
            {
                //make an attempt to reconnect on the fly first
                if (CycleDatabaseConnection() == false)
                {
                    ret.ErrorDetails = "database Connection to server is closed.";
                    ret.Successful = false;
                    RaiseErrorEvent("(error) IfxConnection is not open in FillDataTableBlocking");
                    return ret;
                }
            }

            if (Monitor.TryEnter(_lockCommandObject, LockWaitTimeMs) == false)
            {
                RaiseErrorEvent("(error) Could not get lock for database access in FillDataTableBlocking");
                ret.ErrorDetails = "Timed out waiting for DB lock to free";
                return ret;
            }

            //This routine uses it's own command object and then disposes of it - the data set is returned and the connection used
            //to build it are disposed.  This does allow for 2 DB connections to be active at any given time but will limit it to that 
            //which is acceptable.  Connection allows for 10 by default.
            using (IfxCommand oCommand = new IfxCommand(pQueryString, _iFxConnection))
            {
                AddParameters(oCommand, pParams);

                using (IfxDataAdapter oDataAdapter = new IfxDataAdapter(oCommand))
                {
                    try
                    {
                        oDataAdapter.Fill(pDataTable);
                    }
                    catch (Exception ex)
                    {
                        ret.ErrorDetails = ex.Message;
                        ret.Successful = false;
                        ret.SQLQuery = GetFullSQLQueryWithParams(pQueryString, _command);
                        RaiseErrorEvent("(error) in FillDataSetBlocking on ConnectionOBECDatabaseFunctions:" + ex.Message);
                        return ret;
                    }
                    finally
                    {
                        Monitor.Exit(_lockCommandObject);
                    }
                }
            }

            //if the calling routine is expecting data (they pass in the pFailIfNoData flag) check for rows and bail out here.
            if (pFailIfNoData && (pDataTable.Rows.Count == 0))
            {
                ret.ErrorDetails = "No data returned on a query that required data to be returned";
                ret.Successful = false;
            }

            return ret;

        }

        /// <summary>
        /// Returns TRUE if there is a conflict with an extension in the partiton provided, false if there is no.  If there is a conflict a 
        /// description of the conflicting object type is returned in the pMatchDescription string.
        /// </summary>
        /// <param name="pDtmfAccessId">
        /// The extension to search for
        /// </param>
        /// <param name="pPartitionObjectId">
        /// The partition to search in
        /// </param>
        /// <param name="pMatchDescription">
        /// If there's a conflict the description of the conflicting object is returned here, otherwise this is empty.
        /// </param>
        /// <returns>
        /// TRUE is returned if there is a matching extension, FALSE if there is not.
        /// </returns>
        public bool ExtensionExists(string pDtmfAccessId, string pPartitionObjectId, out string pMatchDescription)
        {
            pMatchDescription = "";

            if (string.IsNullOrEmpty(pDtmfAccessId) | string.IsNullOrEmpty(pPartitionObjectId))
            {
                RaiseErrorEvent("Empty DTMFAccessId or Partition passed to ExtensionExists");
                return false;
            }

            const string strSql = "SELECT * from vw_DtmfaccessId WHERE DTMFAccessId=? AND PartitionObjectId=?";
            DataTable oTable;
            DbFetchResult res = FillDataTableBlocking(strSql, out oTable, false, pDtmfAccessId, pPartitionObjectId);
            if (res.Successful == false)
            {
                RaiseErrorEvent("(error) fetching data in CheckForExtensionConflict on ConnectionADONETDatabaseFunctions:" + res);
                return false;
            }

            if (oTable.Rows.Count == 0)
            {
                return false;
            }

            ObjectsTypesWithExtensions oObjectType = ObjectsTypesWithExtensions.User;
            string strObjectId = "";

            //it'd be nice if there were a "partent object type" field still around but currently you have to manually check each and every ObjectID
            //type column to see what the parent object type is.  Painful but unavoidable.
            if (oTable.Rows[0]["parent_contactObjectId"].ToString().Length > 0)
            {
                oObjectType = ObjectsTypesWithExtensions.Contact;
                strObjectId = oTable.Rows[0]["parent_contactObjectId"].ToString();
            }

            else if (oTable.Rows[0]["parent_distributionListObjectId"].ToString().Length > 0)
            {
                oObjectType = ObjectsTypesWithExtensions.PublicDistributionList;
                strObjectId = oTable.Rows[0]["parent_distributionListObjectId"].ToString();
            }
            if (oTable.Rows[0]["parent_GlobalUserObjectId"].ToString().Length > 0)
            {
                oObjectType = ObjectsTypesWithExtensions.User;
                strObjectId = oTable.Rows[0]["parent_GlobalUserObjectId"].ToString();
            }
            if (oTable.Rows[0]["parent_HandlerObjectId"].ToString().Length > 0)
            {
                oObjectType = ObjectsTypesWithExtensions.Handler;
                strObjectId = oTable.Rows[0]["parent_HandlerObjectId"].ToString();
            }
            if (oTable.Rows[0]["parent_LocationObjectId"].ToString().Length > 0)
            {
                oObjectType = ObjectsTypesWithExtensions.Location;
                strObjectId = oTable.Rows[0]["parent_LocationObjectId"].ToString();
            }
            if (oTable.Rows[0]["parent_SubscriberObjectId"].ToString().Length > 0)
            {
                oObjectType = ObjectsTypesWithExtensions.User;
                strObjectId = oTable.Rows[0]["parent_SubscriberObjectId"].ToString();
            }

            //construct the description item.
            pMatchDescription = GetObjectDescription(strObjectId, oObjectType);

            return true;
        }

        /// <summary>
        /// Pulls a description of a Connection object that has an extension from the database - helper function for displaying information 
        /// about conflicting extensions so the admin can know WHAT object it's conflicting with and not just that there's a conflict.
        /// </summary>
        /// <param name="pObjectId">
        /// Object's unique id
        /// </param>
        /// <param name="pObjectType">
        /// Type of object to search for.
        /// </param>
        /// <returns>
        /// Description of the object and it's type or an error string if there's a problem finding it.
        /// </returns>
        public string GetObjectDescription(string pObjectId, ObjectsTypesWithExtensions pObjectType)
        {
            string strSql;
            string strDescripiton;
            DataTable oTable;


            switch (pObjectType)
            {
                case ObjectsTypesWithExtensions.Handler:
                    //we have to do ANOTHER lookup to tell what kind of handler this is - very, very annoying
                    string strObjectType = GetSingleValueFromQuery("SELECT ObjectType FROM vw_Handler WHERE ObjectId=?", false, "", pObjectId);
                    if (strObjectType.Length == 0)
                    {
                        RaiseErrorEvent("(error) unable to get objectType for handler in GetObjectDescription on ConnectionObjectDatabaseFunctions.cs:" + pObjectId);
                        return "[Unknown Handler Type]";
                    }

                    if (strObjectType.Equals("3")) //call handler
                    {
                        strDescripiton = "[Call Hanlder] ";
                        strSql = "SELECT DisplayName, DTMFAccessId FROM vw_CallHandler WHERE ObjectId=?";
                    }
                    else if (strObjectType.Equals("6")) //directory handler
                    {
                        strDescripiton = "[Name Lookup Hanlder] ";
                        strSql = "SELECT DisplayName, DTMFAccessId FROM vw_DirectoryHandler WHERE ObjectId=?";
                    }
                    else if (strObjectType.Equals("5")) //interview handler
                    {
                        strDescripiton = "[Interview Handler] ";
                        strSql = "SELECT DisplayName, DTMFAccessId FROM vw_InterviewHandler WHERE ObjectId=?";
                    }
                    else
                    {
                        RaiseErrorEvent("(error) unknown handler type encountered in in GetObjectDescription on ConnectionObjectDatabaseFunctions.cs:" + strObjectType);
                        return "[Unknown Handler Type]";
                    }
                    break;
                case ObjectsTypesWithExtensions.User:
                    strDescripiton = "[User] ";
                    strSql = "SELECT DisplayName, DTMFAccessId FROM vw_GlobalUser WHERE ObjectId=?";
                    break;
                case ObjectsTypesWithExtensions.PublicDistributionList:
                    strDescripiton = "[Distribution List] ";
                    strSql = "SELECT DisplayName, DTMFAccessId FROM vw_DistributionList WHERE ObjectId=?";
                    break;
                case ObjectsTypesWithExtensions.Contact:
                    strDescripiton = "[Contact] ";
                    strSql = "SELECT DisplayName, DTMFAccessId FROM vw_Contact WHERE ObjectId=?";
                    break;
                case ObjectsTypesWithExtensions.Location:
                    strDescripiton = "[Location] ";
                    strSql = "SELECT DisplayName, DTMFAccessId FROM vw_Location WHERE ObjectId=?";
                    break;

                default:
                    RaiseErrorEvent("(error) invalid object type passed to GetObjectDescription:" + pObjectType.ToString());
                    return "(error) invalid object type passed to GetObjectDescription:" + pObjectType.ToString();
            }

            DbFetchResult res = FillDataTableBlocking(strSql, out oTable, false, pObjectId);

            if (res.Successful == false)
            {
                RaiseErrorEvent("(error) fetching data in GetObjectDescription on ConnectionADONETDatabaseFunctions.cs:" + res);
                return "(error): " + res;
            }

            //this should never happen but just in case
            if (oTable.Rows.Count == 0)
            {
                RaiseErrorEvent("(error) no match found for object in GetObjectDescription on ConnectionADONETDatabaseFunctions with query=" + 
                    res.SQLQuery);
                return ("[NO MATCH FOUND]");
            }

            strDescripiton += oTable.Rows[0]["DisplayName"].ToString();

            //tack on the extension if it's there
            if (oTable.Rows[0]["DTMFAccessID"].ToString().Length > 0)
            {
                strDescripiton += " x " + oTable.Rows[0]["DTMFAccessId"];
            }

            return strDescripiton;
        }

        #endregion

    }
}

Commits for ConnectionOdbcSdk/trunk/ConnectionServer/ConnectionInformixAdoNetDatabaseFunctions.cs

Diff revisions: vs.
Revision Author Commited Message
18 Diff Diff jlindborg picture jlindborg Thu 17 Oct, 2013 18:29:43 +0000

renaming main ConnectionServerOdbc class to match convention for REST SDKs

17 Diff Diff jlindborg picture jlindborg Tue 10 Sep, 2013 19:18:58 +0000

2.0.4
Basics for the dev guide in – more notes on helper functions, examples for proc calls and how to use REST and ODBC SDKs together needed before the NuGet download can be made public.

16 Diff Diff jlindborg picture jlindborg Tue 10 Sep, 2013 00:16:23 +0000

2.0.4
working on the dev guide and making various minor fixes to the database function methods during that process.

15 Diff Diff jlindborg picture jlindborg Sun 08 Sep, 2013 17:27:35 +0000

2.0.3
Changed class name to be CiscoUnityConnectionServerOdbc
Updated to support 32 or 64 bit projects
Changed order of parameters on login methods at server and DB functions class to match.
Started testing for NuGet package deployment.
Dropped in holder for dev guide docs

14 Diff Diff jlindborg picture jlindborg Fri 06 Sep, 2013 22:40:34 +0000

Most of the integration tests complete – more unit tests needed at some point.

13 Diff Diff jlindborg picture jlindborg Fri 06 Sep, 2013 02:57:55 +0000

More unit test work and related bug fixing.

12 Diff Diff jlindborg picture jlindborg Thu 05 Sep, 2013 01:56:48 +0000

more unit test work.

10 Diff Diff jlindborg picture jlindborg Mon 02 Sep, 2013 18:54:54 +0000

More unit and integration test work

8 Diff Diff jlindborg picture jlindborg Fri 30 Aug, 2013 00:27:58 +0000

adding some unit/integration tests into the project, doing a little cleanup.

7 jlindborg picture jlindborg Thu 29 Aug, 2013 00:02:27 +0000

working on cleaning up the ODBC sdk project