ASP.NET 5

Configuration in ASP.NET 5

ASP.NET 5 offer a lot of options for loading configuration data such as json files, ini files, XML files, in memory collections, command line arguments, user secrets and environment variables.

The following has at least one example of each type of configuration. Configurations are setup in the constructor of the Startup class.

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
    // Setup configuration sources.
    var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
        .AddJsonFile("config.json")
        .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
        .AddIniFile("config.ini", optional: true)
        .AddInMemoryCollection(new Dictionary<string, string="">
        {
            {
            "AppSettings:TagLine",
            "InMemoryCollection"
            }
        })
        .AddXmlFile("config.xml", optional:true);

    if (env.IsDevelopment())
    {
        builder.AddUserSecrets();
    }
    builder.AddEnvironmentVariables();
    Configuration = builder.Build();
}

As you can see from the example all the different configuration sources can be used together without any issues. A critical thing to keep in mind is if a configuration option is set in multiple places the last configuration source’s value will be used. For example, using the code above, if the title of a site was sent in config.json and config.ini then the value from config.ini would be used.

An example I have seen the ASP.NET team use many times is to use user secrets for API key when in development and then store the keys in environment variables for production.

Here are the relevant lines from the dependencies section of the project.json file.

"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.Configuration.Xml" : "1.0.0-beta7"

Another great feature is being able to load an object with the values from a configuration section. The following is a class created to hold the settings for an application.

public class AppSettings
{
    public string Title { get; set; }
    public string TagLine { get; set; }
}

Then in the ConfigureServices function this is all that is needed to load the class.

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

Now instead of directly accessing the configuration classes in the HomeController the AppSettings class can be used instead. Here is an example of using ASP.NET 5’s built-in dependency to automatically get a reference to AppSetting via constructor injection.

private readonly IOptions _appSettings;

public HomeController(IOptions appSettings)
{
    _appSettings = appSettings;
}

And then using the _appSettings in the index action to pass values to the view.

public IActionResult Index()
{
    ViewData["Title"] = $"{_appSettings.Options.Title} - " +
                        $"{_appSettings.Options.TagLine}";
    return View();
}

The above is using C# 6’s new interpolated string feature.  The dollar sign before the string is what triggers the feature and allow use variables when wrapped in curly braces.

Check out this github repo for the internals of configuration in ASP.NET 5 .

I also recommend checking out the new Introduction to ASP.NET 5 course on Microsoft Virtual Academy. It covers a lot of good information including live.asp.net which is a production site used to for the ASP.NET 5 community stand up.

Configuration in ASP.NET 5 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 »

Start Aurelia from an ASP.NET 5 Controller

Last week was all about getting Aurelia up and running from inside of Visual Studio with an ASP.NET 5 project. In last week’s post I started Aurelia from an html page in the wwwroot folder. This week I am going to use a controller action to kick off Aurelia.

Start by modifying the default HomeController, or any controller of your choice, to add an Aurelia action that just returns a view.

public IActionResult Aurelia()
{
    return View();
}

Next right-click on the View/Home folder and add a new item.

AddNewItem

Select MVC View Page and enter a name that matches the above controller action, Aurelia.cshtml for this example.

AddNewItemDialog

The contents of Aurelia.cshtml are very close to the html page from last week except for a couple of items. The aurelia-app is on a div instead of the body and the script source has been changed to go up a folder level since the view will be running out of the Home folder but the scripts will still be in the root of the site when it is being served.

<div aurelia-app>
    <script src="../jspm_packages/system.js"></script>
    <script src="../config.js"></script>
    <script>
        System.import("aurelia-bootstrapper");
    </script>
</div>

Now change _Layout.cshtml in the Views/Shared folder to provide a link to the new Aurelia action. In this case it is being added to the navigation bar.

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li><a asp-controller="Home" asp-action="Index">Home</a></li>
        <li><a asp-controller="Home" asp-action="Aurelia">Aurelia</a></li>
        <li><a asp-controller="Home" asp-action="About">About</a></li>
        <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
    </ul>
    @await Html.PartialAsync("_LoginPartial")
</div>

A couple of use cases for this might be to split a really large application into multiple sub-spas to keep user from having to load data for parts of the application they may use infrequently. I bet this same concept could be achieved with Aurelia itself, but with an existing application the approach above maybe an easier way to start.

Start Aurelia from an ASP.NET 5 Controller 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 »

Web API with Get Filter and Security

This is a slight extension on the web API contacts controller from last week.

The first change is to the get that returns all contacts. Getting all contacts is great, but it would be helpful to be able to filter the data down. The following code is all the changes to the get function.

