Entity Framework 7

ASP.NET Core Project with Angular 2, Aurelia and an API

I have been exploring Aurelia and more recently Angular 2 and while doing so I thought it might be nice to run both frameworks from the same project.  My first crack at this can be found in this repo on Github.

Content

  • Contact model, a simplified version of the one used in previous blogs
  • ContactsController and related razor views created using Visual Studio’s scaffolding tools based on the contact mode
  • ContactsApiController is the end point for the Angular 2 and Aurelia applications
  • Angular 2 application that closely match the one from last week’s post
  • Aurelia application is currently just a proof that Angular 2 and Aurelia could run in the same project. This application will be updated to connect to the project’s web API.

Getting Started

Ensure that node and jspm are install.

After acquiring the code open the solution. If using Visual Studio the npm based packages will be restored automatically. If not using Visual Studio then run  npm install from the console. This will handle all the files needed by Angular 2.

Next run the jspm install -y  command to install the Aurelia related packages.

Make sure the database is created and up to date with the following two commands.

dnx ef database update -c ApplicationDbContext
dnx ef database update -c ContactsDbContext

In wwwroot open the config.js file and verify the paths section looking like the following. Jspm install seems to rewrite the github and npm portions of the paths section which removed the “../”. This is more than likely a configuration issue that I hope to fix in the future.

paths: {
  "*": "../Aurelia/*",
  "github:*": "../jspm_packages/github/*",
  "npm:*": "../jspm_packages/npm/*"
}

Finally run the angular2 gulp task from the task runner. The application should now run with no issues.

First Run

Make sure to register a new user as both the contacts controllers require an authorized user and filter down the contacts to display based on the logged in user.

The menu bar will contain links for Angular 2, Aurelia and Razor. Use the razor link to create some data. This is the generated razor views mentioned above. It is also the only way to add data through the application currently.

The Angular 2 link will of course launch the Angular 2 application that will display a list of contacts for the current user.

The  Aurelia like will launch the Aurelia application which just contains the very basic application from the getting started guide.

Going Forward

The plan is to develop the Angular 2 and Aurelia applications together. The Aurelia application will be the first to get some time to get up to the same level as the Angular 2 application.

It is also my hope that having this project will be a good reference for you when reading the examples in future blog posts.

ASP.NET Core Project with Angular 2, Aurelia and an API Read More »

ASP.NET 5 Web API Put

As part of last week’s post on Aurelia’s Event Aggregator I needed a way to update existing contacts. This was a hole in my existing API and it was time to fill it.  See last week’s post for usage on the client side this post will only be covering the server side.

First off here is the code I added to the ContactsController in the API folder of my project. I thought the overview would be helpful a helpful context as we break down the different parts of the function.

[HttpPut("{id}")]
public async Task<IActionResult> Update(int id, [FromBody] Contact updatedContact)
{
    if (updatedContact == null || updatedContact.Id != id)
    {
        return HttpBadRequest();
    }

    var contact = await GetContacts()
                        .Where(c => c.Id == id).FirstOrDefaultAsync();

    if (contact == null)
    {
        return HttpNotFound();
    }

    if (!ModelState.IsValid)
    {
        return new BadRequestObjectResult(ModelState);
    }

    _dbContext.Entry(contact).State = EntityState.Detached;
    _dbContext.Update(updatedContact);
    updatedContact.UserId = User.GetUserId();  
    await _dbContext.SaveChangesAsync();

    return CreatedAtRoute("GetById",
                          new
                          {
                              controller = "Contacts",
                              id = updatedContact.Id
                          },
                          updatedContact);
}

First off the Update function is decorated to only handle HttpPut actions with an ID. The function itself of course requires an ID. The FormBody attribute on the updatedContact parameter tells the framework to build a contact object from the request body.

[HttpPut("{id}")]
public async Task<IActionResult> Update(int id, [FromBody] Contact updatedContact)

Next if the updatedContact was unable to be built from the request body or if the ID passed to the update function doesn’t match the ID in the updatedContact then a bad request status is returned.

if (updatedContact == null || updatedContact.Id != id)
{
    return HttpBadRequest();
}

Next I query the database for a matching contact. This query is limited to the current users so it should help prevent a contact for the wrong user being updated. If no matching contact is found then not found status is returned.

var contact = await GetContacts()
                    .Where(c => c.Id == id).FirstOrDefaultAsync();

if (contact == null)
{
    return HttpNotFound();
}

Next check to see if the mode state is valid and return bad request object result if it is not.

