File: MetaColumn.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (707 lines) | stat: -rw-r--r-- 25,061 bytes parent folder | download | duplicates (8)
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
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Spatial;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Web.DynamicData.ModelProviders;
using System.Web.DynamicData.Util;

namespace System.Web.DynamicData {
    /// <summary>
    /// Object that represents a database column used by dynamic data
    /// </summary>
    public class MetaColumn : IFieldFormattingOptions, IMetaColumn {
        private TypeCode _typeCode = TypeCode.Empty;
        private Type _type;
        private object _metadataCacheLock = new object();

        // text, ntext, varchar(max), nvarchar(max) all have different maximum lengths so this is a minimum value
        // that ensures that all of the abovementioned columns get treated as long strings.
        private static readonly int s_longStringLengthCutoff = ((Int32.MaxValue >> 1) - 4);

        // Metadata related members
        private IMetaColumnMetadata _metadata;
        private bool? _scaffoldValueManual;
        private bool? _scaffoldValueDefault;

        public MetaColumn(MetaTable table, ColumnProvider columnProvider) {
            Table = table;
            Provider = columnProvider;
        }

        /// <summary>
        /// The collection of metadata attributes that apply to this column
        /// </summary>
        public AttributeCollection Attributes {
            get {
                return Metadata.Attributes;
            }
        }

        /// <summary>
        /// The CLR type of the property/column
        /// </summary>
        public Type ColumnType {
            get {
                if (_type == null) {
                    // If it's an Nullable<T>, work with T instead
                    _type = Misc.RemoveNullableFromType(Provider.ColumnType);
                }

                return _type;
            }
        }

        /// <summary>
        ///  The DataTypeAttribute used for the column
        /// </summary>
        public DataTypeAttribute DataTypeAttribute {
            get {
                return Metadata.DataTypeAttribute;
            }
        }

        /// <summary>
        /// This column's defalut value. It is typically used to populate the field when creating a new entry.
        /// </summary>
        public object DefaultValue {
            get {
                return Metadata.DefaultValue;
            }
        }

        /// <summary>
        /// A description for this column
        /// </summary>
        public virtual string Description {
            get {
                // 
                return Metadata.Description;
            }
        }

        /// <summary>
        /// A friendly display name for this column
        /// </summary>
        public virtual string DisplayName {
            get {
                // Default to the Name if there is no DisplayName
                return Metadata.DisplayName ?? Name;
            }
        }

        /// <summary>
        /// The PropertyInfo of the property that represents this column on the entity type
        /// </summary>
        public PropertyInfo EntityTypeProperty { get { return Provider.EntityTypeProperty; } }

        /// <summary>
        /// The FilterUIHint used for the column
        /// </summary>
        public string FilterUIHint {
            get {
                return Metadata.FilterUIHint;
            }
        }

        /// <summary>
        /// Does this column contain binary data
        /// </summary>
        public bool IsBinaryData {
            get {
                return ColumnType == typeof(byte[]);
            }
        }

        /// <summary>
        /// meant to indicate that a member is an extra property that was declared in a partial class 
        /// </summary>
        public bool IsCustomProperty { get { return Provider.IsCustomProperty; } }

        /// <summary>
        /// Is this column a floating point type (float, double, decimal)
        /// </summary>
        public bool IsFloatingPoint {
            get {
                return ColumnType == typeof(float) || ColumnType == typeof(double) || ColumnType == typeof(decimal);
            }
        }

        /// <summary>
        /// This is set for columns that are part of a foreign key. Note that it is NOT set for
        /// the strongly typed entity ref columns (though those columns 'use' one or more columns
        /// where IsForeignKeyComponent is set).
        /// </summary>
        public bool IsForeignKeyComponent {
            get { return Provider.IsForeignKeyComponent; }
        }

        /// <summary>
        /// Is this column's value auto-generated in the database
        /// </summary>
        public bool IsGenerated { get { return Provider.IsGenerated; } }

        /// <summary>
        /// Is this column a integer
        /// </summary>
        public bool IsInteger {
            get {
                return ColumnType == typeof(byte) || ColumnType == typeof(short) || ColumnType == typeof(int) || ColumnType == typeof(long);
            }
        }

