Azure, Technical

Entity Framework Code First Deployment of Azure AD Sample

If you’re interested in building applications using Azure AD (and really, why would you *not*?), the best code repository to be aware of is https://github.com/AzureADSamples. TONS of samples with documentation showing many different scenarios. This post takes a look at one of the samples in a bit more detail, specifically in the area of deploying the sample to Azure and implementing Code First deployment/migrations. Using EF and Code First can be a bit of a religious debate which I will avoid in this post. The sample uses EF and getting Code First to work is only a few extra steps.

The sample I’m working with here is the WebApp-MultiTenant-OpenIDConnect-DotNet sample. Click the link to get the sample code and read the documentation on how to run the sample. Get everything up and running in Azure AD against a local deployment of the sample (covered in the GitHub documentation for the project), then come back here when you’re ready to get Code First set up and deploy to Azure.

Implement Code First

If you’re not familiar with Code First take some time and read through the documentation on the asp.net website, specifically this walkthrough which shows how to get it set up in your project as well as deployed. As you’ll see, I’m really not doing anything fancy here beyond what you see in the asp.net site. Actually, this is a bit more simplified since we’re not doing any seeding.

  1. Add a connectionString entry to the web.config pointing to your local database
    In my case, I’m using ProjectsV12 but you could easily user MSSQLLocalDB, v11.0 or full SQL depending on your local dev machine setup:

    (If you previously ran the sample locally you already have a local database named TodoListWebAppContext. Either delete it or rename it. You could also update the project to use a different name. This isn’t necessary, but it helps demonstrate the Code First deployment later on in this post.)

  2. Remove existing initializer

    Because we’re using Code First to build our database, we don’t need the TodoListWebAppInitializer initializer that is currently called in Global.asax.cs used to create the database. Open up that file and comment out line 19:

  3. Enable migrations
    Now we need to run a few commands in the Package Manager Console. If it’s not already open, click Tools -> NuGet Package Manager -> Package Manager Console. Once open, type “enable-migrations –contexttypename TodoListWebAppContext” and hit enter:

    You’ll notice a new folder called “Migrations” was added to the project along with a new Configuration.cs file. Just leave those as-is.

  4. Add a migration
    Now we need to add our first migration, which is the initial creation of the database in this case since I haven’t deployed the app locally yet. In the Package Manager Console, type “add-migration InitialCreate” (InitialCreate is just a label used for the migration that you can change to identify the specific migration) and hit enter:

    Now you’ll see a few more files added to that new Migrations folder. If you poke through them, you’ll see they define the database changes to apply and the class inherits from the DbMigration EF migration class. I won’t go through them here to define what they do or how they work but it’s worth the time to understand those concepts if you don’t already have that down (look at the asp.net site linked earlier.)

  5. Update the database

    Finally, we run update-database to actually let EF create the database based on our InitialCreate migration definition. In the Package Manager Console, type “update-database” and hit enter:

    When that’s finished, you now have a local database created for you based on the definition in the project. Open up SQL Server Object Explorer and expand your local DB to see the new database:

Success! Go ahead and run the project locally and, assuming you had everything hooked up correctly in Azure AD prior to these steps, all will work fine using this configuration. Feel free to rinse-and-repeat the above add-migration/update-database commands as you update the data model in the project. Each time you add a migration you’ll see some new files pop up in your Migrations folder.

Deploy to Azure

Now let’s look at what it will take to deploy this project into an Azure Web App and SQL Database running in Azure. (I’m using the new Azure Preview Portal in the screenshots below)

  1. Create a new Resource Group
    To help keep your resources organized, create a new Resource Group in the closest region, in my case South Central. We’ll deploy our Web App and SQL Database into this Resource Group.
  2. Create a new Azure Web App
    I’m going with the Free tier here but it will work on any of the pricing tiers. Choose the same Location here that you chose for your Resource Group, in my case South Central.
  3. Create a new SQL Database
    Same story here when creating a SQL Database…choose a server (or create a new one) in the same region and add it to the Resource Group. I’m using the Basic pricing tier, which as of the date of this post is estimated at $4.99/mo.

    There is a free SQL tier that is available in the current management portal when creating a new Web App and that will work for this sample, too, if you prefer to go that route.

  4. Add connection string
    Once the database is created, click in to the connection strings tab and copy the ADO.NET connection string:
    It helps to paste the connection string into a text editor so you can easily find the placeholder for the password and update that. If you don’t, your Web App won’t be able to connect to the database.

    Now open up your Web App and go into Application settings to access the Connection strings. Create a new connection string named “TodoListWebAppContext” (or the name you used in your web.config file if different than what I have above) paste your connection string to your database into the value field and click Save:

  5. Publish web app to Azure
    Ok, everything is now set up in Azure and ready for us to publish our application.
    1. Go back to your project in Visual Studio, right click the TodoListWebApp project and click on Publish
    2. Choose “Microsoft Azure Web Apps” as your target
    3. Log in to your Azure subscription (if prompted) and choose your web app from the drop down and click OK
    4. Leave the Connection screen without changes and click Next to the Settings screen
    5. On the Settings screen, the TodoListWebAppContext connection string should be pre-populated for you
    6. Check the “Execute Code First Migrations…” check box
    7. Click Publish and wait for the magic to happen
    8. After Visual Studio finished publishing, your browser should open to your new Azure Web App…but don’t try to Sign Up or Sign In yet…we’re not done J
  6. Update Azure AD application
    The last step is to get your app properly registered in Azure AD. You can either update the existing app you created when you first set up the sample, or start from scratch and create a completely new application in your AAD tenant. Here, I’m doing the former. If you create a new application, don’t forget to update the Client ID and Password from your new app in the web.config and re-publish your Web App.
    1. Log into the Azure management portal (https://manage.windowsazure.com) and drill down into your existing Azure AD tenant and application
    2. Click on the Configure tab
    3. Update the Sign-On URL to your new Azure Web App URL (use either http or https, just remember which so you navigate to the proper URL later for testing)
    4. Scroll down to the Single Sign-On section and find the Reply URL. Remove the existing URL and add in your Azure Web App URL
    5. Click Save
  7. Now the AAD, Web App and SQL Database are all set up. Navigate to your site and click on Sign Up and enter your AAD info as you previously did in the local sample, log in using your AAD user, and click on todos in the top nav
  8. More magic was happening as you accessed the app for the first time. If you would’ve looked at your SQL Database before the previous step there would’ve been nothing there. That’s because the app creates the database the first time it’s accessed, which you just did. Open up your Server Explorer in Visual Studio and refresh your Azure connection. You’ll see your new SQL Database listed. Right-click on the database and choose “Open in SQL Server Object Explorer”, log in with your credentials you set up when you created the database, and you’ll be taken to SQL Server Object Explorer where you can interact with your new database like you would any other SQL database.

    The additional table you see there, “_MigrationHistory”, is owned by EF and is populated every time you do a deployment which includes a database change.

And that’s it! Feel free to go back to your project, update the data model and re-publish to Azure. After you log back into the site and access todo’s, you’ll see the database reflect the data model change as well as a new entry in the _MigrationHistory table.

Leave a Reply

Your email address will not be published. Required fields are marked *