File: LinqDataSourceView.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 (977 lines) | stat: -rw-r--r-- 42,770 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
//------------------------------------------------------------------------------
// <copyright file="LinqDataSourceView.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

namespace System.Web.UI.WebControls {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web.Compilation;
    using System.Web.Query.Dynamic;
    using System.Web.Resources;
    using System.Security;
    using System.Security.Permissions;
    using DynamicValidatorEventArgs = System.Web.DynamicData.DynamicValidatorEventArgs;
    using DynamicDataSourceOperation = System.Web.DynamicData.DynamicDataSourceOperation;

    public partial class LinqDataSourceView : ContextDataSourceView {                
        private static readonly object EventDeleted = new object();
        private static readonly object EventDeleting = new object();
        private static readonly object EventException = new object();
        private static readonly object EventInserted = new object();
        private static readonly object EventInserting = new object();
        private static readonly object EventUpdated = new object();
        private static readonly object EventUpdating = new object();

        private HttpContext _context;
        private Type _contextType;
        private string _contextTypeName;
        private LinqDataSource _owner;
        private List<ContextDataSourceContextData> _selectContexts;
        private bool _enableDelete;
        private bool _enableInsert;
        private bool _enableObjectTracking = true;
        private bool _enableUpdate;
        private bool _isNewContext;
        private ILinqToSql _linqToSql;
        private bool _reuseSelectContext;
        private bool _storeOriginalValuesInViewState = true;
        private bool _storeOriginalValues;
        private object _selectResult;

        public LinqDataSourceView(LinqDataSource owner, string name, HttpContext context)
            : this(owner, name, context, new DynamicQueryableWrapper(), new LinqToSqlWrapper()) {
        }

        // internal constructor that takes mocks for unit tests.
        internal LinqDataSourceView(LinqDataSource owner, string name, HttpContext context,
                                    IDynamicQueryable dynamicQueryable, ILinqToSql linqToSql)
            : base(owner, name, context, dynamicQueryable) {
            _context = context;
            _owner = owner;
            _linqToSql = linqToSql;
        }

        public override bool CanDelete {
            get {
                return EnableDelete;
            }
        }

        public override bool CanInsert {
            get {
                return EnableInsert;
            }
        }

        // When AutoPage is false the user should manually page in the Selecting event.
        public override bool CanPage {
            get {
                return true;
            }
        }

        // When AutoPage is false the user must set the total row count in the Selecting event.
        public override bool CanRetrieveTotalRowCount {
            get {
                return true;
            }
        }

        // When AutoSort is false the user should manually sort in the Selecting event.
        public override bool CanSort {
            get {
                return true;
            }
        }

        public override bool CanUpdate {
            get {
                return EnableUpdate;
            }
        }

