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 »