if (!ModelState.IsValid)
{
    return new BadRequestObjectResult(ModelState);
}

This next bit was a little bit of a challenge. Since entity framework was queried to see if the updated contact already exists I was getting an error when trying to use the DB context’s update function. One way to address this error would have been to update the contact pulled from the database with the values from the updated contact from the request body. If I had of gone this route something like automapper would have made the job fairly easy. Instead I used the DB context entry on the contact returned from the database to set its state to detached which tells the context to stop tracking that item. After that the context’s update function worked like a charm and I could save changes based on the updatedContact parameter.

_dbContext.Entry(contact).State = EntityState.Detached;
_dbContext.Update(updatedContact);
updatedContact.UserId = User.GetUserId();
await _dbContext.SaveChangesAsync();

Finally I returned the client the updated contact. This is the same thing I did for post and may or may not be the best thing to do on a put.

return CreatedAtRoute("GetById",
                      new
                      {
                          controller = "Contacts",
                          id = updatedContact.Id
                      },
                      updatedContact);

I am not sure how much of this is the “correct” way to handle a put. After seeing how some of this is handled when using razor with anti-forgery tokens and the ability to only allow certain fields to be updated this implementation seems lacking. This is a jumping off point, but I need to do more research on how to properly secure an API.

ASP.NET 5 Web API Put Read More »

Migration from ASP.NET 5 Beta 7 to Beta 8

ASP.NET 5 beta 8 was released on October 15th. Read the main announcement here and the entity framework 7 specific announcement here.

The tooling update can be found here. The relevant files are either DotNetVersionManager-x64.msi or DotNetVersionManager-x86.msi depending on what your system supports and WebToolsExtensionsVS14.msi.

The above gets everything needed for use inside Visual Studio for more details on other options check out Microsoft’s documentation for getting started with Windows, Mac or Linux.

After completing the upgrade open global.json and update the sdk version to beta 8.

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-beta8"
  }
}

Next up is project.json which has more changes than other migrations due to the move from hosting in Helios to Kestrel. First update beta7 to beta8 in the dependencies section.

  "dependencies": {
    "EntityFramework.SqlServer": "7.0.0-beta8",
    "EntityFramework.Commands": "7.0.0-beta8",
    "Microsoft.AspNet.Mvc": "6.0.0-beta8",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta8",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta8",
    "Microsoft.AspNet.Authentication.Facebook": "1.0.0-beta8",
    "Microsoft.AspNet.Authentication.Google": "1.0.0-beta8",
    "Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-beta8",
    "Microsoft.AspNet.Authentication.Twitter": "1.0.0-beta8",
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta8",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta8",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta8",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta8",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta8",
    "Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta8",
    "Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
    "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta8",
    "Microsoft.Framework.Logging": "1.0.0-beta8",
    "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
    "Microsoft.Framework.Logging.Debug": "1.0.0-beta8",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta8"
  }

Note that Microsoft.AspNet.Server.IIS and Microsoft.AspNet.Server.WebListener have been removed. Microsoft.AspNet.IISPlatformHandler and Microsoft.AspNet.Server.Kestrel have been added.

In the commands section the web command has been updated to use Kestrel.

Before:
"web": "Microsoft.AspNet.Hosting --config hosting.ini"

After:
"web": "Microsoft.AspNet.Server.Kestrel"

As a result of the move to Kestrel both hosting.ini and wwwroot\bin\AspNetLoader.dll can be deleted. In wwwroot the web.config file changed to the following.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="httpPlatformHandler" 
           path="*" 
           verb="*" 
           modules="httpPlatformHandler" 
           resourceType="Unspecified"/>
    </handlers>
    <httpPlatform processPath="%DNX_PATH%" 
                  arguments="%DNX_ARGS%" 
                  stdoutLogEnabled="false" 
                  startupTimeLimit="3600"/>
  </system.webServer>
</configuration>

Startup.cs had a few changes. First in the constructor the application’s base path moved out of the constructor of ConfigurationBuilder to the SetBasePath function.

Before:
var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath);

After:
var builder = new ConfigurationBuilder()
                .SetBasePath(appEnv.ApplicationBasePath);

In ConfigureServices the setup for third-party authentication has been removed. For example the following has been removed.

services.Configure<FacebookAuthenticationOptions>(options =>
{
    options.AppId = Configuration["Authentication:Facebook:AppId"];
    options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});

Third party authentication options are now set in the Configure function. Here is an example with Facebook.

