intro 2 asp

Upload: omer-e-javedan

Post on 08-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 intro 2 ASP

    1/34

    Introduction to ASP.NET Dynamic DataDemo Script

    This demo shows how to create an ASP.NET Dynamic Data application that provides

    scaffolding functionality on top of an Entity Data Model. It highlights how to add

    additional metadata and validation to your model that will be automatically reflected in

    your application. Finally, it shows how to extend a Dynamic Data application using page

    templates, field templates, and custom pages.

    Demos:

    The following demos are included in this script:

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    2/34

    2

    Demo Description

    1. Scaffolding This demo shows how to create a Dynamic Dataapplication using an Entity Data Model as itsbacking store. It explains the default structure of

    the project and highlights the provided scaffolding

    functionality.

    2. Model Metadata This demo shows how to add additional metadatato your model and how that metadata is reflected

    automatically in your Dynamic Data application.

    3. Model Validation This demo shows how to add additional validationto your model and how that validation is reflected

    automatically in your Dynamic Data application.

    4. Customization This demo shows how to customize a DynamicData application by modifying the existing page

    and field templates. It also shows how to create

    custom pages for specific entities, as well as new

    field templates.

    Setup and Configuration

    Before you begin you should install the resources required to run this demo. This can be accomplished by running the Setup.bat file located within your

    training kit installation path underneath the Demos\ASP.NET Dynamic Data directory.

    Here is a sample of the expected output:

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    3/34

    3

    Setting up the Visual Studio environment

    1. Open Visual Studio 2008.2. In Server Explorer, add a data connection to the NETSP1LABS database. You will need the connection for later use.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    4/34

    4

    3. After creating the connection, expand it until all tables are shown.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    5/34

    5

    Demo 1 Scaffolding

    Estimated time to complete the demo: [10 minutes]

    Action Script Screenshot

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    6/34

    6

    1. Open up Visual Studio.2. From the menu bar select File -> New ->

    Project.

    3. Underneath the Visual C# node, select theWeb option.

    4. Select the Dynamic Data Entities WebApplication.

    5. Set the Name to IntroDynamicData andclick OK.

    Lets begin by creating a new project. [2][3]

    Notice that we have two options: DynamicData Web Application and Dynamic Data

    Entities Web Application.

    Because a Dynamic Data applicationprovides scaffolding on top of a data

    model, the two options provide you with

    the appropriate templates for basing you

    application on a LINQ To SQL model or

    Entity Data Model.

    Were going to base this demo off an EDM,so lets select that option. [4] [5]

    6. Expand the DynamicData folder inSolution Explorer.

    7. Right-click on the IntroDynamicDataproject and select Add -> New Folder.

    Name the new folder Models.

    8. Right-click on the Models folder and selectAdd -> New Item.

    9. In the Add New Item dialog selectADO.NET Entity Data Model, name it

    AdventureWorks.edmx and click Add.

    10. Select Generate from Database and clickNext.

    11. Select the AdventureWorksLT connectionthat was configured for this demo, name

    the config setting AdventureWorksContext

    and click Next.

    The project that has been created for usincludes a rich set of templates that

    provide the dynamic UI for our application.

    [6]

    Well discuss these templates more indetail later.

    Because this application is very data-centric, the first thing we need to do is

    create a data model that we want to add

    scaffolding around. [7]

    Lets create a basic Entity Data Modelbased on the AdventureWorksLT database.

    [8] [9] [10] [11][12] [13]

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    7/34

    7

    12. Select every table except for ErrorLog andBuildVersion.

    13. Set the EDM namespace toIntroDynamicData.Models and click Finish.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    8/34

    8

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    9/34

    9

    14. Open up the Global.asax file.15. Uncomment the line of code that calls

    RegisterContext on the MetaModel.

    16. Change the type parameter being passedto the RegisterContext method to

    AdventureWorksContext.

    17. Add a using statement for theIntroDynamicData.Models namespace.

    18. Set the ScaffoldAllTables property to true.19. Press F5 to run the solution.

    Now that weve got our data model andour Dynamic Data application the only

    thing left is to connect the two. [14]

    Notice the MetaModel that is beingcreated for us and the comments telling us

    to register our data context with it. [15]

    Our context in this case is theObjectContext that was generated by our

    Entity Data Model, so lets register it with

    our MetaModel. [16] [17]

    Now that weve associated our data modelwith our meta model, we just need to

    enable scaffolding. [18]

    Lets try running this application and seewhat we get. [19]

    20. Click on the Products link.21. Click on the ProductID column twice to

    show the data being sorted using AJAX.

    22. Click the forward arrow to page theproduct data.

    23. Scroll to the right of the page and show offthe ProductCategory, ProductModel, andSalesOrderDetail columns.

    Immediately were displayed with a list oftables that are contained in are underlying

    data model.

    Lets start taking a look at what the rest ofthis application looks like. [20]

    Weve got full CRUD provided to us on topof every entity in our data model.

    In addition weve got full AJAX sorting andpaging. [21] [22]

    Notice that the Dynamic Data applicationcan also infer associations in your data

    model and displays them as links. [23]

    ProductCategory and ProductModel are 1:1

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    10/34

    1

    0

    associations and SalesOrderDetail is a

    1:many association.

    24. Click on the ProductCategory link for thetop record.

    25. Click on the Edit link.26. Change the Category Name to Tour Bikes

    and click the Update link.

    27. Click the Insert New Item link.28. Fill out the form with test data and click

    the Insert link.

    29. Find the category you added and click theDelete link.

    Lets follow one of the associations. [24] Notice that it successfully displayed to us

    the details of the category associated with

    the product.

    Lets try editing this category. [25] [26] Now lets add a new category. [27] [28] Because we dont want this test category

    cluttering up our database lets delete it.

    [29]

    Without writing an data access code wevegot an fully-functional web application that

    provides CRUD, sorting, paging, and

    associations.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    11/34

    1

    1

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    12/34

    1

    2

    30. Expand the PageTemplates folder withinthe DynamicData folder.

    You may be wondering whether or notDynamic Data is using code generation, but

    fortunately the answer to that is no.

    Dynamic Data uses a small set of commandtemplates and uses them to dynamically

    render the pages for each entity in your

    model. [30]

    Page templates are used to render everypage in a Dynamic Data application. Notice

    that there are templates for every state of

    a record, which is what provides the full

    CRUD behavior out-of-the-box.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    13/34

    1

    3

    31. Expand the FieldTemplates folder withinthe DynamicData folder.

    In addition to page level templates,Dynamic Data leverages field level

    templates to handler rendering the

    individual fields on every page. [31]

    Notice that there are a whole slew of fieldtemplates provided by default, and are

    largely mapped to field by their data type.

    There are however some field templatesthat dont map to CLR types such as

    Children and ForeignKey. As well see later,

    you can add metadata to your models

    fields that associate it with an arbitrary

    field template regardless of the actual

    underlying type. Finally, notice that field templates allow

    multiple versions for different states, such

    as Edit and Insert.

    Demo 2 Model Metadata

    Estimated time to complete the demo: [10 minutes]

    Action Script Screenshot

    1. Open the IntroDynamicData solution inthe Begin folder.

    While the default scaffolding that we wereprovided with was fully-functioning, there

    were definitely plenty of areas where we

    could have benefited from adding some

    additional metadata.

    Ideally wed like to encapsulate as much ofthe metadata for our model within our

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    14/34

    1

    4

    actual model, but sometimes that isnt

    possible, and you need to enhance your

    underlying model.

    There are two types of metadata you canadd to your model: entity-level and

    property-level.

    To apply entity-level metadata to yourmodel you need to apply the respective

    metadata attribute to the desired entity

    class in your model.

    When working with a LINQ To SQL model orEntity Data Model, because the object

    models are generated for you, you really

    dont want to modify the code manually.Luckily though, the generated object model

    classes are partial, which means we can

    apply the metadata to our own partial

    classes.

    2. Right-click on the Models folder and selectAdd -> New Item.

    3. Select the Class template, name the fileProductModelProductDescription.cs, and

    click Add.

    4. Add the partial modifier to the createdclass.

    5. Add a using statement for theSystem.ComponentModel.DataAnnotation

    s namespace.

    6. Add the ScaffoldTable attribute to theclass, setting its constructor parameter to

    The most basic metadata we can add to ourmodel is that of determining whether or

    not an entity is available for scaffolding.

    When we first registered our context wespecified to scaffold all tables, but we can

    override that value by explicitly adding

    metadata to an entity that says not to

    scaffold it.

    The ProductModelProductDescriptionentity is pretty pointless in our application,

    so lets add metadata to do to have it not

    be scaffolded.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    15/34

    1

    5

    false.

    7. Press F5 to run the application. To do this we need to add a new partial

    class that we can associate our metadata

    with. [2] [3] [4]

    Now that we have our partial class we canadd the metadata directly to it. [5] [6]

    A point of interest is that the metadataattributes are located in the

    System.ComponentModel.DataAnnoations

    namespace which means they arent

    Dynamic Data specific.

    Weve now told the Dynamic Data runtimethat we no longer wish to have the

    ProductModelProductDescription entity

    scaffolded. Lets run the application andsee if it worked. [7]

    8. Close the browser to stop debugging.9. Right-click on the Models folder and select

    Add -> New Item.

    10. Select the Class template, name the fileAddress.cs, and click Add.

    11. Add the partial modifier to the createdclass.

    12. Add a using statement for theSystem.ComponentModel.DataAnnotation

    s namespace.

    13. Add a nested private class within theAddress class and call it AddressMetadata.

    14. Add the following attribute to the Addressclass:

    In addition to being able to override entity-level scaffolding you can also turn off

    scaffolding for individual properties. [8]

    Lets turn out attention towards to theAddress entity and add some metadata to

    it. [9] [10] [11] [12]

    Adding entity-level metadata is as easy asapplying an attribute to a partial class, but

    because C# doesnt support partial

    properties, we dont have the same luxury

    available to us with property-level

    metadata.

    We can however create a class that willhold out property-level metadata and

    associate it with our partial class. [13]

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    16/34

    1

    6

    [MetadataType(typeof(AddressMetadata))]

    15. Add the following property to theAddressMetadata class:

    public object ModifiedDate { get; set; }

    16. Add the following attribute to theModifiedDate property:

    [ScaffoldColumn(false)]

    17. Press F5 to run the application.18. Click on the Address link.

    We can then instruct the Dynamic Dataruntime that this new class will hold the

    property-level metadata for an entity by

    using the MetadataType attribute. [14]

    Now that we have our metadata class, wecan add properties to it that map to

    properties on our model class.

    The Address entity has a property calledModifiedDate that I dont want scaffolded,

    so lets add a property for it to our

    metadata class. [15]

    Note that the return type of the propertydoesnt matter, only the name.

    Finally, lets tell the runtime that we dontwant this property scaffolded. [16]

    Now when we run the app we shouldntsee the ModifiedDate column anymore.

    [17] [18]

    19. Close the browser to stop debugging.20. Open up the Address.cs file within the

    Models folder.

    21. Add a using statement for theSystem.ComponentModel namespace.

    22. Add the following attribute to the Addressclass:

    [DisplayName(Addresses)]

    Notice that the display name for theAddress entity is Address and wed like it

    to be Addresses in the context of our

    Dynamic Data application. [19] [20] We can modify the display name of an

    entity by applying the DisplayName

    attribute to it. [21] [22]

    Now when we run our application, theentity will show up using the new display

    name.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    17/34

    1

    7

    23. Press F5 to run the application.

    24. Click to Back to Home Page link.25. Click the SalesOrderHeader link.26. Expand the Addresses drop down list.27. Close the browser to stop debugging.28. Open up the Address.cs file.29. Add the following attribute to the Address

    class:

    [DisplayColumn("PostalCode",

    "PostalCode")]

    30. Press F5 to run the application.31. Click on the SalesOrderHeader link.

    When Dynamic Data finds foreignkeys/associations between entities it

    creates links and filters between them.

    It tries its best to determine which columnfor an entity is best suited to act as its

    display column, but it cant possibly always

    know what you might want.

    For instance, lets take a look at theSalesOrderHeader entity. [24] [25] Notice that it has an association with the

    Address entity and as such, Dynamic Data is

    rendering a drop down list to filter the

    data. [26]

    It has assumed that we want the Address1

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    18/34

    1

    8

    32. Exapnd the Addresses drop down list. property to act as the display column andthat is what we see in the list, but what if

    we wanted to display just address zip

    code? [27] [28]

    Using metadata, we can instruct theruntime which property to use as its

    display. [29]

    Now when we run the application, weshould see address zip codes in the filter

    lists instead of the street address. [30] [31]

    [32]

    33. Close the browser to stop debugging.34. Open up the Address.cs file.35. Add the following property to the

    AddressMetadata class:

    public object AddressLine2 { get; set;

    }

    36. Add the following attribute to theAddressLine2 property:

    [DisplayFormat(NullDisplayText="N/A")]

    37. Press F5 to run the application.38. Click on the Addresses link.

    The final metadata attribute allows us tocontrol how a propertys value is

    formatted.

    This includes being able to specify a formatstring as well as determine what text

    should be displayed when the property is

    null. [33] [34]

    With our Address entity, the majority ofrecords in our model dont contain any

    value for the AddressLine2 property, and as

    such it would be nice to display N/A

    when no value is present. [35] [36]

    Now when we run the application, alladdresses with no address line 2 should

    display the text N/A. [37] [38]

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    19/34

    1

    9

    Demo 3 Model Validation

    Estimated time to complete the demo: [15 minutes]

    Action Script Screenshot

    1. Open the IntroDataServices solution in theBegin folder.

    2. Open the Address.cs file within theModels folder.

    3. Add the following attribute to theAddressLine2 property:

    [Required(ErrorMessage="We're sorry but

    we only allow addresses with two

    lines.")]

    4. Press F5 to run the application.5. Click on the Addresses link.6. Click on the Insert new item link.

    Model validation enables you to limit theallowed input to properties from within the

    scaffolded application.

    The simplest validation attribute is theRequiredAttribute which lets you specify

    that a field is required.

    Dynamic Data already sets up properties asrequired that were marked as required inthe data model, but sometimes you want

    to require fields at the UI level that werent

    necessarily required in the data layer. [2]

    For example, the AddressLine2 property ofthe Address entity wasnt required, but

    imagine that we later decide that we want

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    20/34

    2

    0

    7. Click the Insert link.8. Close the browser to stop debugging.

    it to be.

    We can mark the property as required aswell as optionally specify our own error

    message to display when a user tries tosubmit a form without providing a value.

    [3]

    An import point to mention is that everyvalidation attribute that well be

    considering in this demo inherits from the

    ValidationAttribute base class which

    provides the ErrorMessage property as well

    as properties for setting a validation error

    message from resource files.

    Lets try to go add a new address withoutgiving it an AddressLine2. [4] [5] [6] [7]

    The runtime now requires theAddressLine2 property to be set and it

    displays our provided error message. [8]

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    21/34

    2

    1

    9. Add the following property to theAddressMetada class:

    public object AddressID { get; set; }

    10. Add the following attribute to theAddressID property:

    [Range(1, 1000, ErrorMessage="We've

    reached the limit for addresses.")]

    11. Press F5 to run the application.12. Click the Addresses link13. Click the Insert new item link.14. Type 1001 in the AddressID field.15. Click in the Insert link.16. Close the browser to stop debugging.

    Right now the AddressID property isrequired and because it is an integer in the

    data model the Dynamic Data runtime will

    also apply a validator that ensures onlyinteger data can be applied.

    But what if we also wanted to constrain thevalue to within a specific range of values?

    [9] [10]

    Now if we try to create a new address withan ID higher than 1,000 we should get an

    error. [11] [12] [13] [14] [15]

    Weve not successfully constrained the IDproperty. [15] [16]

    17. Add the following attribute to theAddressLine2 property:

    [StringLength(10, ErrorMessage="Too

    much data.")]

    18. Press F5 to run the application.19. Click the Addresses link20. Click the Insert new item link.21. Try typing more than ten characters into

    the AddressLine2 field.

    22. Close the browser to stop debugging.

    In addition to specifying a range fornumeric values, we might want to limit the

    length of certain string properties.

    Dynamic Data will translate a length limitset in the data model into a length

    validator, but sometimes you might want

    to override it or add a length limit to the UI

    that didnt exist in the model.

    While were requiring address 2 now, letslimit it to only ten characters. [17]

    We now shouldnt be allowed to input anaddress 2 line that is more than ten

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    22/34

    2

    2

    characters. [17] [18] [19] [20] [21]

    Notice that what the string lengthvalidation attribute actually did was

    instruct the runtime to render the addressline 2 textbox as only physically allowing

    ten characters. There isnt a validator

    placed on the field, but rather a hard limit.

    [22]

    23. Add the following attribute to theAddressLine2 property:

    [RegularExpression(@"Apt. #\d{1,4}",

    ErrorMessage="Only apartments numbers

    please.")]

    24. Press F5 to run the application.25. Click the Addresses link26. Click the Insert new item link.27. Type Apt 430 in the AddressLine2 field.28. Click the Insert link.

    The final validation attribute allows you toplace a regular expression constrain on a

    property.

    Now that weve required the address line 2property and constrained it to exactly ten

    characters, lets finally enforce a formatthat requires an apartment number. [23]

    Lets try to create an address without avalid apartment number. [24] [25] [26] [27]

    [28]

    Now lets specify a valid apartment numberand see if it accepts it. [29] [30]

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    23/34

    2

    3

    29. Type Apt. #430 in the AddressLine2field.

    30. Click the Insert link.31. Close the browser to stop debugging.

    And it accepts the valid apartment number.[31]

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    24/34

    2

    4

    While the four aforementioned validationattributes are great, they obviously cant

    cover every possible scenario.

    The final type of validation that DynamicData supports is model-level validation

    which enables you to place business logic

    within your entity classes and throw an

    exception when invalid data is provided.

    Dynamic Data will catch the exception anddisplay it as a validation error.

    Because were using an EDM as our datamodel, all of our entity classes have partial

    methods that are fired when a property is

    changed, which allows us to hook into

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    25/34

    2

    5

    them to provide validation.

    32. Create a partial method for the Addressclass OnPostalCodeChanging method.

    33. Add the following code within theOnPostalCodeChanging method:

    if (value == "98121" && StateProvince

    != "WA")

    {

    throw new

    ValidationException("98121 is a

    Washingston zip code.");

    }

    34. Press F5 to run the application.35. Click the Addresses link.36. Click the Insert new item link.37. Fill out the form as such:

    a. AddressID -> 100b. AddressLine1 -> Testc. AddressLine2 -> Apt. #430d. City -> Tampae. StateProvince -> FLf. CountryRegion -> USAg. PostalCode -> 98121

    38. Click the Insert link.

    Imagine that we want to add validationthat ensures that if the address zip code is

    98121 then the state must equal WA.

    In a real-world scenario youd obviouslywant to perform more sophisticated

    zipcode-to-state matching, but this will

    suffice for example. [32] [33]

    Notice the use of the ValidationException.This is a custom exception that is part of

    the new DataAnnotations namespace. You

    should always use this exception type when

    throwing validation errors.

    Model-level validation only fires when theform is actually submitted, which means

    we wont get client-side validation like we

    have been getting.

    Lets try to create a new address. [34] [35][36]

    Because our new validation will only triggerupon postback, we need to fill out a valid

    form, keeping in mind all of our other

    validation rules. [37]

    Were now trying to enter an address inFlorida but with a Washington zipcode,

    which shouldnt be allowed. [38]

    Notice that our custom business logic wastriggered and displayed as expected.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    26/34

    2

    6

    Demo 4 Customization

    Estimated time to complete the demo: [15 minutes]

    Action Script Screenshot

    1. Open the IntroDataServices solution in theBegin folder.

    2. Open up the List.aspx file within thePageTemplate folder that is within the

    DynamicData folder.

    3. Append (Template) to the contentwithin the templates h2 element.

    4. Press F5 to run the application.5. Click on the Addresses link.6. Click the Back to home page link.7. Click the Customer link.8. Close the browser to stop debugging.

    Because Dynamic Data uses templating andnot code-generation we can easily made

    changes to templates at either the page or

    field-level and have it take effect

    throughout the entire application.

    This type of encapsulation of UI makesDynamic Data a very compelling

    technology.

    Lets make a minor change to one of thepage templates and ensure that it indeed

    does cascade throughout the application.

    [2]

    The List template is used to display the listof data for each entity. Lets just add some

    custom text within the pages h2 element.

    [3]

    If we run the application now, we shouldsee the text (Template) appear on the list

    page for every entity. [4] [5]

    Alright so we see the template change foraddresses, lets just ensure that the change

    took effect for all entities. [6] [7]

    Page templates are great because they giveyou a nice UI out of the box but allow you

    to customize them as much as you need

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    27/34

    2

    7

    along the way, and only have to do it in one

    place.

    I only showed you the List template, butyou can just as easily customize thetemplates for inserting, updating, and

    viewing an entity record. [8]

    Its important to note that Dynamic Dataisnt using any magic to accomplish its

    scaffolding. If you look in the contents of

    the page templates, its standard ASP.NET

    code using familiar controls such as

    GridView and DetailsView, etc.

    There are however a few custom controlsthat Dynamic Data introduces to the

    ASP.NET stack that will be discussed in the

    deep dive session.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    28/34

    2

    8

    9. Right-click on the CustomPages folderwithin the DynamicData and select Add ->

    New Folder. Name the folder Address.

    10. Copy the List.aspx file from thePageTemplates folder and paste it within

    the Address folder within the

    CustomPages folder.

    11. Delete the copied List.aspx files two code-behind folders.

    12. Change the text (Template) within thepages h2 element to instead be

    (Custom).

    13. Press F5 to run the application.14. Click on the Addresses link.15. Click on the Back to home page link.16. Click on the Customer link.17. Close the browser to stop debugging.

    While being able to make customizations tothe page templates is great, what if you

    wanted to customize a template for a

    specific entity and not the entireapplication?

    This is where custom pages come in. Theyallow you to create static templates that

    will only be used by the entities you want.

    If you look in the DynamicData folder younotice a CustomPages folder. This is where

    you can place custom pages.

    Lets go ahead and create a custom pagefor the Address entitys list view. [9]

    The way custom pages work by default isthat the runtime will look for a folder

    within the CustomPages folder named after

    the entity, so in this case we create a

    subfolder called Address.

    Because the templates are just standardASPX pages we could create our own

    template from scratch, but for the sake of

    example it will be easier for us to extend

    one of the existing templates. [10]

    Were only going to make UI level changesand therefore dont need any code-behind.

    [11]

    Lets just make a minor change to theHTML. [12]

    So now if we run this, the address entityshould display the text Custom on its list,

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    29/34

    2

    9

    while every other entity should still display

    Template. [13] [14]

    Lets quickly ensure that this only affectsthe address entity. [15] [16]

    So our custom page only affects theaddress entity, and we could continue to

    customize it further, but this example gives

    us an idea of what is possible.

    I could also create custom pages for theother views such as insert, update, and

    details. [17]

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    30/34

    3

    0

    18. Open up the DateTime.ascx field withinthe FieldTemplates folder that is within

    the DynamicData folder.

    19. Change the contents of the Literals Textproperty to:

    ((DateTime)FieldValue).ToShortDateStrin

    g()

    20. Press F5 to run the application.21. Click on the SalesOrderHeader link.22. Close the browser to stop debugging.

    The final type of customization for DynamicData scaffolding lies in field templates. As

    we discussed before, the runtime renders

    templates for every field based on its data

    type.

    Because the runtime using the samecommon set of templates to display fieldsthroughout the entire application, we can

    make changes to the existing templates

    and have those changes cascade to every

    entity.

    By default, all date/time fields aredisplayed with both the date and time

    portions displayed, but in our application

    we only want to show the date.

    We can easily achieve this in one place byjust modifying the date/time field

    template. [18]

    Notice that this template simply contains aLiteral control whose text is being set to

    FieldValueString. This is a property that is

    provided to the control by the Dynamic

    Data runtime.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    31/34

    3

    1

    This property comes from the fact that thefield templates dont inherit directly from

    UserControl but rather

    FieldTemplateUserControl.

    Lets modify the Text property to includethe formatting that we want. [19]

    By making that small change, everydate/time field should now be rendered

    with only its date portion. [20] [21]

    Notice that the OrderDate, DueDate, andShipDate fields have all been updated,

    because they all use the date/time

    template that we just updated.

    In addition to this, we could modify theway that every other field templates looks,

    as well as how they are rendered in edit

    and insert mode. [22]

    Its pretty clear that Dynamic Dataapplications are extremely customizable.

    In addition to modifying the provided fieldtemplates, you can also create your own

    field templates.

    Because field templates are largely mappedto fields based on the underlying modeltype, you may be wondering what new

    templates we would want to create.

    The important thing to keep in mind here isthe data type in the context of a Dynamic

    Data application allows a richer semantic

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    32/34

    3

    2

    than a data model.

    For instance, even though an ID might bestored in your model as an integer, you

    might want to have a conceptual ID datatype in your application that has its own

    template, because you dont want IDs

    treated simply as numbers, but as richer

    data with meaning, and their own custom

    UI.

    In fact, lets create that exact scenario.23. Copy the Text.ascx file within the

    FieldTemplates folder than is within the

    DynamicData folder.

    24. Paste the file within the FieldTemplatesfolder.

    25. Rename the file to ID.ascx.26. Delete the ID.ascx files two code-behind

    files.

    27. Open the ID.ascx file.28. Type a # before the Literal control.

    To create a new field template you simplyhave to add a new user control to the

    FieldTemplates folder, and the user control

    has to inherit fromFieldTemplateUserControl.

    While you could create your own fromscratch, since our phone number template

    will be based on the text template, lets just

    go ahead and copy that to start with. [23]

    [24] [25]

    We dont need any code-behind, so letsdelete those two files. [26]

    Alright, so lets take a look at this template.[27]

    Once again, simply a Literal that rendersthe passed in field value.

    To keep it simple, lets say that we justwant to format all ID types by placing a

    pound sign in front of the actual number.

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    33/34

    3

    3

    [28]

    You could obviously do as much as youwanted with this, but well keep it simply

    for demonstration. Since this is just a usercontrol, your existing ASP.NET knowledge

    allows your imagination to run wild with

    possibilities.

    29. Open up the Address.cs file within theModels folder.

    30. Add the following attribute to theAddressID property:

    [DataType("ID")]

    31. Press F5 to run the application.32. Click the Addresses link.

    Now that we have our conceptual ID fieldtemplate, we have to instruct the runtime

    which entity properties are considered IDs.

    In our case, we want to specify the Addressentitys AddressID property is an ID data

    type so that it will leverage our new

    template. [29] [30]

    Now when the runtime is rendering theAddressID field it will look for a field

    template called ID.ascx, which we just

    created, and use that to render its UI.

    Lets run the application and see if our newtemplate works. [31] [32]

    AddressID is now conceptually consideredan ID type and is leveraging our new field

    template.

    Alternatively, instead of using the DataTypeattribute, we could have applied the UIHint

    attribute to the property instead.

    In version one of Dynamic Data thedifference between the two attributes

    comes down to semantics. Whether or not

    you want to consider a property as being of

    Create PDF files without this message by purchasing novaPDF printer (http://www.novapdf.com)

    http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/http://www.novapdf.com/
  • 8/7/2019 intro 2 ASP

    34/34

    3

    4

    a specific type or rather using a specific

    template. Both attributes achieve the same

    result.