File: FieldTemplateFactory.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (333 lines) | stat: -rw-r--r-- 13,913 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
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Spatial;
using System.Diagnostics;
using System.Globalization;
using System.Web.Compilation;
using System.Web.Hosting;
using System.Web.UI.WebControls;

namespace System.Web.DynamicData {
    /// <summary>
    /// Default implementation of IFieldTemplateFactory. It uses user controls for the field templates.
    /// </summary>
    public class FieldTemplateFactory : IFieldTemplateFactory {
        private const string IntegerField = "Integer";
        private const string ForeignKeyField = "ForeignKey";
        private const string ChildrenField = "Children";
        private const string ManyToManyField = "ManyToMany";
        private const string EnumerationField = "Enumeration";

        private const string EditModePathModifier = "_Edit";
        private const string InsertModePathModifier = "_Insert";

        private Dictionary<Type, string> _typesToTemplateNames;
        private Dictionary<Type, Type> _typesFallBacks;

        private TemplateFactory _templateFactory;

        /// <summary>
        /// </summary>
        public FieldTemplateFactory() {
            InitTypesToTemplateNamesTable();
            BuildTypeFallbackTable();
            _templateFactory = new TemplateFactory("FieldTemplates");
        }

        // For unit test purpose
        internal FieldTemplateFactory(VirtualPathProvider vpp)
            : this() {
            _templateFactory.VirtualPathProvider = vpp;
        }

        /// <summary>
        /// Sets the folder containing the user controls. By default, this is ~/DynamicData/FieldTemplates/
        /// </summary>
        public string TemplateFolderVirtualPath {
            get {
                return _templateFactory.TemplateFolderVirtualPath;
            }
            set {
                _templateFactory.TemplateFolderVirtualPath = value;
            }
        }

        /// <summary>
        /// The MetaModel that the factory is associated with
        /// </summary>
        public MetaModel Model {
            get {
                return _templateFactory.Model;
            }
            private set {
                _templateFactory.Model = value;
            }
        }

        private void InitTypesToTemplateNamesTable() {
            _typesToTemplateNames = new Dictionary<Type, string>();
            _typesToTemplateNames[typeof(int)] = FieldTemplateFactory.IntegerField;
            _typesToTemplateNames[typeof(string)] = DataType.Text.ToString();
        }

        private void BuildTypeFallbackTable() {
            _typesFallBacks = new Dictionary<Type, Type>();
            _typesFallBacks[typeof(float)] = typeof(decimal);
            _typesFallBacks[typeof(double)] = typeof(decimal);
            _typesFallBacks[typeof(Int16)] = typeof(int);
            _typesFallBacks[typeof(byte)] = typeof(int);
            _typesFallBacks[typeof(long)] = typeof(int);

            // Fall back to strings for most types
            _typesFallBacks[typeof(char)] = typeof(string);
            _typesFallBacks[typeof(int)] = typeof(string);
            _typesFallBacks[typeof(decimal)] = typeof(string);
            _typesFallBacks[typeof(Guid)] = typeof(string);
            _typesFallBacks[typeof(DateTime)] = typeof(string);
            _typesFallBacks[typeof(DateTimeOffset)] = typeof(string);
            _typesFallBacks[typeof(TimeSpan)] = typeof(string);
            _typesFallBacks[typeof(DbGeography)] = typeof(string);
            _typesFallBacks[typeof(DbGeometry)] = typeof(string);

            // 
        }

        private Type GetFallBackType(Type t) {
            // Check if there is a fallback type
            Type fallbackType;
            if (_typesFallBacks.TryGetValue(t, out fallbackType))
                return fallbackType;

            return null;
        }

        // Internal for unit test purpose
        internal string GetFieldTemplateVirtualPathWithCaching(MetaColumn column, DataBoundControlMode mode, string uiHint) {
            // Compute a cache key based on all the input paramaters
            long cacheKey = Misc.CombineHashCodes(uiHint, column, mode);

            Func<string> templatePathFactoryFunction = () => GetFieldTemplateVirtualPath(column, mode, uiHint);

            return _templateFactory.GetTemplatePath(cacheKey, templatePathFactoryFunction);
        }