app.UseFacebookAuthentication(options =>
{
    options.AppId = Configuration["Authentication:Facebook:AppId"];
    options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});

Also in the Configure function app.UseErrorPage is now app.UseDeveloperExceptionPage and app.UserErrorHandler is now app.UseExceptionHandler.

Before:
app.UseErrorPage();
app.UseErrorHandler("/Home/Error");

After:
app.UseDeveloperExceptionPage();
app.UseExceptionHandler("/Home/Error");

Add the platform handler to the request pipeline before app.UseStaticFiles.

// Add the platform handler to the request pipeline.
app.UseIISPlatformHandler();

// Add static files to the request pipeline.
app.UseStaticFiles();

In AccountController.GetCurrentUserAsync and ManageController.GetCurrentUserAsync Context is now HttpContext.

Before:
return await _userManager.FindByIdAsync(Context.User.GetUserId());

After:
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());

Next up are the changes related to entity framework 7. EF7 had a lot of API changes with this release. I am covering the ones related to the app I am working with and others can be found by looking at the commits related to this issue.

The designer.cs that goes with migrations drop the override of Id in favor of a migration attribute instead. The new attribute can be found in Microsoft.Data.Entity.Migrations.

[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
Migration related renames
Old New
Key HasKey
Reference HasOne
InverseCollection WithMany
ConcurrencyToken IsConcurrencyToken
isNullable nullable

After all the above changes my project built, but would error because entity framework was trying to run migrations that had already been applied. After some digging I found that the table used to check if a migration has been applied or not had been renamed from MigrationHistory to EFMigrationsHistory. The following SQL will move the migrations that have been applied from the old table to the new one.

INSERT INTO dbo.__EFMigrationsHistory (MigrationId, ProductVersion) 
SELECT MigrationId, ProductVersion FROM dbo.__MigrationHistory

After fixing the migration issue the app ran with no problems. Make sure and check out the release page and the breaking changes page for this release.

Also note that the ASP.NET 5 project templates for Visual Studio have been open sourced and can be found here. The templates are a great resource which I used to work through a couple of issues when doing the migration to beta 8.

Migration from ASP.NET 5 Beta 7 to Beta 8 Read More »

Add and Delete from an API

A few weeks ago I covered creating a basic API to retrieve contacts. In this post I am going to expand on that example by adding the ability to create and delete contacts. Before starting it would be a good idea to review my post on API basics as well as make sure you have a tool such as Postman to exercise your API.

First is the function for the creation of a new contact which will be an http post that accepts a contact, does some validation and inserts the contact to the database.

[HttpPost]
public async Task Create([FromBody] ContactModel contact)
{
    if (contact == null)
    {
        return HttpBadRequest();
    }

    if (!ModelState.IsValid)
    {
        return new BadRequestObjectResult(ModelState);
    }

    _dbContext.Add(contact);
    await _dbContext.SaveChangesAsync();

    return CreatedAtRoute("GetById", 
                          new {controller = "Contacts",
                               id = contact.Id}, 
                          contact);
}

First thing to notice is the HttpPost attribute that says this function only handles HTTP posts. Next notice the FromBody attribute on the contact parameter of the function call. This tells ASP to bind the contact object to the data provided by the request body so that the function has a hydrated contact object to work with.

Both if statements are doing validation. The first is making sure that contact has a value. The second if is a bit of magic provided by ASP. ModelState contains information about the state of the model, a contact in this case, after it is bound to the values from the HTTP request. The contact model has data annotations which will cause ModelState.IsValid to return false if the model fails to validate against any of the data annotations. Both set of variations return a HttpBadRequest, but the ModelState version passes back the ModelState to the client since it contains details of all failed validation.

If all validation passed then the new contact is added to the controller’s dbContext and the dbContext saves changes inserts the new contact into the database.

Finally a route to the newly inserted contact is returned to the client. CreatedAtRoute takes a route name, route values and a value. In this case it is saying run the “GetById” route for the contacts controller with the ID of the new contact.

In order to get CreatedAtRoute to work the Get overload that takes an ID needed a name which is provided as part of the HttpGet attribute.

[HttpGet("{id}", Name = "GetById")]
public async Task Get(int id)

Now to add a contact with the API using Postman. First click Get which will drop down a list of HTTP verb to choose from. For adding a new contact we need to use Post.

postmanHttpVerb

After selecting post the body tab will be enabled. On the body tab select raw from the radio buttons. Next click the drop down that says text and select JSON (application/json) since the data for the contact will be sent to the API as JSON.

postmanBodyTypeFinally enter the appropriate JSON and click send. All that is required to create a new contact with my API is a name so the follow JSON is what I used to test.

{"Name" : "John McTest"}

At this point if all went well you will find John McTest in database. If all went well Postman will give the option to view the response which would include the Id which was set when dbContext.SaveChangesAsync was called.

The delete function is much simpler. It just needs the HttpDelete attribute and takes the ID of the contact to be deleted.

[HttpDelete("{id}")]
public async Task Delete(int id)
{
    var contact = await GetContacts()
                          .Where(c => c.Id == id).FirstOrDefaultAsync();

    if (contact == null) return;

    _dbContext.Remove(contact);
    await _dbContext.SaveChangesAsync();
}

Using the dbContext the contact is retrieved for the ID passed in. If the contact is not found the function just returns since the contact has already been removed from the database. If the contact is found then the remove function of the dbContext is used to mark the contact for delete and then save changes of dbContext is used to send the delete command to the database.

To test with Postman select delete from the list of HTTP verbs, this is the same drop down that was used to select post above. Next enter the ID to be deleted in the URL box and click send. In the screenshot below the API will be told to delete the contact with the ID of 108.

postmanDelete

Check out the ASP.NET 5 docs for a great API example that uses Fiddler instead of Postman.

Add and Delete from an API Read More »

Aurelia with ASP.NET 5 and Web API

Update: A series of posts has been made covering this same topic with the RTM versions of both ASP.NET Core and Aurelia. The first post in the series can be found here.

Now that I have a web API for my contacts I wanted to go back and add a front end to view them. I decided this would also be a good time to try out one of the single-page application frameworks instead of using razor. The number of choices for a spa framework is almost over whelming. Angular, Ember, Meteor, etc. In the end I decided to try out Aurelia mostly based on the fact that Rob Eisenberg is behind it.

To get going I highly recommend going through Aurelia’s get started guide. In addition to being a great introduction to Aurelia I also had to pull at least one file out of the sample project to get up and running in my ASP.NET project.

A couple more resources I recommend reading before getting started are a couple of blog post by Scott Allen. The first covers getting jspm going in ASP.NET 5 and the second is a guide to get started with Aurelia in ASP.NET 5.

Now to get started. The first step is to install jspm which is yet another package manager. It can be installed using with the following npm command.

npm install -g jspm@beta

jspm utilizes GitHub in some cases to install packages so it is recommended that jspm be configured with a login or api token for GitHub to avoid any anonymous API request limits.

jspm registry config github

The remaining commands should be run from the project directory that contains the project.json file.

Next run jspm’s init command. This command will ask a series of questions. The default is fine for most of them. The exceptions being the server baseURL should be ./wwwroot and I chose to use Babel as my transpiler.

jspm init

Now to install all the Aurelia bits that will be need to get an application up and hit a web API.

jspm install aurelia-framework
jspm install aurelia-bootstrapper
jspm install aurelia-fetch-client

Next add an html file (any name is fine) to the wwwroot folder. This html file will be how the Aurelia application is accessed and the file does not have a lot in it. If you read either Aurelia’s getting started or Scott’s blog the following contents will look very similar.

<!doctype html>
<html>
<head>
    <title>Hello from Aurelia</title>
</head>
<body aurelia-app>
    <script src="jspm_packages/system.js"></script>
    <script src="config.js"></script>
    <script>
        System.import("aurelia-bootstrapper");
    </script>
</body>
</html>

When the above page loads Aurelia kicks in and looks for app.js and app.html. My app.js is based on the users.js from the getting started guide.

import {inject} from 'aurelia-framework';
import {HttpClient} from 'jspm_packages/github/aurelia/[email protected]/aurelia-fetch-client.js';
import 'fetch';

@inject(HttpClient)
export class App{
    heading = 'Contacts';
    contacts = [];

    constructor(http){
        http.configure(config => {
            config
              .useStandardConfiguration()
              .withBaseUrl('https://localhost:14830/api/');
        });

        this.http = http;
    }

    activate(){
        return this.http.fetch('contacts')
          .then(response => response.json())
          .then(contacts => this.contacts = contacts);
    }
}

This class acts as the view model for my contact list. In the constructor function an http client is set up with a base url that matches the base url for the project’s web API which is http://localhost:14830/api/ in this case. The activate function is called by Aurelia and is where the contacts API is called using http.fetch. The import to fetch is the file I had to copy out of the Aurelia get started application into the wwwroot folder. You may also notice that the other imports are referencing specific folders with specific versions. This is not something that should be done for anything other than a short demo. I need to do some learning on gulp and what exactly Aurelia requires to get that fixed.

The following is the app.html.

<template>
    <section>
        <h2>${heading}</h2>
        <div repeat.for="contact of contacts">
            <p>${contact.Name}</p>
            <div repeat.for="emailaddress of contact.EmailAddressModels">
                <p>${emailaddress.Address}</p>
            </div>
        </div>
    </section>
</template>

The ${heading} is binding the value that will be displayed to the heading property defined in the app class. Next notice the repeat.for which will repeat the element it is defined on and its children foreach in the container to the right of the of statement. For example the above is going to print the name of each contact and all that contact’s email address contained in the contacts property of the app class. The resulting page is ugly, but the point is to prove Aurelia running and displaying the proper data.

At this point to remove some complexity I removed the authorize attribute off of the contacts controller and ran a test. As you may have guessed the test failed.

The failure was caused by the API returning a single object that then contain all the contacts instead of an array of contacts. The cause of this issue is the changes I made to work around serialization issue I was having with circular references  from my entity framework navigation properties.

The fix was to remove the following from the ConfigureServices function of the Startup class.

services.ConfigureMvcJson(options =>
{
    options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
});

Then in all the contact related classes I added the JsonIgnore attribute to the property that pointed back to the contact model.

public class ContactEmailModel
{
    public int ContactId { get; set; }
    public int Id { get; set; }
    [EmailAddress]
    public string Address { get; set; }

    [JsonIgnore]
    public ContactModel Contact {get; set;}
}

With those two changes everything started working. At this point I am not sure if that is the proper way to handle my issue or not. I have a feeling it will be something I will end up revisiting as I continue to learn more.

Aurelia with ASP.NET 5 and Web API Read More »

Migration from ASP.NET 5 Beta 6 to Beta 7

On September 2nd ASP.NET 5 beta 7 was released. As with beta 6 this release includes a tooling update for Visual Studio. Read the announcement here.

The tooling update can be found here. The relevant files are either DotNetVersionManager-x64.msi or DotNetVersionManager-x86.msi depending on what your system supports and WebToolsExtensionsVS14.msi.

After installing the tooling update change the sdk version in global.json to beta 7.

{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-beta7"
  }
}