        /// <summary>
        /// Is this column a 'long' string. This is used to determine whether a textbox or textarea should be used.
        /// </summary>
        public bool IsLongString {
            get {
                return IsString && Provider.MaxLength >= s_longStringLengthCutoff;
            }
        }

        /// <summary>
        /// Is this column part if the table's primary key
        /// </summary>
        public bool IsPrimaryKey { get { return Provider.IsPrimaryKey; } }

        /// <summary>
        /// Is this a readonly column
        /// </summary>
        [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
            Justification = "Interface denotes existence of property, not used for security.")]
        public virtual bool IsReadOnly {
            get {
                return Provider.IsReadOnly || Metadata.IsReadOnly ||
                    (Metadata.EditableAttribute != null && !Metadata.EditableAttribute.AllowEdit);
            }
        }

        /// <summary>
        /// Specifies if a read-only column (see IsReadOnly) allows for a value to be set on insert.
        /// The default value is false when the column is read-only; true when the column is not read-only.
        /// The default value can be override by using EditableAttribute (note that this will indicate that
        /// the column is meant to be read only).
        /// </summary>
        public bool AllowInitialValue {
            get {
                if (IsGenerated) {
                    // always return false for generated columns, since that is a stronger statement.
                    return false;
                }

                return Metadata.EditableAttribute.GetPropertyValue(a => a.AllowInitialValue, !IsReadOnly);
            }
        }

        /// <summary>
        /// Does this column require a value
        /// </summary>
        public bool IsRequired {
            get {
                return Metadata.RequiredAttribute != null;
            }
        }

        /// <summary>
        /// Is this column a string
        /// </summary>
        public bool IsString {
            get {
                return ColumnType == typeof(string);
            }
        }

        /// <summary>
        /// The maximun length allowed for this column (applies to string columns)
        /// </summary>
        public int MaxLength {
            get {
                var stringLengthAttribute = Metadata.StringLengthAttribute;
                return stringLengthAttribute != null ? stringLengthAttribute.MaximumLength : Provider.MaxLength;
            }
        }

        /// <summary>
        /// The MetaModel that this column belongs to
        /// </summary>
        public MetaModel Model { get { return Table.Model; } }

        /// <summary>
        /// The column's name
        /// </summary>
        public string Name { get { return Provider.Name; } }

        /// <summary>
        /// A value that can be used as a watermark in UI bound to value represented by this column.
        /// </summary>
        public virtual string Prompt { get { return Metadata.Prompt; } }

        /// <summary>
        /// the abstraction provider object that was used to construct this metacolumn.
        /// </summary>
        public ColumnProvider Provider { get; private set; }

        /// <summary>
        /// The error message used if this column is required and it is set to empty
        /// </summary>
        public string RequiredErrorMessage {
            get {
                var requiredAttribute = Metadata.RequiredAttribute;
                return requiredAttribute != null ? 
                    StringLocalizerUtil.GetLocalizedString(requiredAttribute, DisplayName) : String.Empty;
            }
        }

