How To…Verify Email Address: Entity Framework Code First Migrations

0 Flares Twitter 0 Facebook 0 StumbleUpon 0 Google+ 0 LinkedIn 0 0 Flares ×


A common feature of web apps user registration is to to make users verify email address, normally by clicking a link sent to that email address. Accomplishing this with ASP.NET MVC on Windows Azure is pretty straight forward, but does require a number of steps:

  1. Amend the model to allow for storing of emails and verification information.
  2. Apply these model changes to the database.
  3. Create a SendGrid account on azure and configure it within your web app.
  4. Collect the additional information on user sign-up
  5. Amend the registration process to send relevant emails and prevent automatic sign-in
  6. Change the login process to ensure the user is verified before logging in
  7. Handle the verification link for the specified user

Once you’ve competed these steps you should be 90% of the way to having all new user registration requiring email verification.

Over the next few weeks I’ll be covering each of these steps as part of my ASP.NET Web Apps on Azure series.

Series: ASP.NET Web Apps on Windows Azure

In this article we’ll be amending the entity framework code-first model and applying the changes using code-first migrations.

This tutorial requires that you have the free NuGet Package Manager Visual Studio installed:

Enabling code first migrations

To do this we’re going take the MyFirstWebApp base solution we’ve created in the previous tutorials and build on that.

The MyFirstWebApp base solution is simply an ASP.NET MVC template web app that has been deployed to Windows Azure and connected SQL Azure

Before we start making any code changes its important to acknowledge one thing – we have already have a database initialized on SQL Azure and probably in LocalDb too. This means if we update our model we need a controlled way to roll these changes out to our databases…enter code first migrations.

A little about code first migrations

Code first migrations allow us to specify changes in database structure from one version to the next. These migration scripts are created as a specific type of C# file within our projects that describe changes in our model, and how they are to be applied to the database. In a production environment these migrations would allow us prevent data loss, and migrate data from one structure to another in a consistent and repeatable way.

A big benefit of the code first migrations is that these migration scripts are simple to source control. This means we can effectively source control the entire life of our database, and the path it takes. Whats great about this is that we kind basically point the tool at any version of our database, and tell it to bring it up to date – an it will do so in a controlled and consistent way.

Getting started with code first migrations

The first thing we need to do to get started with code first migrations is enable them in your project. This is done by executing the following command in the NuGet package manager console:

Visual Studio Quick Tip: A quick way to get to the package manager console in VS2103 is to press Ctrl+Q to enable the Quick Launch box and start typing ‘package manager’ (you wont have to type the whol thing) – you can quickly arrow down and press enter to have the package manager console opened and your cursor focused in it.

On doing this you will have to wait a minute or so while migrations are enabled. You should now find a new folder in the root of your project called “Migrations”, in which are 2 files:

  • Configuration.cs – This file is used to do top level migration configurations such as setting timeouts. It also allows for creating seed data.
  • #####_InitialCreate – This file represents the script that will create the initial version of your database according to the state of your model as it is now. Subsequent scripts will move the database from this state to another state – much like a daisy chain.

Your project structure will look something like this:

Project Structure After Enable Migrations

Now we’ve enabled code first migrations we can make some changes to our model, and generate the required migration scripts to update our database.

Amending the model

Now we need to add some fields to the model that represents our user object – we need fields to capture:

  • Email address: obviously!
  • A verification token: A unique token that will be used to verify the link sent in the email.
  • An IsEmailVerified flag: A flag that identifies whether a use has been verified or not.

The model in our project is an Entity Framework Code First model, whereby classes are defined with a data context, and a database is generated off the back of them. For now we already have the data context, its called “ApplicationDbContext” and is located in the “Models” folder:

Location Of Db Context

The code in this class should look something like this:

So first off we just want to add some properties to our model to support the additional data we mentioned earlier. To do this we’ll add 3 fields to the ApplicationUser class:

  • EmailAddress: A simple string field with a data type of email.
  • EmailVerficationToken: A guid field (I’ve chosen a guid as they’re easy to generate and are generally going to be unique).
  • IsEmailVerfied: A boolean field that represents whether the users email has been verified.

After adding these fields your ApplicationUser class your file should look something like this:

At this point I’m going to separate the ApplicationUser class into its own file – this is mostly for neatness, but will mkae things easier to manage and manipulate in the future.

ReSharper Quick Tip: to move a class to its own file simple put your cursor onto the class name, press Alt+Enter and select “Move to another file to match the file name”.

Once you’ve done this your project structure should look more like this:

Project Structure After File Seperated

Applying the changes to the database

At this stage if you tried to run the app and register a new user you’d get an exception get an error reading something like this:

This error is explaining that the model has changed and is out of line with the database, and as such you cannot proceed. To rectify this you need to create a migration script for the changes you have made, and apply that migration script to the database(s).

Creating the migration script

To create the migration script open the package manager console again and add the following command:

This command will create the migration script to take you from the initial create position, and move you to the models current position. The name parameter instructs entity framework to call the script “Migration1” (This name should be more meaningful, and perhaps give some indication of version numbers).

After completing this command a file will be created inside the “Migrations” folder called ####_Migration1. If you open this file it should look like this:

This is a set of instructions telling entity framework how to upgrade (Up) an downgrade (down) the database. as you can see in the upgrade it is adding the relevant columns, and soing the reverse in the downgrade. At this stage your migrations folder should look like this:

Project Structure After Add Migration

Applying the migrations scripts

At this stage you are still not ready to run and deploy your app! you’ve enabled migrations, modified your model and created the migration script – you just need to apply that script.

To do this just open up the package manager console and enter the following command;

This creates the required sql scripts and applies them to the target database – your scenario probably being a LocalDb file.

You will also need to apply these changes to your sql azure instance before you deploy, so to complete this just switch your configuration to “Release” (image below), and run the same command.

Visual Studio Change Configuration

Wrapping up

At this point you should have all of your database changes applied to your databases in a controlled and version friendly way. In the next article(s) we’ll look at getting up and running with SendGrid and amending the registration process to allow for collecting the additional data.

Let me know if there’s anything you’d like to go into more detail about, or any alternate approaches your taking to doing this kind of thing.

The Essential App Marketing Kit
Subscribe To My Newsletter To Get an Entire Chapter From The Book for FREE
Never display this again
0 Flares Twitter 0 Facebook 0 StumbleUpon 0 Google+ 0 LinkedIn 0 0 Flares ×