In the project.js file update beta6 to beta7 in the dependencies section.

  "dependencies": {
    "EntityFramework.SqlServer": "7.0.0-beta7",
    "EntityFramework.Commands": "7.0.0-beta7",
    "Microsoft.AspNet.Mvc": "6.0.0-beta7",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta7",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta7",
    "Microsoft.AspNet.Authentication.Facebook": "1.0.0-beta7",
    "Microsoft.AspNet.Authentication.Google": "1.0.0-beta7",
    "Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-beta7",
    "Microsoft.AspNet.Authentication.Twitter": "1.0.0-beta7",
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta7",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta7",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta7",
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta7",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta7",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta7",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta7",
    "Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta7",
    "Microsoft.Framework.Configuration.Json": "1.0.0-beta7",
    "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta7",
    "Microsoft.Framework.Logging": "1.0.0-beta7",
    "Microsoft.Framework.Logging.Console": "1.0.0-beta7",
    "Microsoft.Framework.Logging.Debug": "1.0.0-beta7",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta7"
  }

In Startup.cs replace the Microsoft.Framework.Runtime namespace with Microsoft.Dnx.Runtime.

using Microsoft.Dnx.Runtime;

The remaining changes are related to entity framework 7. ApplyMigrations has been change to Migrate.