        /// <summary>
        /// Returns the virtual path of the field template user control to be used, based on various pieces of data
        /// </summary>
        /// <param name="column">The MetaColumn for which the field template is needed</param>
        /// <param name="mode">The mode (Readonly, Edit, Insert) for which the field template is needed</param>
        /// <param name="uiHint">The UIHint (if any) that should affect the field template lookup</param>
        /// <returns></returns>
        public virtual string GetFieldTemplateVirtualPath(MetaColumn column, DataBoundControlMode mode, string uiHint) {

            mode = PreprocessMode(column, mode);

            bool hasDataTypeAttribute = column != null && column.DataTypeAttribute != null;

            // Set the UIHint in some special cases, but don't do it if we already have one or
            // if we have a DataTypeAttribute
            if (String.IsNullOrEmpty(uiHint) && !hasDataTypeAttribute) {
                // Check if it's an association
                // Or if it is an enum
                if (column is MetaForeignKeyColumn) {
                    uiHint = FieldTemplateFactory.ForeignKeyField;
                } else if (column is MetaChildrenColumn) {
                    var childrenColumn = (MetaChildrenColumn)column;
                    if (childrenColumn.IsManyToMany) {
                        uiHint = FieldTemplateFactory.ManyToManyField;
                    }
                    else {
                        uiHint = FieldTemplateFactory.ChildrenField;
                    }
                } else if (column.ColumnType.IsEnum) {
                    uiHint = FieldTemplateFactory.EnumerationField;
                }
            }

            return GetVirtualPathWithModeFallback(uiHint, column, mode);
        }

        /// <summary>
        /// Gets a chance to change the mode.  e.g. an Edit mode request can be turned into ReadOnly mode
        /// if the column is a primary key
        /// </summary>
        public virtual DataBoundControlMode PreprocessMode(MetaColumn column, DataBoundControlMode mode) {
            if (column == null) {
                throw new ArgumentNullException("column");
            }

            // Primary keys can't be edited, so put them in readonly mode.  Note that this
            // does not apply to Insert mode, which is fine
            if (column.IsPrimaryKey && mode == DataBoundControlMode.Edit) {
                mode = DataBoundControlMode.ReadOnly;
            }

            // Generated columns should never be editable/insertable
            if (column.IsGenerated) {
                mode = DataBoundControlMode.ReadOnly;
            }

            // ReadOnly columns cannot be edited nor inserted, and are always in Display mode
            if (column.IsReadOnly) {
                if (mode == DataBoundControlMode.Insert && column.AllowInitialValue) {
                    // but don't change the mode if we're in insert and an initial value is allowed
                } else {
                    mode = DataBoundControlMode.ReadOnly;
                }
            }

            // If initial value is not allowed set mode to ReadOnly
            if (mode == DataBoundControlMode.Insert && !column.AllowInitialValue) {
                mode = DataBoundControlMode.ReadOnly;
            }

            if (column is MetaForeignKeyColumn) {
                // If the foreign key is part of the primary key (e.g. Order and Product in Order_Details table),
                // change the mode to ReadOnly so that they can't be edited.
                if (mode == DataBoundControlMode.Edit && ((MetaForeignKeyColumn)column).IsPrimaryKeyInThisTable) {
                    mode = DataBoundControlMode.ReadOnly;
                }
            }

            return mode;
        }

        private string GetVirtualPathWithModeFallback(string templateName, MetaColumn column, DataBoundControlMode mode) {
            // Try not only the requested mode, but others if needed.  Basically:
            // - an edit template can default to an item template
            // - an insert template can default to an edit template, then to an item template
            for (var currentMode = mode; currentMode >= 0; currentMode--) {
                string virtualPath = GetVirtualPathForMode(templateName, column, currentMode);
                if (virtualPath != null)
                    return virtualPath;
            }

            // We couldn't locate any field template at all, so give up
            return null;
        }

