DPS907 notes – Tue Sep 24

Using an existing project as a ‘template’ for a new project. Data annotations for your app domain model classes. Code First Migrations to handle updates to your app domain data model classes, yet retain existing data. Handling more internet media types.


Creating a project template, by copying-then-renaming a project

You have learned that you are writing lots of code for your web service. As the complexity increases in the coming weeks, you will be interested in using a project as a template for your future work. This will lower the effort needed to create a new web service, and improve its quality.

Visual Studio 2012 does not have an easy copy/rename feature to enable you to use a project as a template. Therefore, for now, you can follow this procedure to make a copy of an existing project. First, in the file system, locate the top-level folder of a project that you want to use as a template. Then:

1. Copy the top-level project folder, and rename the copy as you wish. Then, open the new folder.

2. Inside that folder, change the name of the folder that holds the project files.

3. Change the ‘sln’ (Visual Studio Solution) file name.

4. Now, edit the ‘sln’ file using Notepad, and edit/update only the name of the folder that holds the project files (leave the other old names there for now). Save and close.

5. Open (double-click) the ‘sln’ in Visual Studio, and make sure it still builds and runs (it should).

6. Open a class (e.g. in the Models folder). Select the project’s global namespace name, right-click, and choose Refactor > Rename to a new name. Check-mark all boxes, and proceed (OK, then Apply).

It will also tell you that the project file name will be updated, choose ‘yes’.

7. In Solution Explorer, change (rename) the visible name of the project.

8. Open the project’s properties (Alt+Enter, or right-click Properties), change the assembly name, then save and close the project’s properties.

9. In Solution Explorer, with the project still selected/highlighted, press Ctrl+H to find-and-replace, search all files in project, replace the old name with the new name.

10. In Web.config connection strings, change the database name, if you want to.

Delete the existing contents of the bin and obj folders. And maybe App_Data, depending upon the situation.
Then Build > Clean, and then Build > Rebuild.


Data annotations, revisited

Last week, you learned how to add data annotations to view model classes. They help with the task of validating input data.

Today, you will learn to add them to app domain data model classes.

Your professor recommends that you make a copy of an existing project, using the technique described above.

Then, you can work along with these notes to add data annotations to your app domain model classes.

Before you do that, comment out the store initializer statement in your Global.asax class. That will prevent your existing data from being destroyed when you make the changes that are described below.

The sep24migrations code example implements all of today’s topics, except for the last topic on image handling.

In your app domain model classes source code file, add this namespace:


Useful data annotations include:

[Required] – implemented as ‘not null’ in the database

[StringLength(n)] – implemented as a ‘varchar’ value in the database

You can comma-separate multiple data annotations.

Do you need a ‘default value’ for a property?

A data annotation will not help.

Instead, simply create a class constructor, and set the property’s default value there.

Value types (e.g. int, double) CANNOT use the [Required] attribute.

Others you may use occasionally…

[NotMapped] – for properties that are dynamically-generated

[TimeStamp] – for a byte array (byte[]) property named ‘timestamp’; it is also marked ‘not null’


Entity Framework Code First Migrations

If you added data annotations to an existing project, and then attempted to use Fiddler to make requests, you probably saw an error message. It told you that the database design has changed, and recommends that you use Code First Migrations.

That’s what you’ll learn now.

Migrations enable you to KEEP YOUR EXISTING DATA when you make minor changes to your app domain model classes.

It’s a developer technology, but it obviously helps the users, because you can make many changes to your app domain model classes, and your web service keeps running, with its existing data.

Before you enable and configure Migrations, you must remove the statement in the WebApiApplication class (in Global.asax.cs) that starts/initializes the data store initializer. Why? Because we now want to keep your existing data, and have Migrations manage that process. So, go ahead and remove (or comment out) the statement that starts/initializes the data store initializer.

Configuring Migrations requires two simple tasks:

  1. Enable migrations
  2. After a change (or set of changes), add a ‘migration’ definition, and update the data store.

The first task is to ‘enable’ Migrations. In Visual Studio 2012, open the TOOLS menu. Choose ‘Library Package Manager’, then ‘Package Manager Console’. That will open a command-line window/panel.

Type the following command. It’s a once-per-project command. After you do this, you will not have to do it again for the current project:


This command configures the base or start state of your the app domain data model, and its persistent store implementation.

If you have existing data, and have made a change to your app domain data model, then enable-migrations will also add a ‘migration’ definition automatically.

If it does add the migration, then it immediately executes the update-database command, so you can skip the second task below. Read the package manager console messages carefully – it will tell you the status.

Then, after you have made a change to your app domain model classes, you do the second task, by executing the following two commands in the Package Manager Console:

add-migration DescriptiveNameForTheMigrationDefinition 


In a new (or almost new) project, the descriptive name for your first migration definition can be “Initial” or something similar.

If you anticipate performing many changes, then you can do the add-migration and update-database in a granular way. Or, you could just do all your edits, and run these commands once.


Resources and references 

Introduction and overview – Code First Migrations

Migrations commands – EF Migrations Command Reference


Activating the “help” page feature

Soon, you will learn how to include state information in the responses from your web service.

Until then, you may be interested in the ASP.NET Web API ‘Help’ page feature. After you configure this feature, users can use a browser to view what- and how-to information about your web service.

In Solution Explorer, open this file:

Areas > HelpPage > App_Start > HelpPageConfig.cs

Un-comment the first statement, “config.SetDocumentationProvider…” .

From that statement, copy part of the path, “App_Data/XmlDocument.xml”, because we’ll need that text/string.

Next, select the project, and open its Properties page (Alt+Enter).

Select its Build tab, and check-mark “XML documentation file”, and enter the path from above; save and close the Properties page.

Finally, add XML documentation comments to your controller methods.

Build, then run.

In a browser, append ‘/help’ to the URI, and you’ll see your comments.


Handling new internet media types

You know that your web service will handle JSON and XML.

A ‘media type formatter’ is the name of the component that actually does the work. This component is conceptually located between the requestor and the controller.

Read this document for more information.

Study the following diagram (click to open a full-size version in a new tab/window):



The sep24images code example enables us to learn about writing our own media type formatter.

We’ll use a simple car/vehicle data entity, and configure its entity class with properties that hold a photo of the car/vehicle, and the internet media type of the photo (typically “image/png”).

Therefore, this design will work if an entity object has a single photo/image property. And conceptually, if it makes sense for that single photo/image to represent the object. Examples include personal profile avatars, or ‘favicon‘ images for a web site.

This code example is simple. A future code example will show you how to work with image collection properties, and apps that work with lots of images.

General design approach

Here’s the general approach to handling images.

1. Configure the app domain model class with properties to hold the photo. You need a byte array (byte[]) for the photo, and a string for the internet media type.

2. Configure a view model class with these properties. Typically, you will add attributes to make the JSON and XML serializers ignore the photo-related properties.

3. Add the appropriate repository methods (e.g. update an object with a new photo).

4. Configure the appropriate controller methods. As you will learn, you will have to pay attention to request and response headers.


In our next session, we will discuss some highlights from the code example.









  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: