Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Field Template Lookup Rules

Dynamic Data tries to find the most specific template that matches the field based on the column type and control mode. If such a field template does not exist, Dynamic Data will gradually relax the matching rules until it finds the best possible match among the field templates in the project.

Data Annotations

Consider the RequiredDate column of the Order table used in Listing 3.3 earlier in this chapter. If the developer specifies the exact template name by applying the UIHintAttribute as shown in Listing 3.14, Dynamic Data first checks to see if a template with the specified name, MyDate.ascx, exists. If this template does not exist, Dynamic Data then checks if a DataTypeAttribute is applied to the column and tries using the specified DataType value as the template name. In this example, it checks to see if a field template called Date.ascx exists.

Listing 3.14. Data Annotations That Affect Field Template Lookup

using System.ComponentModel.DataAnnotations;

namespace DataModel
{
  [MetadataType(typeof(Order.Metadata))]
  partial class Order
  {
    public class Metadata
    {
      [UIHint("MyDate")]
      [DataType(DataType.Date)]
      public object RequiredDate;
    }
  }
}

Type Names

If the column has no data annotation attributes, Dynamic Data then tries to find a matching template based on the name of its type. First, it looks for a template whose name matches the full name of the type, including the namespace where the type is defined. In the example of RequiredDate, when looking for a template for a column of DateTime type, it checks to see if a template called System.DateTime.ascx exists. If not, Dynamic Data then tries the short type name, without the namespace, and finally chooses the template called DateTime.ascx provided by Dynamic Data out of the box.

Type Aliases

Dynamic Data allows template names to use special aliases instead of actual type names for two built-in .NET types, Int32 and String. When looking for a field template for a column of type String, Dynamic Data considers the template called Text.ascx to be a match. In the Northwind data model, this means that the Text.ascx template will be used for the ProductName column of the Product table. Likewise, when looking for a template for an Int32 column, Dynamic Data considers Integer.ascx to be a match as well. Table 3.1 shows the built-in type aliases at a glance.

Table 3.1. Type Name Aliases

Type Name

Alias

Int32

Integer

String

Text

Type aliases are considered less specific than the type names, and type names take precedence over aliases during template lookup. For example, if the Dynamic Data project contains templates called Int32.ascx and Integer.ascx, only the one called Int32.ascx will be used for an integer column.

Type Fallback

If there is no matching field template for a particular data type, Dynamic Data uses fallback logic to find a template for a more generic type that could be used instead. Consider the UnitsInStock column of the Product entity, which is of type Int16. When looking for a field template for this column, Dynamic Data first checks to see if a template called Int16.ascx exists. Because there is no template with this name, it uses the fallback rules shown in Table 3.2 to determine the fallback type, Int32, and tries to find a matching template for that type.

Table 3.2. Type Fallback Rules

Data Type

Fallback Type

Double, Float

Decimal

Byte, Int16, Int64

Int32

Char, Decimal, DateTime, DateTimeOffset, Guid Int32, TimeSpan

String

Both type names and aliases are used during template lookup for the fallback type, just as they were used for the original type. For the UnitsInStock column, this means that Dynamic Data will then try System.Int32.ascx, Int32.ascx, and Integer.ascx. Because none of these field templates exist in the default Dynamic Data project, it falls back to the next type—String and tries System.String.ascx, String.ascx, and finally choosing Text.ascx.

Control Mode

Control mode defines the context where the field template will be used. It can be one of the members of the ASP.NET DataBoundControlMode enumeration:

  • ReadOnly templates are used by the Details.aspx page template or custom pages to display field values in Read-only mode.
  • Edit templates are used by the Edit.aspx page template or custom pages to change field values of an existing row.
  • Insert are used by the Insert.aspx page template or custom pages to collect field values for a new row.

When looking for a ReadOnly field template for the ShippedDate column of the Order table, which has DateTime data type and no additional metadata attributes in the sample data model, Dynamic Data finds the DateTime.ascx template. Edit mode is considered more specific because it requires the field template to not only display the current field value, but also allow changing it. Therefore, when looking for an Edit field template for the ShippedDate column, Dynamic Data chooses the template called DateTime_Edit.ascx if it exists. Note that Dynamic Data uses the "_Edit" suffix for Edit templates and no suffix for the ReadOnly templates. The Insert mode is even more specific because it might require special logic to deal with rows that have not been submitted to the database, and Dynamic Data chooses the template called DateTime_Insert.ascx if it exists.