        private string GetVirtualPathForMode(string templateName, MetaColumn column, DataBoundControlMode mode) {

            // If we got a template name, try it
            if (!String.IsNullOrEmpty(templateName)) {
                string virtualPath = GetVirtualPathIfExists(templateName, column, mode);
                if (virtualPath != null)
                    return virtualPath;
            }

            // Otherwise, use the column's type
            return GetVirtualPathForTypeWithFallback(column.ColumnType, column, mode);
        }

        private string GetVirtualPathForTypeWithFallback(Type fieldType, MetaColumn column, DataBoundControlMode mode) {

            string templateName;
            string virtualPath;

            // If we have a data type attribute
            if (column.DataTypeAttribute != null) {
                templateName = column.DataTypeAttribute.GetDataTypeName();

                // Try to get the path from it
                virtualPath = GetVirtualPathIfExists(templateName, column, mode);
                if (virtualPath != null)
                    return virtualPath;
            }

            // Try the actual fully qualified type name (i.e. with the namespace)
            virtualPath = GetVirtualPathIfExists(fieldType.FullName, column, mode);
            if (virtualPath != null)
                return virtualPath;

            // Try the simple type name
            virtualPath = GetVirtualPathIfExists(fieldType.Name, column, mode);
            if (virtualPath != null)
                return virtualPath;

            // If our type name table has an entry for it, try it
            if (_typesToTemplateNames.TryGetValue(fieldType, out templateName)) {
                virtualPath = GetVirtualPathIfExists(templateName, column, mode);
                if (virtualPath != null)
                    return virtualPath;
            }

            // Check if there is a fallback type
            Type fallbackType = GetFallBackType(fieldType);

            // If not, we've run out of options
            if (fallbackType == null)
                return null;

            // If so, try it
            return GetVirtualPathForTypeWithFallback(fallbackType, column, mode);
        }

        private string GetVirtualPathIfExists(string templateName, MetaColumn column, DataBoundControlMode mode) {
            // Build the path
            string virtualPath = BuildVirtualPath(templateName, column, mode);

            // Check if it exists
            if (_templateFactory.FileExists(virtualPath))
                return virtualPath;

            // If not, return null
            return null;
        }

        /// <summary>
        /// Build the virtual path to the field template user control based on the template name and mode.
        /// By default, it returns names that look like TemplateName_ModeName.ascx, in the folder specified
        /// by TemplateFolderVirtualPath.
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="column"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public virtual string BuildVirtualPath(string templateName, MetaColumn column, DataBoundControlMode mode) {
            if (String.IsNullOrEmpty(templateName)) {
                throw new ArgumentNullException("templateName");
            }

            string modePathModifier = null;
            switch (mode) {
                case DataBoundControlMode.ReadOnly:
                    modePathModifier = String.Empty;
                    break;
                case DataBoundControlMode.Edit:
                    modePathModifier = FieldTemplateFactory.EditModePathModifier;
                    break;
                case DataBoundControlMode.Insert:
                    modePathModifier = FieldTemplateFactory.InsertModePathModifier;
                    break;
                default:
                    Debug.Assert(false);
                    break;
            }

            return String.Format(CultureInfo.InvariantCulture,
                TemplateFolderVirtualPath + "{0}{1}.ascx", templateName, modePathModifier);
        }

        #region IFieldTemplateFactory Members

        public virtual void Initialize(MetaModel model) {
            Model = model;
        }

        /// <summary>
        /// See IFieldTemplateFactory for details.
        /// </summary>
        /// <returns></returns>
        public virtual IFieldTemplate CreateFieldTemplate(MetaColumn column, DataBoundControlMode mode, string uiHint) {
            string fieldTemplatePath = GetFieldTemplateVirtualPathWithCaching(column, mode, uiHint);

            if (fieldTemplatePath == null)
                return null;

            return (IFieldTemplate)BuildManager.CreateInstanceFromVirtualPath(
                fieldTemplatePath, typeof(IFieldTemplate));
        }

        #endregion
    }
}