Before:
Database.ApplyMigrations();

After:
Database.Migrate();

Any migration designer.cs files will need the following changes. The Microsoft.Data.Entity.Migrations.Infrastructure namespace is now Microsoft.Data.Entity.Infrastructure.

using Microsoft.Data.Entity.Infrastructure;

ContextType has changed to DbContext.

Before:
[ContextType(typeof(ContactsDbContext))]

After:
[DbContext(typeof(ContactsDbContext))]

The ProductVersion property has been removed and BuildTargetModel is now protected.

Before:
public override string ProductVersion
{
    get { return "7.0.0-beta6-13815"; }
}

public override void BuildTargetModel(ModelBuilder builder)

After:
protected override void BuildTargetModel(ModelBuilder builder)

The Microsoft.Data.Entity.Migrations.Builders namespace is now Microsoft.Data.Entity.Migrations.Operations.Builders.

using Microsoft.Data.Entity.Migrations.Operations.Builders;

Any classes that inherit from the Migration need the Up and Down functions changed to protected.

Before:
public override void Up(MigrationBuilder migration)
public override void Down(MigrationBuilder migration)

After:
protected override void Up(MigrationBuilder migration)
protected override void Down(MigrationBuilder migration)

The AddCoumn of MigrationBuilder now needs a type specified and nullable has changed to isNullable.