Mode Fallback

If there is no matching field template for a particular control mode, Dynamic Data uses fallback logic to find another template for a more generic mode. In this ongoing example, when looking for an Insert template for the ShippedDate column, Dynamic Data will first try to find the template called DateTime_Insert.ascx. Because there is no field template with this name, it falls back from the Insert to the Edit mode and ends up using the template called DateTime_Edit.ascx, assuming it can handle both Edit and Insert modes. Similarly, if an Edit mode template cannot be found, Dynamic Data falls back to Read-only mode.

However, before Dynamic Data falls back to the next mode, it performs the type fallback. Consider UnitsInStock, an Int16 column from the Products table. When looking for an Edit template for this field, it tries using System.Int16_Edit.ascx and Int16_Edit.ascx templates first, but because they do not exist, it falls back to type Int32 and checks for System.Int32_Edit.ascx and Int32_Edit.ascx and eventually finds Integer_Edit.ascx. If Dynamic Data performed the mode fallback first, it would skip this template and try to look for a ReadOnly template called System.Int16.ascx instead.

Navigation Columns

So far, our discussion has been about the lookup rules Dynamic Data uses for columns of primitive types that can be stored using built-in system types like Int32 and String. The Dynamic Data metadata API represents them using the MetaColumn class.

Navigation columns, on the other hand, are columns that provide access to one or more entities that are defined as custom classes in the data model itself. There are three types of navigation columns from the Dynamic Data prospective:

  • MetaForeignKeyColumn represents a navigation property that returns a single entity referenced by the underlying foreign key field. In the Northwind example, Product is a foreign key column of the Order_Detail entity that represents the Product entity referenced by the ProductID foreign key field.
  • MetaChildrenColumn is an opposite of a foreign key. In the Northwind example, Order_Details column of the Product entity returns all Order_Detail items that reference a particular product instance.
  • Many-to-Many column is a special case of a MetaChildrenColumn where the IsManyToMany property is set to true. In the Northwind example, the Territories column of the Employees entity returns all territories assigned to a particular employee. Likewise, the Employees column of the Territory entity returns all employees assigned to work in a particular Territory. Dynamic Data considers both of these columns as Many-to-Many.

Navigation columns get special treatment during field template lookup. Unless the developer already placed a UIHintAttribute on a navigation property, Dynamic Data uses the rules shown in Table 3.3 to come up with a default UI Hint.

Table 3.3. Navigation Column Rules

Column Type

UI Hint

MetaForeignKeyColumn

ForeignKey

MetaChildrenColumn

Children

MetaChildrenColumn, IsManyToMany = true

ManyToMany

In this example, it means that for the Product column of the Order_Details table, Dynamic Data uses a template called ForeignKey.ascx; for the Order_Details column of the Product table, it uses a template called Children.ascx; and for both Employee.Territories and Territory.Employees columns, it uses the template called ManyToMany.ascx.

Effectively, there is no type fallback during template lookup for navigation columns. However, Dynamic Data does perform mode fallback, so if your page needs a foreign key template in Insert mode, it first tries ForeignKey_Insert.ascx, then ForeignKey_Edit.ascx, and then ForeignKey.ascx if necessary. The default Dynamic Data project template actually takes advantage of this to disable user interface for the children columns in Insert mode. If you open the Children_Insert.ascx field template, you see that it is empty. If this empty field template did not exist, Children.ascx would be used in its place, causing runtime errors because this template is not prepared to handle the scenario when the parent row does not exist.

Field Template Lookup Algorithm

Although the lookup rules for field templates might seem complex at a first, they are based on common-sense logic, and when you understand the idea behind them, the results will feel intuitive. Just remember that Dynamic Data tries to choose the most specific field template based on the column definition and control mode, and if such a field template does not exist, it gradually relaxes the matching rules until it finds a match or reports an error. The resulting behavior allows you to easily add new field templates where unique behavior is required to support a particular column type while allowing you to reuse existing templates with common behavior such as displaying read-only field values. Figure 3.4 shows the actual algorithm used by Dynamic Data. FieldTemplateFactory, a special class defined in the System.Web.DynamicData namespace, performs this task.

Figure 3.4

Figure 3.4. Field template lookup algorithm.

