File: SqlDataSourceView.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (1522 lines) | stat: -rw-r--r-- 60,184 bytes parent folder | download | duplicates (7)
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
//------------------------------------------------------------------------------
// <copyright file="SqlDataSourceView.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI.WebControls {

    using System;
    using System.Collections;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Drawing.Design;
    using System.Globalization;
    using System.IO;
    using System.Text;
    using System.Web;
    using System.Web.Caching;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Util;

    using ConflictOptions = System.Web.UI.ConflictOptions;


    /// <devdoc>
    /// Represents a single view of a SqlDataSource.
    /// </devdoc>
    public class SqlDataSourceView : DataSourceView, IStateManager {

        private const int MustDeclareVariableSqlExceptionNumber = 137;
        private const int ProcedureExpectsParameterSqlExceptionNumber = 201;

        private static readonly object EventDeleted = new object();
        private static readonly object EventDeleting = new object();
        private static readonly object EventFiltering = new object();
        private static readonly object EventInserted = new object();
        private static readonly object EventInserting = new object();
        private static readonly object EventSelected = new object();
        private static readonly object EventSelecting = new object();
        private static readonly object EventUpdated = new object();
        private static readonly object EventUpdating = new object();

        private HttpContext _context;
        private SqlDataSource _owner;
        private bool _tracking;

        private bool _cancelSelectOnNullParameter = true;
        private ConflictOptions _conflictDetection = ConflictOptions.OverwriteChanges;
        private string _deleteCommand;
        private SqlDataSourceCommandType _deleteCommandType = SqlDataSourceCommandType.Text;
        private ParameterCollection _deleteParameters;
        private string _filterExpression;
        private ParameterCollection _filterParameters;
        private string _insertCommand;
        private SqlDataSourceCommandType _insertCommandType = SqlDataSourceCommandType.Text;
        private ParameterCollection _insertParameters;
        private string _oldValuesParameterFormatString;
        private string _selectCommand;
        private SqlDataSourceCommandType _selectCommandType = SqlDataSourceCommandType.Text;
        private ParameterCollection _selectParameters;
        private string _sortParameterName;
        private string _updateCommand;
        private SqlDataSourceCommandType _updateCommandType = SqlDataSourceCommandType.Text;
        private ParameterCollection _updateParameters;


        /// <devdoc>
        /// Creates a new instance of SqlDataSourceView.
        /// </devdoc>
        public SqlDataSourceView(SqlDataSource owner, string name, HttpContext context) : base(owner, name) {
            _owner = owner;
            _context = context;
        }


        public bool CancelSelectOnNullParameter {
            get {
                return _cancelSelectOnNullParameter;
            }
            set {
                if (CancelSelectOnNullParameter != value) {
                    _cancelSelectOnNullParameter = value;
                    OnDataSourceViewChanged(EventArgs.Empty);
                }
            }
        }

        /// <devdoc>
        /// Indicates that the view can delete rows.
        /// </devdoc>
        public override bool CanDelete {
            get {
                return (DeleteCommand.Length != 0);
            }
        }

        /// <devdoc>
        /// Indicates that the view can add new rows.
        /// </devdoc>
        public override bool CanInsert {
            get {
                return (InsertCommand.Length != 0);
            }
        }

        /// <devdoc>
        /// Indicates that the view can page the datasource on the server.
        /// </devdoc>
        public override bool CanPage {
            get {
                return false;
            }
        }

        /// <devdoc>
        /// Indicates that the view can return the total number of rows returned by the query.
        /// </devdoc>
        public override bool CanRetrieveTotalRowCount {
            get {
                return false;
            }
        }

        /// <devdoc>
        /// Indicates that the view can sort rows.
        /// </devdoc>
        public override bool CanSort {
            get {
                return (_owner.DataSourceMode == SqlDataSourceMode.DataSet) || (SortParameterName.Length > 0);
            }
        }

        /// <devdoc>
        /// Indicates that the view can update rows.
        /// </devdoc>
        public override bool CanUpdate {
            get {
                return (UpdateCommand.Length != 0);
            }
        }

        /// <devdoc>
        /// Whether commands pass old values in the parameter collection.
        /// </devdoc>
        public ConflictOptions ConflictDetection {
            get {
                return _conflictDetection;
            }
            set {
                if ((value < ConflictOptions.OverwriteChanges) || (value > ConflictOptions.CompareAllValues)) {
                    throw new ArgumentOutOfRangeException("value");
                }
                _conflictDetection = value;
                OnDataSourceViewChanged(EventArgs.Empty);
            }
        }

        /// <devdoc>
        /// The command to execute when Delete() is called on the SqlDataSourceView.
        /// </devdoc>
        public string DeleteCommand {
            get {
                if (_deleteCommand == null) {
                    return String.Empty;
                }
                return _deleteCommand;
            }
            set {
                _deleteCommand = value;
            }
        }

        public SqlDataSourceCommandType DeleteCommandType {
            get {
                return _deleteCommandType;
            }
            set {
                if ((value < SqlDataSourceCommandType.Text) || (value > SqlDataSourceCommandType.StoredProcedure)) {
                    throw new ArgumentOutOfRangeException("value");
                }
                _deleteCommandType = value;
            }
        }

        /// <devdoc>
        /// Collection of parameters used in Delete().
        /// </devdoc>
        [
        DefaultValue(null),
        Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.SqlDataSource_DeleteParameters),
        ]
        public ParameterCollection DeleteParameters {
            get {
                if (_deleteParameters == null) {
                    _deleteParameters = new ParameterCollection();
                }
                return _deleteParameters;
            }
        }

        /// <devdoc>
        /// The filter to apply when Select() is called on the SqlDataSourceView.
        /// </devdoc>
        public string FilterExpression {
            get {
                if (_filterExpression == null) {
                    return String.Empty;
                }
                return _filterExpression;
            }
            set {
                if (FilterExpression != value) {
                    _filterExpression = value;
                    OnDataSourceViewChanged(EventArgs.Empty);
                }
            }
        }

        /// <devdoc>
        /// Collection of parameters used in the FilterExpression property.
        /// </devdoc>
        [
        DefaultValue(null),
        Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.SqlDataSource_FilterParameters),
        ]
        public ParameterCollection FilterParameters {
            get {
                if (_filterParameters == null) {
                    _filterParameters = new ParameterCollection();

                    _filterParameters.ParametersChanged += new EventHandler(SelectParametersChangedEventHandler);

                    if (_tracking) {
                        ((IStateManager)_filterParameters).TrackViewState();
                    }
                }
                return _filterParameters;
            }
        }

        /// <devdoc>
        /// The command to execute when Insert() is called on the SqlDataSourceView.
        /// </devdoc>
        public string InsertCommand {
            get {
                if (_insertCommand == null) {
                    return String.Empty;
                }
                return _insertCommand;
            }
            set {
                _insertCommand = value;
            }
        }

        public SqlDataSourceCommandType InsertCommandType {
            get {
                return _insertCommandType;
            }
            set {
                if ((value < SqlDataSourceCommandType.Text) || (value > SqlDataSourceCommandType.StoredProcedure)) {
                    throw new ArgumentOutOfRangeException("value");
                }
                _insertCommandType = value;
            }
        }

        /// <devdoc>
        /// Collection of values used in Insert().
        /// </devdoc>
        [
        DefaultValue(null),
        Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.SqlDataSource_InsertParameters),
        ]
        public ParameterCollection InsertParameters {
            get {
                if (_insertParameters == null) {
                    _insertParameters = new ParameterCollection();
                }
                return _insertParameters;
            }
        }

        /// <devdoc>
        /// Returns whether this object is tracking view state.
        /// </devdoc>
        protected bool IsTrackingViewState {
            get {
                return _tracking;
            }
        }

        /// <devdoc>
        /// The format string applied to the names of the old values parameters
        /// </devdoc>
        [
        DefaultValue("{0}"),
        WebCategory("Data"),
        WebSysDescription(SR.DataSource_OldValuesParameterFormatString),
        ]
        public string OldValuesParameterFormatString {
            get {
                if (_oldValuesParameterFormatString == null) {
                    return "{0}";
                }
                return _oldValuesParameterFormatString;
            }
            set {
                _oldValuesParameterFormatString = value;
                OnDataSourceViewChanged(EventArgs.Empty);
            }
        }

        /// <devdoc>
        /// Indicates the prefix for parameters.
        /// </devdoc>
        protected virtual string ParameterPrefix {
            get {
                if (String.IsNullOrEmpty(_owner.ProviderName) ||
                    String.Equals(_owner.ProviderName, "System.Data.SqlClient", StringComparison.OrdinalIgnoreCase)) {
                    return "@";
                }
                else {
                    return String.Empty;
                }
            }
        }

        /// <devdoc>
        /// The command to execute when Select() is called on the SqlDataSourceView.
        /// </devdoc>
        public string SelectCommand {
            get {
                if (_selectCommand == null) {
                    return String.Empty;
                }
                return _selectCommand;
            }
            set {
                if (SelectCommand != value) {
                    _selectCommand = value;
                    OnDataSourceViewChanged(EventArgs.Empty);
                }
            }
        }

        public SqlDataSourceCommandType SelectCommandType {
            get {
                return _selectCommandType;
            }
            set {
                if ((value < SqlDataSourceCommandType.Text) || (value > SqlDataSourceCommandType.StoredProcedure)) {
                    throw new ArgumentOutOfRangeException("value");
                }
                _selectCommandType = value;
            }
        }


        /// <devdoc>
        /// The command to execute when Select is called on the SqlDataSourceView and the total rows is requested.
        /// </devdoc>
        /*public string SelectCountCommand {
            get {
                if (_selectCountCommand == null) {
                    return String.Empty;
                }
                return _selectCountCommand;
            }
            set {
                if (SelectCountCommand != value) {
                    _selectCountCommand = value;
                    OnDataSourceViewChanged(EventArgs.Empty);
                }
            }
        }*/


        /// <devdoc>
        /// Collection of parameters used in Select().
        /// </devdoc>
        public ParameterCollection SelectParameters {
            get {
                if (_selectParameters == null) {
                    _selectParameters = new ParameterCollection();

                    _selectParameters.ParametersChanged += new EventHandler(SelectParametersChangedEventHandler);

                    if (_tracking) {
                        ((IStateManager)_selectParameters).TrackViewState();
                    }
                }
                return _selectParameters;
            }
        }


        /// <devdoc>
        /// The name of the parameter in the SelectCommand that specifies the
        /// sort expression. This parameter's value will be automatically set
        /// at runtime with the appropriate sort expression. This is only
        /// supported for stored procedure commands.
        /// </devdoc>
        public string SortParameterName {
            get {
                if (_sortParameterName == null) {
                    return String.Empty;
                }
                return _sortParameterName;
            }
            set {
                if (SortParameterName != value) {
                    _sortParameterName = value;
                    OnDataSourceViewChanged(EventArgs.Empty);
                }
            }
        }


        /// <devdoc>
        /// The command to execute when Update() is called on the SqlDataSourceView.
        /// </devdoc>
        public string UpdateCommand {
            get {
                if (_updateCommand == null) {
                    return String.Empty;
                }
                return _updateCommand;
            }
            set {
                _updateCommand = value;
            }
        }

        public SqlDataSourceCommandType UpdateCommandType {
            get {
                return _updateCommandType;
            }
            set {
                if ((value < SqlDataSourceCommandType.Text) || (value > SqlDataSourceCommandType.StoredProcedure)) {
                    throw new ArgumentOutOfRangeException("value");
                }
                _updateCommandType = value;
            }
        }

        /// <devdoc>
        /// Collection of parameters used in Update().
        /// </devdoc>
        [
        DefaultValue(null),
        Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)),
        PersistenceMode(PersistenceMode.InnerProperty),
        WebSysDescription(SR.SqlDataSource_UpdateParameters),
        ]
        public ParameterCollection UpdateParameters {
            get {
                if (_updateParameters == null) {
                    _updateParameters = new ParameterCollection();
                }
                return _updateParameters;
            }
        }


        /// <devdoc>
        /// This event is raised after the Delete operation has completed.
        /// Handle this event if you need to examine the values of output parameters.
        /// </devdoc>
        public event SqlDataSourceStatusEventHandler Deleted {
            add {
                Events.AddHandler(EventDeleted, value);
            }
            remove {
                Events.RemoveHandler(EventDeleted, value);
            }
        }

        /// <devdoc>
        /// This event is raised before the Delete operation has been executed.
        /// Handle this event if you want to perform additional initialization operations
        /// that are specific to your application. You can also handle this event if you
        /// need to validate the values of parameters or change their values.
        /// When this event is raised, the database connection is not open yet, and you
        /// can cancel the event by setting the Cancel property of the DataCommandEventArgs
        /// to true.
        /// </devdoc>
        public event SqlDataSourceCommandEventHandler Deleting {
            add {
                Events.AddHandler(EventDeleting, value);
            }
            remove {
                Events.RemoveHandler(EventDeleting, value);
            }
        }

        public event SqlDataSourceFilteringEventHandler Filtering {
            add {
                Events.AddHandler(EventFiltering, value);
            }
            remove {
                Events.RemoveHandler(EventFiltering, value);
            }
        }

        /// <devdoc>
        /// This event is raised after the Insert operation has completed.
        /// Handle this event if you need to examine the values of output parameters.
        /// </devdoc>
        public event SqlDataSourceStatusEventHandler Inserted {
            add {
                Events.AddHandler(EventInserted, value);
            }
            remove {
                Events.RemoveHandler(EventInserted, value);
            }
        }

        /// <devdoc>
        /// This event is raised before the Insert operation has been executed.
        /// Handle this event if you want to perform additional initialization operations
        /// that are specific to your application. You can also handle this event if you
        /// need to validate the values of parameters or change their values.
        /// When this event is raised, the database connection is not open yet, and you
        /// can cancel the event by setting the Cancel property of the DataCommandEventArgs
        /// to true.
        /// </devdoc>
        public event SqlDataSourceCommandEventHandler Inserting {
            add {
                Events.AddHandler(EventInserting, value);
            }
            remove {
                Events.RemoveHandler(EventInserting, value);
            }
        }

        /// <devdoc>
        /// This event is raised after the Select operation has completed.
        /// Handle this event if you need to examine the values of output parameters.
        /// </devdoc>
        public event SqlDataSourceStatusEventHandler Selected {
            add {
                Events.AddHandler(EventSelected, value);
            }
            remove {
                Events.RemoveHandler(EventSelected, value);
            }
        }

        /// <devdoc>
        /// This event is raised before the Select operation has been executed.
        /// Handle this event if you want to perform additional initialization operations
        /// that are specific to your application. You can also handle this event if you
        /// need to validate the values of parameters or change their values.
        /// When this event is raised, the database connection is not open yet, and you
        /// can cancel the event by setting the Cancel property of the DataCommandEventArgs
        /// to true.
        /// </devdoc>
        public event SqlDataSourceSelectingEventHandler Selecting {
            add {
                Events.AddHandler(EventSelecting, value);
            }
            remove {
                Events.RemoveHandler(EventSelecting, value);
            }
        }

        /// <devdoc>
        /// This event is raised after the Update operation has completed.
        /// Handle this event if you need to examine the values of output parameters.
        /// </devdoc>
        public event SqlDataSourceStatusEventHandler Updated {
            add {
                Events.AddHandler(EventUpdated, value);
            }
            remove {
                Events.RemoveHandler(EventUpdated, value);
            }
        }

        /// <devdoc>
        /// This event is raised before the Update operation has been executed.
        /// Handle this event if you want to perform additional initialization operations
        /// that are specific to your application. You can also handle this event if you
        /// need to validate the values of parameters or change their values.
        /// When this event is raised, the database connection is not open yet, and you
        /// can cancel the event by setting the Cancel property of the DataCommandEventArgs
        /// to true.
        /// </devdoc>
        public event SqlDataSourceCommandEventHandler Updating {
            add {
                Events.AddHandler(EventUpdating, value);
            }
            remove {
                Events.RemoveHandler(EventUpdating, value);
            }
        }


        /// <devdoc>
        /// Adds parameters to an DbCommand from an IOrderedDictionary.
        /// The exclusion list contains parameter names that should not be added
        /// to the command's parameter collection.
        /// </devdoc>
        private void AddParameters(DbCommand command, ParameterCollection reference, IDictionary parameters, IDictionary exclusionList, string oldValuesParameterFormatString) {
            Debug.Assert(command != null);

            IDictionary caseInsensitiveExclusionList = null;
            if (exclusionList != null) {
                caseInsensitiveExclusionList = new ListDictionary(StringComparer.OrdinalIgnoreCase);
                foreach (DictionaryEntry de in exclusionList) {
                    caseInsensitiveExclusionList.Add(de.Key, de.Value);
                }
            }

            if (parameters != null) {
                string parameterPrefix = ParameterPrefix;
                foreach (DictionaryEntry de in parameters) {
                    string rawParamName = (string)de.Key;

                    if ((caseInsensitiveExclusionList != null) && (caseInsensitiveExclusionList.Contains(rawParamName))) {
                        // If we have an exclusion list and it contains this parameter, skip it
                        continue;
                    }

                    string formattedParamName;
                    if (oldValuesParameterFormatString == null) {
                        formattedParamName = rawParamName;
                    }
                    else {
                        formattedParamName = String.Format(CultureInfo.InvariantCulture, oldValuesParameterFormatString, rawParamName);
                    }
                    object value = de.Value;

                    // If the reference collection contains this parameter, we will use
                    // the Parameter's settings to format the value
                    Parameter parameter = reference[formattedParamName];
                    if (parameter != null) {
                        value = parameter.GetValue(de.Value, false);
                    }

                    formattedParamName = parameterPrefix + formattedParamName;

                    if (command.Parameters.Contains(formattedParamName)) {
                        // We never overwrite an existing value with a null value
                        if (value != null) {
                            command.Parameters[formattedParamName].Value = value;
                        }
                    }
                    else {
                        // Parameter does not exist, add a new one
                        DbParameter dbParameter = _owner.CreateParameter(formattedParamName, value);
                        command.Parameters.Add(dbParameter);
                    }
                }
            }
        }

        /// <devdoc>
        /// Builds a custom exception for specific database errors.
        /// Currently the only custom exception text supported is for SQL Server
        /// when a parameter is present in the command but not in the parameters
        /// collection.
        /// The isCustomException parameter indicates whether a custom exception
        /// was created or not. This way the caller can determine whether it wants
        /// to rethrow the original exception or throw the new custom exception.
        /// </devdoc>
        private Exception BuildCustomException(Exception ex, DataSourceOperation operation, DbCommand command, out bool isCustomException) {
            System.Data.SqlClient.SqlException sqlException = ex as System.Data.SqlClient.SqlException;
            if (sqlException != null) {
                if ((sqlException.Number == MustDeclareVariableSqlExceptionNumber) ||
                    (sqlException.Number == ProcedureExpectsParameterSqlExceptionNumber)) {
                    string parameterNames;
                    if (command.Parameters.Count > 0) {
                        StringBuilder sb = new StringBuilder();
                        bool firstParameter = true;
                        foreach (DbParameter p in command.Parameters) {
                            if (!firstParameter) {
                                sb.Append(", ");
                            }
                            sb.Append(p.ParameterName);
                            firstParameter = false;
                        }
                        parameterNames = sb.ToString();
                    }
                    else {
                        parameterNames = SR.GetString(SR.SqlDataSourceView_NoParameters);
                    }
                    isCustomException = true;
                    return new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_MissingParameters, operation, _owner.ID, parameterNames));
                }
            }
            isCustomException = false;
            return ex;
        }

        public int Delete(IDictionary keys, IDictionary oldValues) {
            return ExecuteDelete(keys, oldValues);
        }

        /// <devdoc>
        /// Executes a DbCommand and returns the number of rows affected.
        /// </devdoc>
        private int ExecuteDbCommand(DbCommand command, DataSourceOperation operation) {
            int rowsAffected = 0;

            bool eventRaised = false;
            try {
                if (command.Connection.State != ConnectionState.Open) {
                    command.Connection.Open();
                }

                rowsAffected = command.ExecuteNonQuery();

                if (rowsAffected > 0) {
                    OnDataSourceViewChanged(EventArgs.Empty);

                    DataSourceCache cache = _owner.Cache;
                    if ((cache != null) && (cache.Enabled)) {
                        _owner.InvalidateCacheEntry();
                    }
                }

                // Raise appropriate event
                eventRaised = true;
                SqlDataSourceStatusEventArgs eventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, null);
                switch (operation) {
                    case DataSourceOperation.Delete:
                        OnDeleted(eventArgs);
                        break;
                    case DataSourceOperation.Insert:
                        OnInserted(eventArgs);
                        break;
                    case DataSourceOperation.Update:
                        OnUpdated(eventArgs);
                        break;
                }
            }
            catch (Exception ex) {
                if (!eventRaised) {
                    // Raise appropriate event
                    SqlDataSourceStatusEventArgs eventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, ex);
                    switch (operation) {
                        case DataSourceOperation.Delete:
                            OnDeleted(eventArgs);
                            break;
                        case DataSourceOperation.Insert:
                            OnInserted(eventArgs);
                            break;
                        case DataSourceOperation.Update:
                            OnUpdated(eventArgs);
                            break;
                    }
                    if (!eventArgs.ExceptionHandled) {
                        throw;
                    }
                }
                else {
                    bool isCustomException;
                    ex = BuildCustomException(ex, operation, command, out isCustomException);
                    if (isCustomException) {
                        throw ex;
                    }
                    else {
                        throw;
                    }
                }
            }
            finally {
                if (command.Connection.State == ConnectionState.Open) {
                    command.Connection.Close();
                }
            }

            return rowsAffected;
        }


        /// <devdoc>
        /// Deletes rows from the data source with given parameters.
        /// </devdoc>
        protected override int ExecuteDelete(IDictionary keys, IDictionary oldValues) {
            if (!CanDelete) {
                throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_DeleteNotSupported, _owner.ID));
            }

            DbConnection connection = _owner.CreateConnection(_owner.ConnectionString);

            if (connection == null) {
                throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CouldNotCreateConnection, _owner.ID));
            }

            // Create command and add parameters
            string oldValuesParameterFormatString = OldValuesParameterFormatString;
            DbCommand command = _owner.CreateCommand(DeleteCommand, connection);
            InitializeParameters(command, DeleteParameters, oldValues);
            AddParameters(command, DeleteParameters, keys, null, oldValuesParameterFormatString);
            if (ConflictDetection == ConflictOptions.CompareAllValues) {
                if (oldValues == null || oldValues.Count == 0) {
                    throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_Pessimistic, SR.GetString(SR.DataSourceView_delete), _owner.ID, "values"));
                }
                AddParameters(command, DeleteParameters, oldValues, null, oldValuesParameterFormatString);
            }
            command.CommandType = GetCommandType(DeleteCommandType);

            // Raise event to allow customization and cancellation
            SqlDataSourceCommandEventArgs eventArgs = new SqlDataSourceCommandEventArgs(command);
            OnDeleting(eventArgs);

            // If the operation was cancelled, exit immediately
            if (eventArgs.Cancel) {
                return 0;
            }

            // Replace null values in parameters with DBNull.Value
            ReplaceNullValues(command);

            return ExecuteDbCommand(command, DataSourceOperation.Delete);
        }


        /// <devdoc>
        /// Inserts a new row with data from a name/value collection.
        /// </devdoc>
        protected override int ExecuteInsert(IDictionary values) {
            if (!CanInsert) {
                throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_InsertNotSupported, _owner.ID));
            }

            DbConnection connection = _owner.CreateConnection(_owner.ConnectionString);

            if (connection == null) {
                throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CouldNotCreateConnection, _owner.ID));
            }

            // Create command and add parameters
            DbCommand command = _owner.CreateCommand(InsertCommand, connection);
            InitializeParameters(command, InsertParameters, null);
            AddParameters(command, InsertParameters, values, null, null);
            command.CommandType = GetCommandType(InsertCommandType);

            // Raise event to allow customization and cancellation
            SqlDataSourceCommandEventArgs eventArgs = new SqlDataSourceCommandEventArgs(command);
            OnInserting(eventArgs);

            // If the operation was cancelled, exit immediately
            if (eventArgs.Cancel) {
                return 0;
            }

            // Replace null values in parameters with DBNull.Value
            ReplaceNullValues(command);

            return ExecuteDbCommand(command, DataSourceOperation.Insert);
        }


        /// <devdoc>
        /// Returns all the rows of the datasource.
        /// Parameters are taken from the SqlDataSource.Parameters property collection.
        /// If DataSourceMode is set to DataSet then a DataView is returned.
        /// If DataSourceMode is set to DataReader then a DataReader is returned, and it must be closed when done.
        /// </devdoc>
        protected internal override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments) {
            if (SelectCommand.Length == 0) {
                return null;
            }

            DbConnection connection = _owner.CreateConnection(_owner.ConnectionString);

            if (connection == null) {
                throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CouldNotCreateConnection, _owner.ID));
            }

            DataSourceCache cache = _owner.Cache;
            bool cacheEnabled = (cache != null) && (cache.Enabled);
            //int startRowIndex = arguments.StartRowIndex;
            //int maximumRows = arguments.MaximumRows;
            string sortExpression = arguments.SortExpression;

            if (CanPage) {
                arguments.AddSupportedCapabilities(DataSourceCapabilities.Page);
            }

            if (CanSort) {
                arguments.AddSupportedCapabilities(DataSourceCapabilities.Sort);
            }

            if (CanRetrieveTotalRowCount) {
                arguments.AddSupportedCapabilities(DataSourceCapabilities.RetrieveTotalRowCount);
            }


            // If caching is enabled, load DataSet from cache
            if (cacheEnabled) {
                if (_owner.DataSourceMode != SqlDataSourceMode.DataSet) {
                    throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_CacheNotSupported, _owner.ID));
                }

                arguments.RaiseUnsupportedCapabilitiesError(this);

                DataSet dataSet = _owner.LoadDataFromCache(0, -1) as DataSet;

                if (dataSet != null) {
                    /*if (arguments.RetrieveTotalRowCount) {
                        int cachedTotalRowCount = _owner.LoadTotalRowCountFromCache();
                        if (cachedTotalRowCount >= 0) {
                            arguments.TotalRowCount = cachedTotalRowCount;
                        }
                        else {
                            // query for row count and then save it in cache
                            cachedTotalRowCount = QueryTotalRowCount(connection, arguments);
                            arguments.TotalRowCount = cachedTotalRowCount;
                            _owner.SaveTotalRowCountToCache(cachedTotalRowCount);
                        }
                    }*/
                    IOrderedDictionary parameterValues = FilterParameters.GetValues(_context, _owner);
                    if (FilterExpression.Length > 0) {
                        SqlDataSourceFilteringEventArgs filterArgs = new SqlDataSourceFilteringEventArgs(parameterValues);
                        OnFiltering(filterArgs);
                        if (filterArgs.Cancel) {
                            return null;
                        }
                    }
                    return FilteredDataSetHelper.CreateFilteredDataView(dataSet.Tables[0], sortExpression, FilterExpression, parameterValues);
                }
            }

            // Create command and add parameters
            DbCommand command = _owner.CreateCommand(SelectCommand, connection);
            InitializeParameters(command, SelectParameters, null);
            command.CommandType = GetCommandType(SelectCommandType);

            // Raise event to allow customization and cancellation
            SqlDataSourceSelectingEventArgs selectingEventArgs = new SqlDataSourceSelectingEventArgs(command, arguments);
            OnSelecting(selectingEventArgs);

            // If the operation was cancelled, exit immediately
            if (selectingEventArgs.Cancel) {
                return null;
            }

            // Add the sort parameter to allow for custom stored procedure sorting, if necessary
            string sortParameterName = SortParameterName;
            if (sortParameterName.Length > 0) {
                if (command.CommandType != CommandType.StoredProcedure) {
                    throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_SortParameterRequiresStoredProcedure, _owner.ID));
                }
                command.Parameters.Add(_owner.CreateParameter(ParameterPrefix + sortParameterName, sortExpression));

                // We reset the sort expression here so that we pretend as
                // though we're not really sorting (since the developer is
                // worrying about it instead of us).
                arguments.SortExpression = String.Empty;
            }

            arguments.RaiseUnsupportedCapabilitiesError(this);

            // reset these values, since they might have changed in the OnSelecting event
            sortExpression = arguments.SortExpression;
            //startRowIndex = arguments.StartRowIndex;
            //maximumRows = arguments.MaximumRows;

            // Perform null check if user wants to cancel on any null parameter value
            if (CancelSelectOnNullParameter) {
                int paramCount = command.Parameters.Count;
                for (int i = 0; i < paramCount; i++) {
                    DbParameter parameter = command.Parameters[i];
                    if ((parameter != null) &&
                        (parameter.Value == null) &&
                        ((parameter.Direction == ParameterDirection.Input) || (parameter.Direction == ParameterDirection.InputOutput))) {
                        return null;
                    }
                }
            }

            // Replace null values in parameters with DBNull.Value
            ReplaceNullValues(command);

            /*if (arguments.RetrieveTotalRowCount && SelectCountCommand.Length > 0) {
                int cachedTotalRowCount = -1;
                if (cacheEnabled) {
                    cachedTotalRowCount = _owner.LoadTotalRowCountFromCache();
                    if (cachedTotalRowCount >= 0) {
                        arguments.TotalRowCount = cachedTotalRowCount;
                    }
                }
                if (cachedTotalRowCount < 0) {
                    cachedTotalRowCount = QueryTotalRowCount(connection, arguments);
                    arguments.TotalRowCount = cachedTotalRowCount;
                    if (cacheEnabled) {
                        _owner.SaveTotalRowCountToCache(cachedTotalRowCount);
                    }
                }
            }*/

            IEnumerable selectResult = null;

            switch (_owner.DataSourceMode) {
                case SqlDataSourceMode.DataSet:
                {
                    SqlCacheDependency cacheDependency = null;
                    if (cacheEnabled && cache is SqlDataSourceCache) {
                        SqlDataSourceCache sqlCache = (SqlDataSourceCache)cache;
                        if (String.Equals(sqlCache.SqlCacheDependency, SqlDataSourceCache.Sql9CacheDependencyDirective, StringComparison.OrdinalIgnoreCase)) {
                            if (!(command is System.Data.SqlClient.SqlCommand)) {
                                throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CommandNotificationNotSupported, _owner.ID));
                            }
                            cacheDependency = new SqlCacheDependency((System.Data.SqlClient.SqlCommand)command);
                        }
                    }

                    DbDataAdapter adapter = _owner.CreateDataAdapter(command);

                    DataSet dataSet = new DataSet();
                    int rowsAffected = 0;

                    bool eventRaised = false;
                    try {
                        rowsAffected = adapter.Fill(dataSet, Name);

                        // Raise the Selected event
                        eventRaised = true;
                        SqlDataSourceStatusEventArgs selectedEventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, null);
                        OnSelected(selectedEventArgs);
                    }
                    catch (Exception ex) {
                        if (!eventRaised) {
                            // Raise the Selected event
                            SqlDataSourceStatusEventArgs selectedEventArgs = new SqlDataSourceStatusEventArgs(command, rowsAffected, ex);
                            OnSelected(selectedEventArgs);
                            if (!selectedEventArgs.ExceptionHandled) {
                                throw;
                            }
                        }
                        else {
                            bool isCustomException;
                            ex = BuildCustomException(ex, DataSourceOperation.Select, command, out isCustomException);
                            if (isCustomException) {
                                throw ex;
                            }
                            else {
                                throw;
                            }
                        }
                    }
                    finally {
                        if (connection.State == ConnectionState.Open) {
                            connection.Close();
                        }
                    }

                    // If caching is enabled, save DataSet to cache
                    DataTable dataTable = (dataSet.Tables.Count > 0 ? dataSet.Tables[0] : null);
                    if (cacheEnabled && dataTable != null) {
                        _owner.SaveDataToCache(0, -1, dataSet, cacheDependency);
                    }

                    if (dataTable != null) {
                        IOrderedDictionary parameterValues = FilterParameters.GetValues(_context, _owner);
                        if (FilterExpression.Length > 0) {
                            SqlDataSourceFilteringEventArgs filterArgs = new SqlDataSourceFilteringEventArgs(parameterValues);
                            OnFiltering(filterArgs);
                            if (filterArgs.Cancel) {
                                return null;
                            }
                        }
                        selectResult = FilteredDataSetHelper.CreateFilteredDataView(dataTable, sortExpression, FilterExpression, parameterValues);
                    }
                    break;
                }

                case SqlDataSourceMode.DataReader:
                {
                    if (FilterExpression.Length > 0) {
                        throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_FilterNotSupported, _owner.ID));
                    }

                    if (sortExpression.Length > 0) {
                        throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_SortNotSupported, _owner.ID));
                    }

                    bool eventRaised = false;
                    try {
                        if (connection.State != ConnectionState.Open) {
                            connection.Open();
                        }

                        selectResult = command.ExecuteReader(CommandBehavior.CloseConnection);

                        // Raise the Selected event
                        eventRaised = true;
                        SqlDataSourceStatusEventArgs selectedEventArgs = new SqlDataSourceStatusEventArgs(command, 0, null);
                        OnSelected(selectedEventArgs);
                    }
                    catch (Exception ex) {
                        if (!eventRaised) {
                            // Raise the Selected event
                            SqlDataSourceStatusEventArgs selectedEventArgs = new SqlDataSourceStatusEventArgs(command, 0, ex);
                            OnSelected(selectedEventArgs);
                            if (!selectedEventArgs.ExceptionHandled) {
                                throw;
                            }
                        }
                        else {
                            bool isCustomException;
                            ex = BuildCustomException(ex, DataSourceOperation.Select, command, out isCustomException);
                            if (isCustomException) {
                                throw ex;
                            }
                            else {
                                throw;
                            }
                        }
                    }
                    break;
                }
            }
            return selectResult;
        }


        /// <devdoc>
        /// Updates rows matching the parameter collection and setting new values from the name/value values collection.
        /// </devdoc>
        protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) {
            if (!CanUpdate) {
                throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_UpdateNotSupported, _owner.ID));
            }

            DbConnection connection = _owner.CreateConnection(_owner.ConnectionString);

            if (connection == null) {
                throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_CouldNotCreateConnection, _owner.ID));
            }

            // Create command and add parameters
            string oldValuesParameterFormatString = OldValuesParameterFormatString;
            DbCommand command = _owner.CreateCommand(UpdateCommand, connection);
            InitializeParameters(command, UpdateParameters, keys);
            AddParameters(command, UpdateParameters, values, null, null);
            AddParameters(command, UpdateParameters, keys, null, oldValuesParameterFormatString);
            if (ConflictDetection == ConflictOptions.CompareAllValues) {
                if (oldValues == null || oldValues.Count == 0) {
                    throw new InvalidOperationException(SR.GetString(SR.SqlDataSourceView_Pessimistic, SR.GetString(SR.DataSourceView_update), _owner.ID, "oldValues"));
                }
                AddParameters(command, UpdateParameters, oldValues, null, oldValuesParameterFormatString);
            }
            command.CommandType = GetCommandType(UpdateCommandType);

            // Raise event to allow customization and cancellation
            SqlDataSourceCommandEventArgs eventArgs = new SqlDataSourceCommandEventArgs(command);
            OnUpdating(eventArgs);

            // If the operation was cancelled, exit immediately
            if (eventArgs.Cancel) {
                return 0;
            }

            // Replace null values in parameters with DBNull.Value
            ReplaceNullValues(command);

            return ExecuteDbCommand(command, DataSourceOperation.Update);
        }

        /// <devdoc>
        /// Converts a SqlDataSourceCommandType to a System.Data.CommandType.
        /// </devdoc>
        private static CommandType GetCommandType(SqlDataSourceCommandType commandType) {
            if (commandType == SqlDataSourceCommandType.Text) {
                return CommandType.Text;
            }
            return CommandType.StoredProcedure;
        }

        /// <devdoc>
        /// Initializes a DbCommand with parameters from a ParameterCollection.
        /// The exclusion list contains parameter names that should not be added
        /// to the command's parameter collection.
        /// </devdoc>
        private void InitializeParameters(DbCommand command, ParameterCollection parameters, IDictionary exclusionList) {
            Debug.Assert(command != null);
            Debug.Assert(parameters != null);

            string parameterPrefix = ParameterPrefix;

            IDictionary caseInsensitiveExclusionList = null;
            if (exclusionList != null) {
                caseInsensitiveExclusionList = new ListDictionary(StringComparer.OrdinalIgnoreCase);
                foreach (DictionaryEntry de in exclusionList) {
                    caseInsensitiveExclusionList.Add(de.Key, de.Value);
                }
            }

            IOrderedDictionary values = parameters.GetValues(_context, _owner);
            for (int i = 0; i < parameters.Count; i++) {
                Parameter parameter = parameters[i];
                if ((caseInsensitiveExclusionList == null) || (!caseInsensitiveExclusionList.Contains(parameter.Name))) {
                    DbParameter dbParameter = _owner.CreateParameter(parameterPrefix + parameter.Name, values[i]);
                    dbParameter.Direction = parameter.Direction;
                    dbParameter.Size = parameter.Size;
                    if (parameter.DbType != DbType.Object || (parameter.Type != TypeCode.Empty && parameter.Type != TypeCode.DBNull)) {
                        SqlParameter sqlParameter = dbParameter as SqlParameter;
                        if (sqlParameter == null) {
                            dbParameter.DbType = parameter.GetDatabaseType();
                        }
                        else {
                            // In Whidbey, the DbType Date and Time members mapped to SqlDbType.DateTime since there
                            // were no SqlDbType equivalents. SqlDbType has since been modified to include the new
                            // Katmai types, including Date and Time. For backwards compatability SqlParameter's DbType
                            // setter doesn't support Date and Time, so the SqlDbType property should be used instead.
                            // Other new SqlServer 2008 types (DateTime2, DateTimeOffset) can be set using DbType.
                            DbType dbType = parameter.GetDatabaseType();
                            switch (dbType) {
                                case DbType.Time:
                                    sqlParameter.SqlDbType = SqlDbType.Time;
                                    break;
                                case DbType.Date:
                                    sqlParameter.SqlDbType = SqlDbType.Date;
                                    break;
                                default:
                                    dbParameter.DbType = parameter.GetDatabaseType();
                                    break;
                            }
                        }
                    }
                    command.Parameters.Add(dbParameter);
                }
            }
        }

        public int Insert(IDictionary values) {
            return ExecuteInsert(values);
        }


        /// <devdoc>
        /// Loads view state.
        /// </devdoc>
        protected virtual void LoadViewState(object savedState) {
            if (savedState == null)
                return;

            Pair myState = (Pair)savedState;

            if (myState.First != null)
                ((IStateManager)SelectParameters).LoadViewState(myState.First);

            if (myState.Second != null)
                ((IStateManager)FilterParameters).LoadViewState(myState.Second);
        }


        /// <devdoc>
        /// Raises the Deleted event.
        /// </devdoc>
        protected virtual void OnDeleted(SqlDataSourceStatusEventArgs e) {
            SqlDataSourceStatusEventHandler handler = Events[EventDeleted] as SqlDataSourceStatusEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        /// Raises the Deleting event.
        /// </devdoc>
        protected virtual void OnDeleting(SqlDataSourceCommandEventArgs e) {
            SqlDataSourceCommandEventHandler handler = Events[EventDeleting] as SqlDataSourceCommandEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }

        protected virtual void OnFiltering(SqlDataSourceFilteringEventArgs e) {
            SqlDataSourceFilteringEventHandler handler = Events[EventFiltering] as SqlDataSourceFilteringEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        /// Raises the Inserted event.
        /// </devdoc>
        protected virtual void OnInserted(SqlDataSourceStatusEventArgs e) {
            SqlDataSourceStatusEventHandler handler = Events[EventInserted] as SqlDataSourceStatusEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        /// Raises the Inserting event.
        /// </devdoc>
        protected virtual void OnInserting(SqlDataSourceCommandEventArgs e) {
            SqlDataSourceCommandEventHandler handler = Events[EventInserting] as SqlDataSourceCommandEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        /// Raises the Selected event.
        /// </devdoc>
        protected virtual void OnSelected(SqlDataSourceStatusEventArgs e) {
            SqlDataSourceStatusEventHandler handler = Events[EventSelected] as SqlDataSourceStatusEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        /// Raises the Selecting event.
        /// </devdoc>
        protected virtual void OnSelecting(SqlDataSourceSelectingEventArgs e) {
            SqlDataSourceSelectingEventHandler handler = Events[EventSelecting] as SqlDataSourceSelectingEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }
        

        /// <devdoc>
        /// Raises the Updated event.
        /// </devdoc>
        protected virtual void OnUpdated(SqlDataSourceStatusEventArgs e) {
            SqlDataSourceStatusEventHandler handler = Events[EventUpdated] as SqlDataSourceStatusEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        /// Raises the Updating event.
        /// </devdoc>
        protected virtual void OnUpdating(SqlDataSourceCommandEventArgs e) {
            SqlDataSourceCommandEventHandler handler = Events[EventUpdating] as SqlDataSourceCommandEventHandler;
            if (handler != null) {
                handler(this, e);
            }
        }


        /// <devdoc>
        /// Executes the SelectCountCommand to retrieve the total row count.
        /// </devdoc>
        /*protected virtual int QueryTotalRowCount(DbConnection connection, DataSourceSelectArguments arguments) {
            int totalRowCount = 0;
            bool eventRaised = false;

            if (SelectCountCommand.Length > 0) {
                // Create command and add parameters
                DbCommand command = _owner.CreateCommand(SelectCountCommand, connection);
                InitializeParameters(command, SelectParameters);
                command.CommandType = GetCommandType(SelectCountCommand, SelectCompareString);

                // Raise event to allow customization and cancellation
                SqlDataSourceSelectingEventArgs selectCountingEventArgs = new SqlDataSourceSelectingEventArgs(command, arguments, true);
                OnSelecting(selectCountingEventArgs);

                // If the operation was cancelled, exit immediately
                if (selectCountingEventArgs.Cancel) {
                    return totalRowCount;
                }

                // the arguments may have been changed
                arguments.RaiseUnsupportedCapabilitiesError(this);

                // 






































*/


        protected internal override void RaiseUnsupportedCapabilityError(DataSourceCapabilities capability) {
            if (!CanPage && ((capability & DataSourceCapabilities.Page) != 0)) {
                throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_NoPaging, _owner.ID));
            }

            if (!CanSort && ((capability & DataSourceCapabilities.Sort) != 0)) {
                throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_NoSorting, _owner.ID));
            }

            if (!CanRetrieveTotalRowCount && ((capability & DataSourceCapabilities.RetrieveTotalRowCount) != 0)) {
                throw new NotSupportedException(SR.GetString(SR.SqlDataSourceView_NoRowCount, _owner.ID));
            }
            base.RaiseUnsupportedCapabilityError(capability);
        }

        /// <devdoc>
        /// Replace null values in parameters with DBNull.Value.
        /// </devdoc>
        private void ReplaceNullValues(DbCommand command) {
            int paramCount = command.Parameters.Count;
            foreach (DbParameter parameter in command.Parameters) {
                if (parameter.Value == null) {
                    parameter.Value = DBNull.Value;
                }
            }
        }

        /// <devdoc>
        /// Saves view state.
        /// </devdoc>
        protected virtual object SaveViewState() {
            Pair myState = new Pair();

            myState.First = (_selectParameters != null) ? ((IStateManager)_selectParameters).SaveViewState() : null;
            myState.Second = (_filterParameters != null) ? ((IStateManager)_filterParameters).SaveViewState() : null;

            if ((myState.First == null) &&
                (myState.Second == null)) {
                return null;
            }

            return myState;
        }

        public IEnumerable Select(DataSourceSelectArguments arguments) {
            return ExecuteSelect(arguments);
        }

        /// <devdoc>
        /// Event handler for SelectParametersChanged event.
        /// </devdoc>
        private void SelectParametersChangedEventHandler(object o, EventArgs e) {
            OnDataSourceViewChanged(EventArgs.Empty);
        }


        /// <devdoc>
        /// Starts tracking view state.
        /// </devdoc>
        protected virtual void TrackViewState() {
            _tracking = true;

            if (_selectParameters != null) {
                ((IStateManager)_selectParameters).TrackViewState();
            }
            if (_filterParameters != null) {
                ((IStateManager)_filterParameters).TrackViewState();
            }
        }

        public int Update(IDictionary keys, IDictionary values, IDictionary oldValues) {
            return ExecuteUpdate(keys, values, oldValues);
        }


        #region IStateManager implementation
        bool IStateManager.IsTrackingViewState {
            get {
                return IsTrackingViewState;
            }
        }

        void IStateManager.LoadViewState(object savedState) {
            LoadViewState(savedState);
        }

        object IStateManager.SaveViewState() {
            return SaveViewState();
        }

        void IStateManager.TrackViewState() {
            TrackViewState();
        }
        #endregion
    }
}