// GET: api/values
[HttpGet]
public async Task Get(string filter = null)
{
  var contacts = GetContacts();

  if (!string.IsNullOrWhiteSpace(filter))
  {
    contacts = contacts
         .Where(c => c.Name.IndexOf(filter, 0, StringComparison.CurrentCultureIgnoreCase) > -1 ||
                     c.AddressModels.Exists(a => a.Address.IndexOf(filter, 0, StringComparison.CurrentCultureIgnoreCase) > -1 ||
                                                 a.City.IndexOf(filter, 0, StringComparison.CurrentCultureIgnoreCase) > -1 ||
                                                 a.Country.IndexOf(filter, 0, StringComparison.CurrentCultureIgnoreCase) > -1 ||
                                                 a.PostalCode.IndexOf(filter, 0, StringComparison.CurrentCultureIgnoreCase) > -1 ||
                                                 a.State.IndexOf(filter, 0, StringComparison.CurrentCultureIgnoreCase) > -1) ||
                     c.EmailAddressModels.Exists(e => e.Address.IndexOf(filter, 0, StringComparison.CurrentCultureIgnoreCase) > -1) ||
                     c.PhoneModels.Exists(p => p.Number.IndexOf(filter, 0, StringComparison.CurrentCultureIgnoreCase) > -1));
  }

  return await contacts.ToListAsync();
}

The get function call now has an optional string for filter. If the filter has a value then a linq statement checks to see if any contact fields matches the filter. In the past I had used the contains function, but during tested I noticed that contains function was dong a case-sensitive matching and I wanted case-insensitive so I switch to the IndexOf function of the string class.

The filter is passed via a query string which seem to the be more restful way of doing filtering type stuff instead of creating a different get function. Keep in mind I am new to web API and rest so if I have any of this wrong please let me know.

The second thing I changed this round was to require authorization to use the API.

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

As you can see the only thing I did was add the authorize attribute to the controller class. That is all that is required and now the API will require the user be logged in. This is using ASP’s authorization and means that the user must be logged in via the web site and then use that same session to hit the API.

Requiring the user to already be logged may or may not be what you are looking for with your API. If you are using the API for run a SPA that could be fine, but if your API is being used to back another scenario than authorization will need to be fleshed out more.

I hope to address both the SPA and other authorization type in a future blog post so stay tuned.

Web API with Get Filter and Security 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 »

New ASP.NET 5 Project Using Yeoman

One of the great things about ASP.NET 5 its openness and support for cross-platform development. This post is going to walk through using Yeoman to create a new ASP.NET 5 application and then run that application from the command line. This will give you the same application as Visual Studio just without the Visual Studio solution.

First make sure node.js is installed. The installer can be found here. Node comes with a package manager called npm automatically. Don’t know anything about npm? Watch this introductory video.

Yeoman is a scaffolding tool that uses templates called generators. First using the following command from the command prompt to install Yeoman. As a note all the commands in this post should be run from the command prompt.

npm install -g yo

Next install the generator for ASP.NET 5 which is provided by the OmniSharp team.

npm install -g generator-aspnet

Now tell Yeoman to run the ASP.NET 5 generator.

yo aspnet

Below is a screenshot of the results. This is where the type of application to be generated is chosen. In this case I am choosing a Web Application.

yoaspnet

Next enter the name of the application. In this case WebApp1.

yoaspnetWebApp1

After the creation process is done a set of commands are show as the next steps.

yoaspnetWebApp1GettingGoing

This command changes to the directory created during the generation process.

cd "WebApp1"

DNX Utility or dnu is a tool used to manage operations related to packages an application uses. The restore command finds all the dependencies of your application and downloads them. Not only does restore get the top level of dependencies but it also gets all the sub dependencies.

dnu restore

DNU build runs the build process to produce the assemblies for an application.

dnu build

DNX is a .NET execution environment. It contains all that is needed to run an application. The run command is for console applications as the output from the generator said and does not apply to a web application.

Kestrel is a development web server that works cross platform. The web command uses this project and only works on Windows I believe.

dnx . web

OR

dnx . kestrel

At this point a web server is running and should the application will be viewable in a browser on a local host address. The exact url can be found in the hosting.ini file of the project.

The list of commands defined for an application can be found in the project.json file command section. The command section defines named entry points for the application. The following is the commands section of WebApp1 which defines both kestrel and web.

"commands": {
  "kestrel": "Microsoft.AspNet.Hosting --server Kestrel --config hosting.ini",
  "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --config hosting.ini"
}

New ASP.NET 5 Project Using Yeoman 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 »