        public override Type ContextType {
            [SecuritySafeCritical]
            get {
                if (_contextType == null) {
                    string typeName = ContextTypeName;
                    if (String.IsNullOrEmpty(typeName)) {
                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                            AtlasWeb.LinqDataSourceView_ContextTypeNameNotSpecified, _owner.ID));
                    }
                    try {
                        _contextType = BuildManager.GetType(typeName, /*throwOnFail*/true, /*ignoreCase*/true);
                    }
                    catch (Exception e) {
                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                            AtlasWeb.LinqDataSourceView_ContextTypeNameNotFound, _owner.ID), e);
                    }
                }
                return _contextType;
            }
        }

        public override string ContextTypeName {
            get {
                return _contextTypeName ?? String.Empty;
            }
            set {
                if (_contextTypeName != value) {
                    if (_reuseSelectContext) {
                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                            AtlasWeb.LinqDataSourceView_ContextTypeNameChanged, _owner.ID));
                    }
                    _contextTypeName = value;
                    _contextType = null;
                    OnDataSourceViewChanged(EventArgs.Empty);
                }
            }
        }

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

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

        public bool EnableObjectTracking {
            get {
                return _enableObjectTracking;
            }
            set {
                if (_enableObjectTracking != value) {
                    if (_reuseSelectContext) {
                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                            AtlasWeb.LinqDataSourceView_EnableObjectTrackingChanged, _owner.ID));
                    }
                    _enableObjectTracking = value;
                }
            }
        }

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

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

        public string TableName {
            get {
                return EntitySetName;
            }
            set {
                if (EntitySetName != value) {
                    if (_reuseSelectContext) {
                        throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                            AtlasWeb.LinqDataSourceView_TableNameChanged, _owner.ID));
                    }                    
                    EntitySetName = value;                    
                }
            }
        }

        public event EventHandler<LinqDataSourceStatusEventArgs> ContextCreated {
            add {
                Events.AddHandler(EventContextCreated, value);
            }
            remove {
                Events.RemoveHandler(EventContextCreated, value);
            }
        }

        public event EventHandler<LinqDataSourceContextEventArgs> ContextCreating {
            add {
                Events.AddHandler(EventContextCreating, value);
            }
            remove {
                Events.RemoveHandler(EventContextCreating, value);
            }
        }

        public event EventHandler<LinqDataSourceDisposeEventArgs> ContextDisposing {
            add {
                Events.AddHandler(EventContextDisposing, value);
            }
            remove {
                Events.RemoveHandler(EventContextDisposing, value);
            }
        }

        public event EventHandler<LinqDataSourceStatusEventArgs> Deleted {
            add {
                Events.AddHandler(EventDeleted, value);
            }
            remove {
                Events.RemoveHandler(EventDeleted, value);
            }
        }

        public event EventHandler<LinqDataSourceDeleteEventArgs> Deleting {
            add {
                Events.AddHandler(EventDeleting, value);
            }
            remove {
                Events.RemoveHandler(EventDeleting, value);
            }
        }

        internal event EventHandler<DynamicValidatorEventArgs> Exception {
            add {
                Events.AddHandler(EventException, value);
            }
            remove {
                Events.RemoveHandler(EventException, value);
            }
        }

        public event EventHandler<LinqDataSourceStatusEventArgs> Inserted {
            add {
                Events.AddHandler(EventInserted, value);
            }
            remove {
                Events.RemoveHandler(EventInserted, value);
            }
        }

        public event EventHandler<LinqDataSourceInsertEventArgs> Inserting {
            add {
                Events.AddHandler(EventInserting, value);
            }
            remove {
                Events.RemoveHandler(EventInserting, value);
            }
        }

        public event EventHandler<LinqDataSourceStatusEventArgs> Selected {
            add {
                Events.AddHandler(EventSelected, value);
            }
            remove {
                Events.RemoveHandler(EventSelected, value);
            }
        }

        public event EventHandler<LinqDataSourceSelectEventArgs> Selecting {
            add {
                Events.AddHandler(EventSelecting, value);
            }
            remove {
                Events.RemoveHandler(EventSelecting, value);
            }
        }

        public event EventHandler<LinqDataSourceStatusEventArgs> Updated {
            add {
                Events.AddHandler(EventUpdated, value);
            }
            remove {
                Events.RemoveHandler(EventUpdated, value);
            }
        }

        public event EventHandler<LinqDataSourceUpdateEventArgs> Updating {
            add {
                Events.AddHandler(EventUpdating, value);
            }
            remove {
                Events.RemoveHandler(EventUpdating, value);
            }
        }

        protected virtual object CreateContext(Type contextType) {
            return DataSourceHelper.CreateObjectInstance(contextType);
        }

        protected override ContextDataSourceContextData CreateContext(DataSourceOperation operation) {
            if (operation == DataSourceOperation.Select) {
                return CreateContextAndTableForSelect();
            }
            return CreateContextAndTableForEdit(operation);            
        }        

        private ContextDataSourceContextData CreateContextAndTable(DataSourceOperation operation) {
            ContextDataSourceContextData contextData = null;            
            bool eventFired = false;
            try {
                LinqDataSourceContextEventArgs contextEventArgs = new LinqDataSourceContextEventArgs(operation);
                OnContextCreating(contextEventArgs);

                contextData = new ContextDataSourceContextData(contextEventArgs.ObjectInstance);
                Type contextType = null;
                MemberInfo tableMemberInfo = null;
                if (contextData.Context == null) {
                    // construct the context unless accessing a static table for Select.
                    contextType = ContextType;
                    tableMemberInfo = GetTableMemberInfo(contextType);
                    if (tableMemberInfo != null) {
                        if (MemberIsStatic(tableMemberInfo)) {
                            if (operation != DataSourceOperation.Select) {
                                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                                    AtlasWeb.LinqDataSourceView_TableCannotBeStatic, TableName, contextType.Name, _owner.ID));
                            }
                        }
                        else {
                            contextData.Context = CreateContext(contextType);
                            _isNewContext = true;                            
                        }
                    }
                }
                else {
                    // use the manually constructed context.
                    tableMemberInfo = GetTableMemberInfo(contextData.Context.GetType());
                }

                // fetch the table from the context.
                if (tableMemberInfo != null) {
                    FieldInfo field = tableMemberInfo as FieldInfo;
                    if (field != null) {
                        contextData.EntitySet = field.GetValue(contextData.Context);
                    }
                    PropertyInfo property = tableMemberInfo as PropertyInfo;
                    if (property != null) {
                        contextData.EntitySet = property.GetValue(contextData.Context, null);
                    }
                }
                if (contextData.EntitySet == null) {
                    throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                        AtlasWeb.LinqDataSourceView_TableNameNotFound, TableName, contextType.Name, _owner.ID));
                }
            }
            catch (Exception e) {
                eventFired = true;
                LinqDataSourceStatusEventArgs createdEventArgs = new LinqDataSourceStatusEventArgs(e);
                OnContextCreated(createdEventArgs);
                OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.ContextCreate));
                // CreateContextAndTable will return null if this exception is handled.
                if (!createdEventArgs.ExceptionHandled) {
                    throw;
                }
            }
            finally {
                if (!eventFired) {
                    // contextData can be null if exception thrown from ContextCreating handler.
                    object context = (contextData == null) ? null : contextData.Context;
                    LinqDataSourceStatusEventArgs createdEventArgs = new LinqDataSourceStatusEventArgs(context);
                    OnContextCreated(createdEventArgs);
                }
            }
            return contextData;
        }

        private ContextDataSourceContextData CreateContextAndTableForEdit(DataSourceOperation operation) {
            ContextDataSourceContextData contextData = CreateContextAndTable(operation);
            // context data may be null or incomplete if an exception was handled
            if (contextData != null) {
                if (contextData.Context == null) {
                    return null;
                }
                if (contextData.EntitySet == null) {
                    DisposeContext(contextData.Context);
                    return null;
                }
                ValidateContextType(contextData.Context.GetType(), false);
                ValidateTableType(contextData.EntitySet.GetType(), false);
            }
            return contextData;
        }

        private ContextDataSourceContextData CreateContextAndTableForSelect() {
            _isNewContext = false;

            if (_selectContexts == null) {
                _selectContexts = new List<ContextDataSourceContextData>();
            }
            else if (_reuseSelectContext && _selectContexts.Count > 0) {
                return _selectContexts[_selectContexts.Count - 1];
            }

            // context data may be null if an exception was handled
            ContextDataSourceContextData contextData = CreateContextAndTable(DataSourceOperation.Select);
            if (contextData != null) {
                if (contextData.Context != null) {
                    ValidateContextType(contextData.Context.GetType(), true);
                }
                if (contextData.EntitySet != null) {
                    ValidateTableType(contextData.EntitySet.GetType(), true);
                }

                _selectContexts.Add(contextData);

                // context may not be dlinq context or may be null if table was static.
                DataContext dlinqContext = contextData.Context as DataContext;
                if ((dlinqContext != null) && _isNewContext) {
                    dlinqContext.ObjectTrackingEnabled = EnableObjectTracking;
                }
                // don't reuse dlinq contexts that cache data or exterior changes will not be reflected.
                _reuseSelectContext = (dlinqContext == null) || !EnableObjectTracking;
            }
            return contextData;
        }        

        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object",
            Justification = "Names are consistent with those used in the ObjectDataSource classes")]
        protected virtual void DeleteDataObject(object dataContext, object table, object oldDataObject) {
            _linqToSql.Attach((ITable)table, oldDataObject);
            _linqToSql.Remove((ITable)table, oldDataObject);
            _linqToSql.SubmitChanges((DataContext)dataContext);
        }

        protected override int DeleteObject(object oldEntity) {
            LinqDataSourceDeleteEventArgs deleteEventArgs = new LinqDataSourceDeleteEventArgs(oldEntity);
            OnDeleting(deleteEventArgs);
            if (deleteEventArgs.Cancel) {
                return -1;
            }

            LinqDataSourceStatusEventArgs deletedEventArgs = null;
            try {
                DeleteDataObject(Context, EntitySet, deleteEventArgs.OriginalObject);
            }
            catch (Exception e) {
                // allow user to handle dlinq exceptions including OnValidate validation.
                deletedEventArgs = new LinqDataSourceStatusEventArgs(e);
                OnDeleted(deletedEventArgs);
                OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.Delete));
                if (deletedEventArgs.ExceptionHandled) {
                    return -1;
                }
                throw;
            }
            deletedEventArgs = new LinqDataSourceStatusEventArgs(deleteEventArgs.OriginalObject);
            OnDeleted(deletedEventArgs);

            return 1;
        }

        protected override void DisposeContext(object dataContext) {
            if (dataContext != null) {
                LinqDataSourceDisposeEventArgs disposingEventArgs = new LinqDataSourceDisposeEventArgs(dataContext);
                OnContextDisposing(disposingEventArgs);
                if (!disposingEventArgs.Cancel) {
                    base.DisposeContext(dataContext);
                }
            }
        }

        protected override int ExecuteDelete(IDictionary keys, IDictionary oldValues) {
            ValidateDeleteSupported(keys, oldValues);
            return base.ExecuteDelete(keys, oldValues);
        }

        protected override int ExecuteInsert(IDictionary values) {
            ValidateInsertSupported(values);
            return base.ExecuteInsert(values);
        }

        protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) {
            ValidateUpdateSupported(keys, values, oldValues);
            return base.ExecuteUpdate(keys, values, oldValues);
        }
        
        protected internal override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments) {
            ClearOriginalValues();

            QueryContext queryContext = CreateQueryContext(arguments);
            object table = GetSource(queryContext);
            IList result = null;

            if (_selectResult != null) {
                try {
                    IQueryable query = QueryableDataSourceHelper.AsQueryable(_selectResult);
                    query = ExecuteQuery(query, queryContext);

                    Type dataObjectType = GetDataObjectType(query.GetType());
                    result = query.ToList(dataObjectType);

                    if (_storeOriginalValues) {
                        ITable dlinqTable = table as ITable;
                        // We can store original values if the type is exact or derived
                        if ((dlinqTable != null) && dataObjectType.IsAssignableFrom(EntityType)) {
                            StoreOriginalValues(result);
                        }
                    }
                }
                catch (Exception e) {
                    result = null;
                    LinqDataSourceStatusEventArgs selectedEventArgs = new LinqDataSourceStatusEventArgs(e);
                    OnSelected(selectedEventArgs);
                    OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.Select));
                    if (!selectedEventArgs.ExceptionHandled) {
                        throw;
                    }
                }
                finally {
                    if (result != null) {
                        int totalRowCount = -1; // paging performed, but row count not available.
                        if (arguments.RetrieveTotalRowCount) {
                            totalRowCount = arguments.TotalRowCount;
                        }
                        else if (!AutoPage) {
                            totalRowCount = result.Count;
                        }
                        LinqDataSourceStatusEventArgs selectedEventArgs = new LinqDataSourceStatusEventArgs(result, totalRowCount);
                        OnSelected(selectedEventArgs);
                    }
                }
                // Null out the select context
                Context = null;
            }
            return result;
        }        

        protected override object GetSource(QueryContext context) {
            LinqDataSourceSelectEventArgs selectEventArgs = new LinqDataSourceSelectEventArgs(
                context.Arguments,
                context.WhereParameters,
                context.OrderByParameters,
                context.GroupByParameters,
                context.OrderGroupsByParameters,
                context.SelectParameters);

            OnSelecting(selectEventArgs);
            if (selectEventArgs.Cancel) {
                return null;
            }

            _selectResult = selectEventArgs.Result;
            object table = _selectResult;

            // Original values should only be stored for valid delete and update scenarios.
            _storeOriginalValues = StoreOriginalValuesInViewState && (CanDelete || CanUpdate) &&
                String.IsNullOrEmpty(GroupBy) && String.IsNullOrEmpty(SelectNew);

            if (_selectResult == null) {
                table = base.GetSource(context);
                _selectResult = table;
            }
            // If the provided select result was not a DLinq table and we need to store
            // original values then we must get the table and create a new data context
            // instance so that we can access the column metadata.
            else if (!(table is ITable) && _storeOriginalValues) {
                table = base.GetSource(context);
            }

            return table;
        }

        protected virtual MemberInfo GetTableMemberInfo(Type contextType) {
            string tableName = TableName;
            if (String.IsNullOrEmpty(tableName)) {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                    AtlasWeb.LinqDataSourceView_TableNameNotSpecified, _owner.ID));
            }

            MemberInfo[] members = contextType.FindMembers(MemberTypes.Field | MemberTypes.Property,
                                                           BindingFlags.Public | BindingFlags.Instance |
                                                           BindingFlags.Static, /*filter*/null, /*filterCriteria*/null);

            for (int i = 0; i < members.Length; i++) {
                if (String.Equals(members[i].Name, tableName, StringComparison.OrdinalIgnoreCase)) {
                    return members[i];
                }
            }
            return null;
        }                                                            

        private ReadOnlyCollection<MetaDataMember> GetTableMetaDataMembers(ITable table, Type dataObjectType) {
            DataContext context = ((ITable)table).Context;
            MetaModel contextMetaData = context.Mapping;
            MetaTable tableMetaData = contextMetaData.GetTable(dataObjectType);
            MetaType rowMetaData = tableMetaData.Model.GetMetaType(dataObjectType);
            return rowMetaData.DataMembers;
        }

        protected override void HandleValidationErrors(IDictionary<string, Exception> errors, DataSourceOperation operation) {
            LinqDataSourceValidationException exception = new LinqDataSourceValidationException(String.Format(CultureInfo.InvariantCulture,
                AtlasWeb.LinqDataSourceView_ValidationFailed,
                EntityType, errors.Values.First().Message),
                errors);

            bool exceptionHandled = false;

            switch (operation) {
                case DataSourceOperation.Delete:
                    LinqDataSourceDeleteEventArgs deleteEventArgs = new LinqDataSourceDeleteEventArgs(exception);
                    OnDeleting(deleteEventArgs);
                    OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Delete));
                    exceptionHandled = deleteEventArgs.ExceptionHandled;
                    break;

                case DataSourceOperation.Insert:
                    LinqDataSourceInsertEventArgs insertEventArgs = new LinqDataSourceInsertEventArgs(exception);
                    OnInserting(insertEventArgs);
                    OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Insert));
                    exceptionHandled = insertEventArgs.ExceptionHandled;
                    break;
                case DataSourceOperation.Update:
                    // allow user to handle conversion or dlinq property validation exceptions.
                    LinqDataSourceUpdateEventArgs updateEventArgs = new LinqDataSourceUpdateEventArgs(exception);
                    OnUpdating(updateEventArgs);
                    OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Update));
                    exceptionHandled = updateEventArgs.ExceptionHandled;
                    break;
            }

            if (!exceptionHandled) {
                throw exception;
            }
        } 

        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object",
            Justification = "Names are consistent with those used in the ObjectDataSource classes")]
        protected virtual void InsertDataObject(object dataContext, object table, object newDataObject) {
            _linqToSql.Add((ITable)table, newDataObject);
            _linqToSql.SubmitChanges((DataContext)dataContext);
        }

        protected override int InsertObject(object newEntity) {
            LinqDataSourceInsertEventArgs insertEventArgs = new LinqDataSourceInsertEventArgs(newEntity);
            OnInserting(insertEventArgs);
            if (insertEventArgs.Cancel) {
                return -1;
            }

            LinqDataSourceStatusEventArgs insertedEventArgs = null;
            try {
                InsertDataObject(Context, EntitySet, insertEventArgs.NewObject);
            }
            catch (Exception e) {
                // allow user to handle dlinq exceptions including OnValidate validation.
                insertedEventArgs = new LinqDataSourceStatusEventArgs(e);
                OnInserted(insertedEventArgs);
                OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.Insert));
                if (insertedEventArgs.ExceptionHandled) {
                    return -1;
                }
                throw;
            }
            insertedEventArgs = new LinqDataSourceStatusEventArgs(insertEventArgs.NewObject);
            OnInserted(insertedEventArgs);

            return 1;
        }

        private static bool MemberIsStatic(MemberInfo member) {
            FieldInfo field = member as FieldInfo;
            if (field != null) {
                return field.IsStatic;
            }
            PropertyInfo property = member as PropertyInfo;
            if (property != null) {
                MethodInfo propertyGetter = property.GetGetMethod();
                return ((propertyGetter != null) && propertyGetter.IsStatic);
            }
            return false;
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnContextCreated(LinqDataSourceStatusEventArgs e) {
            EventHandler<LinqDataSourceStatusEventArgs> handler = (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventContextCreated];
            if (handler != null) {
                handler(this, e);
            }
        }        

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnContextCreating(LinqDataSourceContextEventArgs e) {
            EventHandler<LinqDataSourceContextEventArgs> handler = (EventHandler<LinqDataSourceContextEventArgs>)Events[EventContextCreating];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnContextDisposing(LinqDataSourceDisposeEventArgs e) {
            EventHandler<LinqDataSourceDisposeEventArgs> handler = (EventHandler<LinqDataSourceDisposeEventArgs>)Events[EventContextDisposing];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnDeleted(LinqDataSourceStatusEventArgs e) {
            EventHandler<LinqDataSourceStatusEventArgs> handler =
                (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventDeleted];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnDeleting(LinqDataSourceDeleteEventArgs e) {
            EventHandler<LinqDataSourceDeleteEventArgs> handler =
                (EventHandler<LinqDataSourceDeleteEventArgs>)Events[EventDeleting];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnException(DynamicValidatorEventArgs e) {
            EventHandler<DynamicValidatorEventArgs> handler = (EventHandler<DynamicValidatorEventArgs>)Events[EventException];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnInserted(LinqDataSourceStatusEventArgs e) {
            EventHandler<LinqDataSourceStatusEventArgs> handler =
                (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventInserted];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnInserting(LinqDataSourceInsertEventArgs e) {
            EventHandler<LinqDataSourceInsertEventArgs> handler =
                (EventHandler<LinqDataSourceInsertEventArgs>)Events[EventInserting];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnSelected(LinqDataSourceStatusEventArgs e) {
            EventHandler<LinqDataSourceStatusEventArgs> handler =
                (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventSelected];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnSelecting(LinqDataSourceSelectEventArgs e) {
            EventHandler<LinqDataSourceSelectEventArgs> handler =
                (EventHandler<LinqDataSourceSelectEventArgs>)Events[EventSelecting];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnUpdated(LinqDataSourceStatusEventArgs e) {
            EventHandler<LinqDataSourceStatusEventArgs> handler =
                (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventUpdated];
            if (handler != null) {
                handler(this, e);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")]
        protected virtual void OnUpdating(LinqDataSourceUpdateEventArgs e) {
            EventHandler<LinqDataSourceUpdateEventArgs> handler =
                (EventHandler<LinqDataSourceUpdateEventArgs>)Events[EventUpdating];
            if (handler != null) {
                handler(this, e);
            }
        }        

        internal void ReleaseSelectContexts() {
            if (_selectContexts != null) {
                foreach (ContextDataSourceContextData contextData in _selectContexts) {
                    DisposeContext(contextData.Context);
                }
            }
        }

        [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters",
            Justification = "Names are consistent with those used in the ObjectDataSource classes")]
        protected virtual void ResetDataObject(object table, object dataObject) {
            // DevDiv Bugs 187705, and 114508: Resetting is no longer necessary because
            // select has it's own context, but this method is kept for compatibility purposes.

            // no-op
        }

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

        private Dictionary<string, Exception> SetDataObjectProperties(object oldDataObject, object newDataObject) {
            Dictionary<string, Exception> validateExceptions = null;

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(oldDataObject);
            foreach (PropertyDescriptor property in properties) {
                if (property.PropertyType.IsSerializable && !property.IsReadOnly) {
                    object newValue = property.GetValue(newDataObject);
                    try {
                        property.SetValue(oldDataObject, newValue);
                    }
                    catch (Exception e) {
                        if (validateExceptions == null) {
                            validateExceptions = new Dictionary<string, Exception>(StringComparer.OrdinalIgnoreCase);
                        }
                        validateExceptions[property.Name] = e;
                    }
                }
            }

            return validateExceptions;
        }

        [SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods",
                         Justification = "System.Data.Linq assembly will be changing to support partial trust.")]
        protected override void StoreOriginalValues(IList results) {
            Type entityType = EntityType;
            IDictionary<string, MetaDataMember> columns = GetTableMetaDataMembers((ITable)EntitySet, entityType).ToDictionary(c => c.Member.Name);

            StoreOriginalValues(results, p => columns.ContainsKey(p.Name) && 
                                                (columns[p.Name].IsPrimaryKey || 
                                                columns[p.Name].IsVersion || 
                                                (columns[p.Name].UpdateCheck != UpdateCheck.Never)));
        }

        [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters",
            Justification = "Names are consistent with those used in the ObjectDataSource classes")]
        protected virtual void UpdateDataObject(object dataContext, object table,
                                                object oldDataObject, object newDataObject) {
            _linqToSql.Attach((ITable)table, oldDataObject);
            Dictionary<string, Exception> validateExceptions = SetDataObjectProperties(oldDataObject, newDataObject);

            // package up dlinq validation exceptions into single exception.
            if (validateExceptions != null) {
                throw new LinqDataSourceValidationException(String.Format(CultureInfo.InvariantCulture,
                    AtlasWeb.LinqDataSourceView_ValidationFailed, oldDataObject.GetType(), validateExceptions.Values.First().Message), validateExceptions);
            }

            _linqToSql.SubmitChanges((DataContext)dataContext);
        }

        protected override int UpdateObject(object oldEntity, object newEntity) {
            LinqDataSourceUpdateEventArgs updateEventArgs = new LinqDataSourceUpdateEventArgs(oldEntity, newEntity);
            OnUpdating(updateEventArgs);
            if (updateEventArgs.Cancel) {
                return -1;
            }

            LinqDataSourceStatusEventArgs updatedEventArgs = null;
            try {
                UpdateDataObject(Context, EntitySet, updateEventArgs.OriginalObject, updateEventArgs.NewObject);
            }
            catch (Exception e) {
                ResetDataObject(EntitySet, updateEventArgs.OriginalObject);
                // allow user to handle dlinq exceptions including OnValidate validation.
                updatedEventArgs = new LinqDataSourceStatusEventArgs(e);
                OnUpdated(updatedEventArgs);
                OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.Update));
                if (updatedEventArgs.ExceptionHandled) {
                    return -1;
                }
                throw;
            }
            updatedEventArgs = new LinqDataSourceStatusEventArgs(updateEventArgs.NewObject);
            OnUpdated(updatedEventArgs);

            return 1;
        }

        protected virtual void ValidateContextType(Type contextType, bool selecting) {
            if (!selecting && !typeof(DataContext).IsAssignableFrom(contextType)) {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                    AtlasWeb.LinqDataSourceView_InvalidContextType, _owner.ID));
            }
        }

        protected virtual void ValidateDeleteSupported(IDictionary keys, IDictionary oldValues) {
            if (!CanDelete) {
                throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture,
                AtlasWeb.LinqDataSourceView_DeleteNotSupported, _owner.ID));
            }
            ValidateEditSupported();
        }

        protected virtual void ValidateEditSupported() {
            if (!String.IsNullOrEmpty(GroupBy)) {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                    AtlasWeb.LinqDataSourceView_GroupByNotSupportedOnEdit, _owner.ID));
            }
            if (!String.IsNullOrEmpty(SelectNew)) {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                    AtlasWeb.LinqDataSourceView_SelectNewNotSupportedOnEdit, _owner.ID));
            }
        }

        protected virtual void ValidateInsertSupported(IDictionary values) {
            if (!CanInsert) {
                throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture,
                AtlasWeb.LinqDataSourceView_InsertNotSupported, _owner.ID));
            }
            ValidateEditSupported();
            if ((values == null) || (values.Count == 0)) {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                    AtlasWeb.LinqDataSourceView_InsertRequiresValues, _owner.ID));
            }
        }

        protected virtual void ValidateTableType(Type tableType, bool selecting) {
            if (!selecting) {
                if (!(tableType.IsGenericType && tableType.GetGenericArguments().Length == 1 && typeof(ITable).IsAssignableFrom(tableType))) {
                    throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture,
                        AtlasWeb.LinqDataSourceView_InvalidTablePropertyType, _owner.ID));
                }
            }
        }

        protected virtual void ValidateUpdateSupported(IDictionary keys, IDictionary values, IDictionary oldValues) {
            if (!CanUpdate) {
                throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture,
                AtlasWeb.LinqDataSourceView_UpdateNotSupported, _owner.ID));
            }
            ValidateEditSupported();
        }
    }

}