As an example, consider Table 3.4, which shows the sequence of template file names Dynamic Data will try when looking for a matching field template for the HomePhone property of the Employee entity.

Table 3.4. Example of Field Template Lookup for String Column

Mode=“Insert”

PhoneNumber_Insert.ascx

System.String_Insert.ascx

String_Insert.ascx

Text_Insert.ascx

PhoneNumber_Edit.ascx

System.String_Edit.ascx

String_Edit.ascx

Text_Edit.ascx

PhoneNumber.ascx

System.String.ascx

String.ascx

Text.ascx

Mode=“Edit”

PhoneNumber_Edit.ascx

System.String_Edit.ascx

String_Edit.ascx

Text_Edit.ascx

PhoneNumber.ascx

System.String.ascx

String.ascx

Text.ascx

Mode=“ReadOnly”

PhoneNumber.ascx

System.String.ascx

String.ascx

Text.ascx

Because the HomePhone property has no UIHintAttribute and UIHint property is not specified for DynamicControl or DynamicField in page markup, the search sequence does not include the file names based on the UIHint. However, the HomePhone property does have the DataType specified in the data model using the [DataType(DataType.PhoneNumber)] attribute.

In Insert mode, the FieldTemplateFactory checks to see if PhoneNumber_Insert.ascx, System.String_Insert.ascx, String_Insert.ascx, and Text_Insert.ascx field templates exist before finding the PhoneNumber_Edit.ascx template created earlier in this chapter. If this template didn’t exist, the FieldTemplateFactory would continue checking for System.String_Edit.ascx, String_Edit.ascx, and eventually find the Text_Edit.ascx field template provided by Dynamic Data projects out of the box.

In Edit mode, the FieldTemplateFactory starts with PhoneNumber_Edit.ascx and because it exists, uses it immediately. Likewise, had this field template not been defined, it would continue the search and eventually find the Text_Edit.ascx template provided by Dynamic Data.

In ReadOnly mode, the FieldTemplateFactory starts with PhoneNumber.ascx. Because the read-only version of the phone number field template does not exist, it continues by trying System.String.ascx and String.ascx and finally finds the Text.ascx field template provided by Dynamic Data out of the box.

Table 3.5 shows another example of field template lookup sequence, this time for the UnitsInStock property of the Product entity. This column is of type Int32 and, unlike the HomePhone in the previous example, doesn’t have a DataTypeAttribute applied to it. Instead, this field template takes advantage of the fallback logic Dynamic Data uses for types and modes.

Table 3.5. Example of Field Template Lookup for Integer Column

Mode=“Insert”

System.Int32_Insert.ascx

Int32_Insert.ascx

Integer_Insert.ascx

System.String_Insert.ascx

String_Insert.ascx

Text_Insert.ascx

System.Int32_Edit.ascx

Int32_Edit.ascx

Integer_Edit.ascx

System.String_Edit.ascx

String_Edit.ascx

Text_Edit.ascx

System.Int32.ascx

Int32.ascx

Integer.ascx

System.String.ascx

String.ascx

Text.ascx

Mode=“Edit”

System.Int32_Edit.ascx

Int32_Edit.ascx

Integer_Edit.ascx

System.String_Edit.ascx

String_Edit.ascx

Text_Edit.ascx

System.Int32.ascx

Int32.ascx

Integer.ascx

System.String.ascx

String.ascx

Text.ascx

Mode=“ReadOnly

System.Int32.ascx

Int32.ascx

Integer.ascx

System.String.ascx

String.ascx

Text.ascx

In Insert mode, the FieldTemplateFactory starts with the most specific template name (System.Int32) and mode (Insert). It tries System.Int32_Insert, Int32_Insert, and Integer_Insert before falling back to the next type—String. It continues trying System.String_Insert, String_Insert, and Text_Insert before falling back to the next mode, Edit, and repeating the steps starting with the most specific template name, System.Int32. Eventually, it finds Integer_Edit.ascx, the built-in field template provided by Dynamic Data for integer columns.

The Edit mode lookup sequence for the UnitsInStock column is very similar to that of Insert mode’s. It starts with System.Int32_Edit and finds the built-in Integer_Edit template. The Read-only mode is different, however. Because Dynamic Data doesn’t provide a built-in read-only template for integer columns, the FieldTemplateFactory falls back from Integer to String data type and eventually finds Text.ascx, a read-only template that can display field values of all types.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020