Before:
migration.AddColumn(name: "UserId", 
                    table: "ContactModel",
                    type: "nvarchar(max)",
                    nullable: true);

After:
migration.AddColumn<string>(name: "UserId",
                            table: "ContactModel",
                            type: "nvarchar(max)",
                            isNullable: true);

The last change to MigrationBuilder that I ran into was with table.ForeginKey. referencedTable and referencedColumn changed to principleTable and principalColumns.

Before:
table.ForeignKey(name: "FK_ContactAddressModel_ContactModel_ContactId",
                 columns: x => x.ContactId,
                 referencedTable: "ContactModel",
                 referencedColumn: "Id");

After:
table.ForeignKey(name: "FK_ContactAddressModel_ContactModel_ContactId",
                 columns: x => x.ContactId,
                 principalTable: "ContactModel",
                 principalColumns: new []{"Id"});

That was all the changes needed to get my test project updated. Here is the Github release page and breaking changes page for this release.

Migration of an existing project through the betas does work, but I recommend creating a new project every couple of betas. Things are changing in the project templates as well the core of ASP.NET 5. At the very least create a new project and look through the startup class and implement anything new that you find useful.  For example the debug logger is now included when creating a new project.

Migration from ASP.NET 5 Beta 6 to Beta 7 Read More »

Basic Web API with ASP.NET 5

I am going to create basic web API access to the contacts data I have been using in previous posts. To start with I added an API folder to my project to hold my API controller. Next I added a contacts controller to the API folder by right clicking on the folder and selecting add new item.

AddNewItem

From the add new item under DNX selected Web API Controller Class, entered a name and clicked add.

AddNewItemDialog

From the resulting code I removed all the actions except for two get functions.

[Route("api/[controller]")]
public class ContactsController : Controller
{
    private readonly ContactsDbContext _dbContext;