        /// <summary>
        /// Is it a column that should be displayed (e.g. in a GridView's auto generate mode) 
        /// </summary>
        [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
            Justification = "Interface denotes existence of property, not used for security.")]
        public virtual bool Scaffold {
            get {
                // If the value was explicitely set, that always takes precedence
                if (_scaffoldValueManual != null) {
                    return _scaffoldValueManual.Value;
                }

                // If there is a DisplayAttribute with an explicit value, always honor it
                var displayAttribute = Metadata.DisplayAttribute;
                if (displayAttribute != null && displayAttribute.GetAutoGenerateField().HasValue) {
                    return displayAttribute.GetAutoGenerateField().Value;
                }

                // If there is an explicit Scaffold attribute, always honor it
                var scaffoldAttribute = Metadata.ScaffoldColumnAttribute;
                if (scaffoldAttribute != null) {
                    return scaffoldAttribute.Scaffold;
                }

                if (_scaffoldValueDefault == null) {
                    _scaffoldValueDefault = ScaffoldNoCache;
                }

                return _scaffoldValueDefault.Value;
            }
            set {
                _scaffoldValueManual = value;
            }
        }

        /// <summary>
        /// Look at various pieces of data on the column to determine whether it's
        /// Scaffold mode should be on.  This only gets called once per column and the result
        /// is cached
        /// </summary>
        internal virtual bool ScaffoldNoCache {
            get {
                // Any field with a UIHint should be included
                if (!String.IsNullOrEmpty(UIHint)) return true;

                // Skip columns that are part of a foreign key, since they are already 'covered' in the
                // strongly typed foreign key column
                if (IsForeignKeyComponent) return false;

                // Skip generated columns, which are not typically interesting
                if (IsGenerated) return false;

                // Always include non-generated primary keys
                if (IsPrimaryKey) return true;

                // Skip custom properties
                if (IsCustomProperty) return false;

                // Include strings and characters
                if (IsString) return true;
                if (ColumnType == typeof(char)) return true;

                // Include numbers
                if (IsInteger) return true;
                if (IsFloatingPoint) return true;

                // Include date related columns
                if (ColumnType == typeof(DateTime)) return true;
                if (ColumnType == typeof(TimeSpan)) return true;
                if (ColumnType == typeof(DateTimeOffset)) return true;


                // Include bools
                if (ColumnType == typeof(bool)) return true;

                // Include enums
                Type enumType;
                if (this.IsEnumType(out enumType)) return true;

                //Include spatial types
                if (ColumnType == typeof(DbGeography)) return true;
                if (ColumnType == typeof(DbGeometry)) return true;

                return false;
            }
        }

        /// <summary>
        /// A friendly short display name for this column. Meant to be used in GridView and similar controls where there might be
        /// limited column header space
        /// </summary>
        public virtual string ShortDisplayName {
            get {
                // Default to the DisplayName if there is no ShortDisplayName
                return Metadata.ShortDisplayName ?? DisplayName;
            }
        }

        /// <summary>
        /// The expression used to determine the sort order for this column
        /// </summary>
        public string SortExpression {
            get {
                return SortExpressionInternal;
            }
        }

        internal virtual string SortExpressionInternal {
            get {
                return Provider.IsSortable ? Name : string.Empty;
            }
        }

        /// <summary>
        /// The MetaTable that this column belongs to
        /// </summary>
        public MetaTable Table { get; private set; }

        /// <summary>
        /// The TypeCode of this column. It is derived from the ColumnType
        /// </summary>
        public TypeCode TypeCode {
            get {
                if (_typeCode == TypeCode.Empty) {
                    _typeCode = DataSourceUtil.TypeCodeFromType(ColumnType);
                }

                return _typeCode;
            }
        }

        /// <summary>
        ///  The UIHint used for the column
        /// </summary>
        [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces",
            Justification = "Interface denotes existence of property, not used for security.")]
        public virtual string UIHint {
            get {
                return Metadata.UIHint;
            }
        }

        #region IFieldFormattingOptions Members

        /// <summary>
        /// Same semantic as the same property on System.Web.UI.WebControls.BoundField
        /// </summary>
        public bool ApplyFormatInEditMode {
            get {
                return Metadata.ApplyFormatInEditMode;
            }
        }

        /// <summary>
        /// Same semantic as the same property on System.Web.UI.WebControls.BoundField
        /// </summary>
        public bool ConvertEmptyStringToNull {
            get {
                return Metadata.ConvertEmptyStringToNull;
            }
        }

        /// <summary>
        /// Same semantic as the same property on System.Web.UI.WebControls.BoundField
        /// </summary>
        public string DataFormatString {
            get {
                return Metadata.DataFormatString;
            }
        }

        /// <summary>
        /// Same semantic as the same property on System.Web.UI.WebControls.BoundField
        /// </summary>
        public bool HtmlEncode {
            get { 
                return Metadata.HtmlEncode; 
            }
        }

        /// <summary>
        /// Same semantic as the same property on System.Web.UI.WebControls.BoundField
        /// </summary>
        public string NullDisplayText {
            get {
                return Metadata.NullDisplayText;
            }
        }

        #endregion

        /// <summary>
        /// Build the attribute collection, later made available through the Attributes property
        /// </summary>
        protected virtual AttributeCollection BuildAttributeCollection() {
            return Provider.Attributes;
        }

        /// <summary>
        /// Perform initialization logic for this column
        /// </summary>
        internal protected virtual void Initialize() { }

        /// <summary>
        /// Resets cached column metadata (i.e. information coming from attributes). The metadata cache will be rebuilt
        /// the next time any metadata-derived information gets requested.
        /// </summary>
        public void ResetMetadata() {
            _metadata = null;
        }

        /// <summary>
        /// Shows the column name. Mostly for debugging purpose.
        /// </summary>
        [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public override string ToString() {
            return GetType().Name + " " + Name;
        }

        internal IMetaColumnMetadata Metadata {
            get {
                // Use a local to avoid returning null if ResetMetadata is called
                IMetaColumnMetadata metadata = _metadata;
                if (metadata == null) {
                    metadata = new MetaColumnMetadata(this);
                    _metadata = metadata;
                }
                return metadata;
            }
            set {
                // settable for unit testing
                _metadata = value;
            }
        }

        #region Metadata abstraction

        internal interface IMetaColumnMetadata {

            AttributeCollection Attributes { get; }

            DisplayAttribute DisplayAttribute { get; }

            bool ApplyFormatInEditMode { get; }

            bool ConvertEmptyStringToNull { get; }

            bool HtmlEncode { get; }

            string DataFormatString { get; }

            DataTypeAttribute DataTypeAttribute { get; }

            object DefaultValue { get; }

            string Description { get; }

            string DisplayName { get; }

            string FilterUIHint { get; }

            string ShortDisplayName { get; }

            string NullDisplayText { get; }

            string Prompt { get; }

            RequiredAttribute RequiredAttribute { get; }

            ScaffoldColumnAttribute ScaffoldColumnAttribute { get; }

            StringLengthAttribute StringLengthAttribute { get; }

            string UIHint { get; }

            bool IsReadOnly { get; }

            EditableAttribute EditableAttribute { get; }
        }

        internal class MetaColumnMetadata : IMetaColumnMetadata {
            private MetaColumn Column { get; set; }

            public AttributeCollection Attributes { get; private set; }

            public MetaColumnMetadata(MetaColumn column) {
                Debug.Assert(column != null);
                Column = column;

                Attributes = Column.BuildAttributeCollection();

                DisplayAttribute = Attributes.FirstOrDefault<DisplayAttribute>();
                DataTypeAttribute = Attributes.FirstOrDefault<DataTypeAttribute>() ?? GetDefaultDataTypeAttribute();
                DescriptionAttribute = Attributes.FirstOrDefault<DescriptionAttribute>();
                DefaultValueAttribute = Attributes.FirstOrDefault<DefaultValueAttribute>();
                DisplayNameAttribute = Attributes.FirstOrDefault<DisplayNameAttribute>();
                RequiredAttribute = Attributes.FirstOrDefault<RequiredAttribute>();
                ScaffoldColumnAttribute = Attributes.FirstOrDefault<ScaffoldColumnAttribute>();
                StringLengthAttribute = Attributes.FirstOrDefault<StringLengthAttribute>();

                UIHint = GetHint<UIHintAttribute>(a => a.PresentationLayer, a => a.UIHint);
                FilterUIHint = GetHint<FilterUIHintAttribute>(a => a.PresentationLayer, a => a.FilterUIHint);

                EditableAttribute = Attributes.FirstOrDefault<EditableAttribute>();
                IsReadOnly = Attributes.GetAttributePropertyValue<ReadOnlyAttribute, bool>(a => a.IsReadOnly, false);

                var displayFormatAttribute = Attributes.FirstOrDefault<DisplayFormatAttribute>() ??
                    (DataTypeAttribute != null ? DataTypeAttribute.DisplayFormat : null);

                ApplyFormatInEditMode = displayFormatAttribute.GetPropertyValue(a => a.ApplyFormatInEditMode, false);
                ConvertEmptyStringToNull = displayFormatAttribute.GetPropertyValue(a => a.ConvertEmptyStringToNull, true);
                DataFormatString = displayFormatAttribute.GetPropertyValue(a => a.DataFormatString, String.Empty);
                NullDisplayText = displayFormatAttribute.GetPropertyValue(a => a.NullDisplayText, String.Empty);
                HtmlEncode = displayFormatAttribute.GetPropertyValue(a => a.HtmlEncode, true);
            }

            public DisplayAttribute DisplayAttribute { get; private set; }

            public bool ApplyFormatInEditMode { get; private set; }

            public bool ConvertEmptyStringToNull { get; private set; }

            public string DataFormatString { get; private set; }

            public DataTypeAttribute DataTypeAttribute { get; private set; }

            public object DefaultValue {
                get {
                    return DefaultValueAttribute.GetPropertyValue(a => a.Value, null);
                }
            }

            private DefaultValueAttribute DefaultValueAttribute { get; set; }

            public string Description {
                get {
                    return DisplayAttribute.GetLocalizedDescription() ??
                        DescriptionAttribute.GetPropertyValue(a => a.Description, null);
                }
            }

            private DescriptionAttribute DescriptionAttribute { get; set; }

            public string DisplayName {
                get {
                    return DisplayAttribute.GetLocalizedName() ??
                        DisplayNameAttribute.GetPropertyValue(a => a.DisplayName, null);
                }
            }

            public string ShortDisplayName {
                get {
                    return DisplayAttribute.GetLocalizedShortName();
                }
            }

            private DisplayNameAttribute DisplayNameAttribute { get; set; }

            public string FilterUIHint { get; private set; }

            public EditableAttribute EditableAttribute { get; private set; }

            public bool IsReadOnly { get; private set; }

            public string NullDisplayText { get; private set; }

            public string Prompt {
                get {
                    return DisplayAttribute.GetLocalizedPrompt();
                }
            }

            public RequiredAttribute RequiredAttribute { get; private set; }

            public ScaffoldColumnAttribute ScaffoldColumnAttribute { get; private set; }

            public StringLengthAttribute StringLengthAttribute { get; private set; }

            public string UIHint { get; private set; }

            private DataTypeAttribute GetDefaultDataTypeAttribute() {
                if (Column.IsString) {
                    if (Column.IsLongString) {
                        return new DataTypeAttribute(DataType.MultilineText);
                    }
                    else {
                        return new DataTypeAttribute(DataType.Text);
                    }
                }

                return null;
            }

            private string GetHint<T>(Func<T, string> presentationLayerPropertyAccessor, Func<T, string> hintPropertyAccessor) where T : Attribute {
                var uiHints = Attributes.OfType<T>();
                var presentationLayerNotSpecified = uiHints.Where(a => String.IsNullOrEmpty(presentationLayerPropertyAccessor(a)));
                var presentationLayerSpecified = uiHints.Where(a => !String.IsNullOrEmpty(presentationLayerPropertyAccessor(a)));

                T uiHintAttribute = presentationLayerSpecified.FirstOrDefault(a => presentationLayerPropertyAccessor(a).ToLower(CultureInfo.InvariantCulture) == "webforms" ||
                                                                                   presentationLayerPropertyAccessor(a).ToLower(CultureInfo.InvariantCulture) == "mvc") ??
                                                  presentationLayerNotSpecified.FirstOrDefault();

                return uiHintAttribute.GetPropertyValue(hintPropertyAccessor);
            }


            public bool HtmlEncode {
                get; set;
            }
        }

        #endregion

        string IMetaColumn.Description {
            get {
                return Description;
            }
        }

        string IMetaColumn.DisplayName {
            get {
                return DisplayName;
            }
        }

        string IMetaColumn.Prompt {
            get {
                return Prompt;
            }
        }

        string IMetaColumn.ShortDisplayName {
            get {
                return ShortDisplayName;
            }
        }

        IMetaTable IMetaColumn.Table {
            get {
                return Table;
            }
        }

        IMetaModel IMetaColumn.Model {
            get {
                return Model;
            }
        }
    }
}