    public ContactsController(ContactsDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    // GET: api/values
    [HttpGet]
    public async Task<IEnumerable<ContactModel>> Get()
    {
        return await GetContacts().ToListAsync();
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public async Task<ContactModel> Get(int id)
    {
        return await GetContacts()
                     .Where(c => c.Id == id).FirstOrDefaultAsync();
    }

    private IQueryable GetContacts()
    {
        var contacts = from c in _dbContext.ContactModels
                                 .Include(c => c.AddressModels)
                                 .Include(c => c.EmailAddressModels)
                                 .Include(c => c.PhoneModels)
                       select c;
        return contacts;
    }
}

The above code contains a lot of new concepts I am going to break it down more.

[Route("api/[controller]")]
public class ContactsController : Controller

The first thing to notice is the route attribute on the class declaration. The route attribute is how the routing engine determines where to send requests. Using [controller] tells the routing engine to use the class name minus the word controller. For example the above route handles api/contacts.

private readonly ContactsDbContext _dbContext;

public ContactsController(ContactsDbContext dbContext)
{
    _dbContext = dbContext;
}

The constructor takes the DbContext needed to access contacts. Note that the context is being automatically injected via the constructor thanks to the fact that ASP.NET 5 now comes with dependency injection out of the box.

// GET: api/values
[HttpGet]
public async Task<IEnumerable<ContactModel>> Get()
{
    return await GetContacts().ToListAsync();
}

// GET api/values/5
[HttpGet("{id}")]
public async Task<ContactModel> Get(int id)
{
    return await GetContacts()
                 .Where(c => c.Id == id).FirstOrDefaultAsync();
}

First get function returns all contacts and the second returns a specific contact based on the contact’s ID.

private IQueryable<ContactModel> GetContacts()
{
    var contacts = from c in _dbContext.ContactModels
                             .Include(c => c.AddressModels)
                             .Include(c => c.EmailAddressModels)
                             .Include(c => c.PhoneModels)
                   select c;
    return contacts;
}

Note that the query contains three includes and each of the included classes contain a navigation property back to the main contact. For example here is the email address model.

public class ContactEmailModel
{
    public int ContactId { get; set; }
    public int Id { get; set; }
    [EmailAddress]
    public string Address { get; set; }

    public ContactModel Contact {get; set;}
}

All of the above compiles and seems to run fine, but will not provide a response. The navigation property for contact creates a circular reference that the response serializer throws an exception trying to serialize.

Thankfully the framework has a configuration option to work around this problem. In the ConfigureServices function of the Startup class add the following.

services.ConfigureMvcJson(options =>
{
    options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
});

The above options marks the Contact property as a reference and does not try to circularly serialize it.

Now by running the project and going to http://localhost:port/api/contacts/1 in the browser I get all the contact data related to the contact with an ID of 1. I recommend using something like Postman to make the result more readable if you don’t have a front end to display the data.

Basic Web API with ASP.NET 5 Read More »

Viewing SQL for Entity Framework 7 Queries

While writing this post on dealing with entity framework and collections I needed a way to see what SQL queries entity framework was sending to the database. At the time I used Express Profiler for the task.

expressProfiler

To get up and running with Express Profiler enter the server and authorization information and click the play button. Each event is logged in the grid. When an event is selected the actual query will show in the panel below the grid. The clear function is also very handy. Just hit it before triggering the entity framework query that you want to see the SQL for to minimize the number of event that have to be gone through.

I came across Express Profiler while watching Julie Lerman’s Looking Ahead to Entity Framework 7 Pluralsight course. This course is one of the ones provided free with a MSDN subscription so there is no reason not to check it. The course is a good introduction to Entity Framework 7. Keep in mind that the course is using beta 4 so things have changed some since it was released.

With the release of ASP.NET 5 Beta 6 a new debug logger was added to log to Visual Studio’s output window. This new logger seemed like it would be useful for logging entity framework queries.

In project.json add a dependency for Microsoft.Framework.Logging.Debug.

"Microsoft.Framework.Logging.Debug" :  "1.0.0-beta6"

In the Configure function of the Startup class use the logger factory to add the new debug logger. This is done via the AddDebug extension method that comes when the new dependency was added above.

if (env.IsDevelopment())
{
    app.UseBrowserLink();
    app.UseErrorPage();
    app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
    loggerfactory.AddDebug(LogLevel.Verbose);
}

Run the application and the output window will contain the SQL that is sent to the database. The downside to this approach is that the log level of verbose outputs a lot of information making it harder to locate the SQL bits.

Viewing SQL for Entity Framework 7 Queries Read More »

Migration from ASP.NET 5 Beta 5 to Beta 6

ASP.NET 5 Beta 6 was released on July 27th with the details from Microsoft in this blog post.  This release comes with a tooling update for Visual Studio 2015 and fewer breaking changes than beta 5.

Download and install the tooling update from here. Grab either DotNetVersionManager-x64.msi or DotNetVersionManager-x86.msi depending on what your system supports and WebToolsExtensionsVS14.msi. For WebToolsExtensionsVS14.msi there are language pack versions available for languages other than english.

With the tooling updates installed the following changes were made from Visual Studio. In global.json update the sdk version to beta 6.

{
    "projects": [ "src", "test" ],
    "sdk": {
        "version": "1.0.0-beta6"
    }
}

For project.json in dependencies section update all the values from beta5 to beta6 except for  Microsoft.Framework.CodeGenerator.Mvc which stays at beta5.

"dependencies": {
  "EntityFramework.SqlServer": "7.0.0-beta6",
  "EntityFramework.Commands": "7.0.0-beta6",
  "Microsoft.AspNet.Mvc": "6.0.0-beta6",
  "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta6",
  "Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta6",
  "Microsoft.AspNet.Authentication.Facebook": "1.0.0-beta6",
  "Microsoft.AspNet.Authentication.Google": "1.0.0-beta6",
  "Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-beta6",
  "Microsoft.AspNet.Authentication.Twitter": "1.0.0-beta6",
  "Microsoft.AspNet.Diagnostics": "1.0.0-beta6",
  "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta6",
  "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta6",
  "Microsoft.AspNet.Server.IIS": "1.0.0-beta6",
  "Microsoft.AspNet.Server.WebListener": "1.0.0-beta6",
  "Microsoft.AspNet.StaticFiles": "1.0.0-beta6",
  "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta6",
  "Microsoft.Framework.Configuration.Json": "1.0.0-beta6",
  "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta6",
  "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5",
  "Microsoft.Framework.Logging": "1.0.0-beta6",
  "Microsoft.Framework.Logging.Console": "1.0.0-beta6",
  "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta6"
}

In Startup.cs in the configure function in the is development section I was able to enable browser link and the UseErrorPage dropped the show all option.

if (env.IsDevelopment())
{
    app.UseBrowserLink();
    app.UseErrorPage();
    app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
}

The LogOff action of the AccountController changed to an async operation.

Before:
public IActionResult LogOff()
{
    SignInManager.SignOut();
    return RedirectToAction("Index", "Home");
}

After:
public async Task LogOff()
{
    await SignInManager.SignOutAsync();
    return RedirectToAction("Index", "Home");
}

The rest of the changes I had to make are entity framework related. The call to apply migrations no longer requires the as relation call.

Before:
Database.AsRelational().ApplyMigrations();

After:
Database.ApplyMigrations();

If you are trying to keep any existing migrations then changes will need to be made in them as well. There is a namespace change related to moving migrations out of the relational area.

Before:
Microsoft.Data.Entity.Relational.Migrations.Infrastructure

After:
Microsoft.Data.Entity.Migrations.Infrastructure

The settings on auto incremented properties changed as well.

Before:
b.Property<int>("ContactId")
    .GenerateValueOnAdd()
    .StoreGeneratedPattern(StoreGeneratedPattern.Identity);

After:
b.Property("ContactId")
    .ValueGeneratedOnAdd();

That is all there is to moving to beta 6 from beta 5. I am going to leave you with some reference links that may help if your project has issues with the move to beta 6.

Release page on Github with all the change in beta 6
Beta 6 Announcements Github page including breaking changes
ASP.NET 5 Roadmap

Migration from ASP.NET 5 Beta 5 to Beta 6 Read More »

Entity Framework 7 with a Class that Contains Collections

In order to explore entity framework a bit more I took my existing contact class and broke it down to the following.

public class Contact
{
    public int ContactId { get; set; }
    public string UserId { get; set; }
    [Required]
    [StringLength(200, MinimumLength = 0)]
    public string Name { get; set; }
    public List<ContactAddress> Addresses { get; set; }
    public List<ContactPhone> Phones { get; set; }
    public List<ContactEmailAddress> EmailAddresses { get; set; } 
}

The following is the new email address model from it you will get the idea of what the address and phone models contain.

public class ContactEmailAddress
{
    public int ContactId { get; set; }
    public int EmailId { get; set; }
    [EmailAddress]
    public string Email { get; set; }

    public Contact Contact { get; set; }
}

Next up was the DbContext which got a new DbSet, set up keys and relationships between the models. Again I am limiting the example to contact and email addresses but the same concepts apply to the other related models.

public class ContactsDbContext : DbContext
{
    private static bool _created;
    public DbSet<Contact> Contacts { get; set; }
    public DbSet<ContactEmailAddress> ContactEmailAddresses { get; set; }

    public ContactsDbContext()
    {
        if (!_created)
        {
            Database.AsRelational().ApplyMigrations();
            _created = true;
        }
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Contact>().Key(c => c.ContactId);

        builder.Entity<ContactEmailAddress>(entity =>
        {
            entity.Key(e => new { e.ContactId, e.EmailId });
            entity.Reference(e => e.Contact)
                  .InverseCollection(c => c.EmailAddresses)
                  .ForeignKey(e => e.ContactId);
        });
    }
}

In the above code the override of OnModelCreating establishes the connection between the models. InverseCollection establishes that there can be multiple email addresses for a single contact. I am not using it, but InverseReference would establish a one to one relationship.

After all the model changes are complete add a new migration from the command line using the following command. Then apply the migration by using the apply command or running the application if your application auto applies migrations.

dnx . ef migration add ContactsSplit --context ContactsDbContext

Here is an example query using this new class setup that include data from the contacts table and joins the email address table to get the related email addresses.

var contacts = from c in _db.Contacts
                         .Include(c => c.EmailAddresses)
               where c.UserId == User.GetUserId()
               select c;

The include statement above is what make entity framework eagerly load the data from the email address table. The default behavior would not load the email addresses. Also note that include statements can be chained as needed.

The following query is the same as above without eagerly loading the contact’s email addresses.

var contacts = from c in _db.Contacts
               where c.UserId == User.GetUserId()
               select c;

At this point the EmailAddresses property of the returned contacts would be null. To load the email addresses for a particular contact the following can be used.

_db.ContactEmailAddresses.Where(e => e.ContactId == contact.ContactId).Load();

This post on stackoverflow has a great set of tips related to collections with entity framework 7.

Entity Framework 7 with a Class that Contains Collections Read More »