.NET Core

Entity Framework Core Errors Using Add-Migration

I started off trying to expand my sample from last week’s post and hit some issues when trying to add a migration for a new DbContext.

The Setup

I added the following DbContext that only has one DbSet and auto applies migrations in the constructor.

using EfSqlite.Models;
using Microsoft.EntityFrameworkCore;

public sealed class ContactsDbContext : DbContext
{
    private static bool _created;

    public DbSet<Contact> Contacts { get; set; }

    public ContactsDbContext(DbContextOptions<ContactsDbContext> options)
        : base(options)
    {
        if (_created) return;
        Database.Migrate();
        _created = true;
    }
}

The command

Using Visual Studio’s Package Manager Console I ran the following command.

Add-Migration AddContacts -Context ContactsDbContext
Error 1 – No parameterless constructor

The above command resulted in the following error.

No parameterless constructor was found on ‘ContactsDbContext’. Either add a parameterless constructor to ‘ContactsDbContext’ or add an implementation of ‘IDbContextFactory<ContactsDbContext>’ in the same assembly as ‘ContactsDbContext’.

I read the first sentence and added a parameterless constructor to ContactsDbContext. I did think it was strange that a parameterless constructor wasn’t required the other contexts I had written in the past, but the error said to add a parameterless constructor so that is what I did.

Error 2 – System.InvalidOperationException: No database provider has been configured for this DbContext

Now having a parameterless constructor I ran the Add-Migration command again and was greeted with the following error.

System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

The second error forced me to step back and think more about what the problem was as it didn’t have an action I could take as the first sentence, which is, of course, my fault for not fully digesting what the error was saying.

The fix

The bit I was missing was the fact that I hadn’t added the following to the ConfigureServices function of the project’s Startup class.

services.AddDbContext<ContactsDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("Sqlite")));

With the above added I removed the parameterless constructor from ContactsDbContext and was able to successfully run the add migration command again.

Wrapping up

The moral of the story is to actually read the full error message before running off and trying to fix the problem. The second error message saying “using AddDbContext on the application service provider” is what triggered me to head in the right direction.

This was also a good reminder that tools like the ones used by Add-Migration can/do compile the project they are being used on in order to have enough context to perform their tasks.

Entity Framework Core Errors Using Add-Migration Read More »

Entity Framework Core with SQLite

All the applications used as examples for ASP.NET Core and Entity Framework Core from this site so far used database running SQL Server/SQL Express. In addition to the Microsoft-based SQL databases, Entity Framework Core has support for a number of other database providers. This post is going to look at using SQLite. A full list of the support database providers can be found here.

Starting point

Using Visual Studio 2017 I started with a new ASP.NET Core project using Individual User Accounts which ensured all the Entity Framework Core bits were present. The template in RC 4 used packages based on the Core 1.0.3 which I upgraded to 1.1.0. The project at this point can be found here.

Just a side note this project was created when Visual Studio 2017 was at the RC 4 stage. This code associated with this post will be updated when Visual Studio 2017 is released.

Naming warning

As you will be able to see with the structure of the solution I started this work using the project name SQLite. With this project name, it was impossible to get the SQLite package to install. If you see something like the following renaming your project should get you running.

Cycle detected: 
   Sqlite (>= 1.0.0) -> Microsoft.EntityFrameworkCore.Sqlite (>= 1.1.0) -> Microsoft.Data.Sqlite (>= 1.1.0) -> SQLite (>= 3.13.0)

This issue is where I found out what the problem was.

Add SQLite Packages

Right-click on the project file and click Manage NuGet Packages.

Select Browse and in the search box enter “Microsoft.EntityFramework.Sqlite” and install the two packages that are found.

Remove SqlServer Packages

While still in the Manage NuGet Packages screen click on the Installed tab. Select and uninstall the following packages.

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design

Configuration changes

Open appsettings.json and in the ConnectionStrings delete the line for DefaultConnection. Next, in the same section add a line for a SQLite connection string. The following is the result.

"ConnectionStrings": {
  "Sqlite": "Data Source=Database.db"
}

The above will expect the database file to be in the same location as the application is running. For a debug build the database file can be found in the \bin\Debug\netcoreapp1.0\ directory of the project.

Startup changes

The final location to change is in the ConfigureServices function of the Startup class. The following shows the addition of the application DB context before and after the changes.

Before:
services
  .AddDbContext<ApplicationDbContext>(options =>  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
 
After:
services
  .AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlite(Configuration.GetConnectionString("Sqlite")));

Wrapping up

The application is now runnable using SQLite as its backing data store. At this point, the only thing using data access is related to identity. The first time an attempt is made to access the database you may be prompted to apply migrations.

I have been using SQLite Studio to view the data in my database if you have that need outside of the application it does a good job.

The code in its final state can be found here.

Entity Framework Core with SQLite Read More »

ASP.NET Core Conversion to csproj with Visual Studio 2017 and update to 1.1.1

On March 7th Visual Studio 2017 was released bring the ASP.NET Core tools preview. ASP.NET Core 1.1.1 was also released. This post is going to cover converting the project from my MailGun post from being project.json based to csproj as well as migrating from the project from ASP.NET Core 1.0.2 to 1.1.1. Here is the project as it stood before I made any changes.

Visual Studio 2017

The first step is to get a version of Visual Studio 2017 (VS 2017) installed. The download page can be found here. Make sure to grab the community edition if you are looking for a free fully-featured IDE option. Check out this blog post from Microsoft on the many new features Visual Studio 2017 brings.

The installer for VS 2017 has changed a lot from previous versions. The way it works now is you select the workload you use and it only installs the bit it has to to keep the size of install down. The following is a screen shot from my install. I have a lot more workloads checked that is needed for just an ASP.NET Core application. At a minimum make sure the “ASP.NET and web development” workload gets installed. If you are interested in cross-platform development scroll to the bottom and also check “.NET Core cross-platform development”.

Project conversion

When you open the solution in VS 2017 it will prompt you to do a one-way upgrade.

After the conversion is complete a migration report will open. Below is mine. I had no issues, but if there were any this report should give you some idea of how they should be addressed.

As part of the conversion process, the following file changes happened.

Deleted:
global.json
ASP.NET-Core-Email.xproj
project.json

Added:
ASP.NET-Core-Email.csproj

That is all there is to the conversion. The tooling takes care of it all and your project should keep work just as before. The sample project post conversion can be found here.

Migration from 1.0.x to 1.1.1

The migration is almost as simple as the project conversion. In the solution explorer right click on the project to be migrated and select Properties.

Find the Target framework selection and select .NETCoreApp 1.1. Then save your solution.

Next, open the NuGet Package Manager. It can be by right click on the project and selecting Manage NuGet Packages or from the Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

Select the Updates tab and update all the related packages to 1.1.1 and click the Update button.

If you want a specific list of all the package changes check out the associated commit.

The only other change needed is in the constructor of the Startup class.

Before:
builder.AddUserSecrets();

After:
builder.AddUserSecrets<Startup>();

Wrapping up

After all the changes above your solution will be on the latest released bits. Having been following releases since beta 4 I can tell you this is one of the easiest migration so far. I may be partial, but .NET and Microsoft seem to be getting better and better over the last couple of years.

I am going to leave you with a few related links.

ASP.NET Core 1.1.1 Release Notes
Announcing New ASP.NET Core and Web Dev Feature in VS 2017
Project File Tools – Extension for IntelliSense in csproj
Razor Language Services – Extension for tag helper Intellisense

ASP.NET Core Conversion to csproj with Visual Studio 2017 and update to 1.1.1 Read More »

Log Requests and Responses in ASP.NET Core

Note: An updated version of this post for ASP.NET Core 3 and above is available.

As part of trying to do some debugging, I needed a way to log the requests and responses. Writing a piece of middleware seemed to be a good way to handle this problem. It also turned out to be more complicated that I had expected to deal with the request and response bodies.

Middleware

In ASP.NET Core middleware are the components that make up the pipeline that handles request and responses for the application. Each piece of middleware called has the option to do some processing on the request before calling next piece of middleware in line. After execution returns from the call to the next middleware, there is an opportunity to do processing on the response.

The pipeline for an application is set in the Configure function of the Startup class. Run, Map and Use are the three types of middleware. Run should only be used to terminate the pipeline. Map is used for pipeline branching. Use seems to be the most common type of middleware that does some processing and call the next middleware in line. For more detail see the official docs.

Creating Middleware

Middleware can be implemented as a lambda directly in the Configure function, but more typically it is implemented as a class that is added to the pipeline using an extension method on IApplicationBuilder. This example will be going the class route.

This example is a piece of middleware that using ASP.NET Cores built-in logging to log requests and responses. Create a class called RequestResponseLoggingMiddleware.

The class will need a constructor that takes to arguments both will be provided by ASP.NET Core’s dependency injection system. The first is a RequestDelegate for the next piece of middleware to be called. The second is an ILoggerFactory which will be used to create a logger. The RequestDelegate is stored to the class level _next variable and the loggerFactory is used to create a logger which is stored to the class level _logger variable.

public class RequestResponseLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public RequestResponseLoggingMiddleware(RequestDelegate next,
                                            ILoggerFactory loggerFactory)
    {
        _next = next;
        _logger = loggerFactory
                  .CreateLogger<RequestResponseLoggingMiddleware>();
    }
}

Add an Invoke function which is the function that will be called when your middleware is run by the pipeline. The following is the function that does nothing other than call the next middleware in the pipeline.

public async Task Invoke(HttpContext context)
{
     //code dealing with request

     await _next(context);

     //code dealing with response
}

Next, add a static class to simplify adding the middleware to the application’s pipeline. This is the same pattern the built-in middleware uses.

public static class RequestResponseLoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestResponseLogging(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestResponseLoggingMiddleware>();
    }
}

Adding to the pipeline

To add the new middleware to the pipeline open the Startup to the Configure function and add the following line.

app.UseRequestResponseLogging();

Keep in mind that the order in which middleware is added can make a difference in how the application behaves. Since the middleware this post is dealing with is logging I have placed it near the begging of the pipeline just before app.UseStaticFiles().

Logging requests and responses

Now that the setup work for our new middleware is done we will come back to its Invoke function. As I stated above this ended up being more complicated that I expected, but thankfully I found this by Sul Aga which really helped me work through the issues I was having.

I created a couple of helper functions that we will look at first. The following is the function call to create the string that will be logged for a request.

private async Task<string> FormatRequest(HttpRequest request)
{
    var body = request.Body;
    request.EnableRewind();

    var buffer = new byte[Convert.ToInt32(request.ContentLength)];
    await request.Body.ReadAsync(buffer, 0, buffer.Length);
    var bodyAsText = Encoding.UTF8.GetString(buffer);
    request.Body = body;

    return $"{request.Scheme} {request.Host}{request.Path} {request.QueryString} {bodyAsText}";
}

The key to getting this function to work and allow reading of the request body was request.EnableRewind() which allows us to read from the beginning of the stream. The rest of the function is pretty straight forward.

The next function is used to get the string to that will be used to log the response body. This function looks simpler than it is and only works because of how it is called from the Invoke function.

private async Task<string> FormatResponse(HttpResponse response)
{
    response.Body.Seek(0, SeekOrigin.Begin);
    var text = await new StreamReader(response.Body).ReadToEndAsync(); 
    response.Body.Seek(0, SeekOrigin.Begin);

    return $"Response {text}";
}

Finally, the Invoke which does the logging and jumps through some hoops to allow the response body to be read.

public async Task Invoke(HttpContext context)
{
    _logger.LogInformation(await FormatRequest(context.Request));

    var originalBodyStream = context.Response.Body;

    using (var responseBody = new MemoryStream())
    {
        context.Response.Body = responseBody;

        await _next(context);

        _logger.LogInformation(await FormatResponse(context.Response));
        await responseBody.CopyToAsync(originalBodyStream);
    }
}

As you can see the trick to reading the response body is replacing the stream being used with a new MemoryStream and then copying the data back to the original body steam. This works and is a concept I found in Sul’s blog post. I don’t know how much the affect performance and would make sure to study how it scales or just avoid using it in production as much as possible.

Wrapping up

This entry didn’t turn out anything like I expected. I came into this looking to do a very simple post due to some time restrictions and it turned into something larger. I hope you find it helpful. I didn’t do a full repo for this week’s post, but you can a gist with the middleware classes here.

Log Requests and Responses in ASP.NET Core Read More »

Email with ASP.NET Core Using Mailgun

Sending emails from ASP.NET Core using Mailgun is a topic I covered in this post almost a year ago. The previous post was before ASP.NET Core hit 1.0 and I didn’t save or upload the code to GitHub. Based on the comments on the post I decided to redo the post using the current version of ASP.NET.

Starting point

For this post, I created a new ASP.NET Core Web Application targeting .NET Core using Individual User Accounts for authentication. The project before any changes for email can be found here.

UI and Controller change to support email

The project template comes with all the UI and controller functions need to support email, but they are commented out. The following is going to walk through uncommenting the proper code.

Account controller

Starting with the Register function the code to send a confirmation email needs to be uncommented and the existing call to _signInManager.SignInAsync should be commented out to keep a user from being signed in before their email address has been confirmed. The following is after the changes.

var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", "Account", 
                             new { userId = user.Id, code = code }, 
                             protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
   $"Please confirm your account by clicking this link: 
     <a href='{callbackUrl}'>link</a>");
//await _signInManager.SignInAsync(user, isPersistent: false);

Next, in the Login function add a check to verify a user’s account has been confirmed before allowing them to sign in. The new code starts with var user = await _userManager.FindByNameAsync(model.Email); the code above it is just to provide context.

 public async Task<IActionResult> Login(LoginViewModel model, 
                                        string returnUrl = null)
 {
      ViewData["ReturnUrl"] = returnUrl;
      if (ModelState.IsValid)
      {
          var user = await _userManager.FindByNameAsync(model.Email);
          if (user != null)
          {
              if (!await _userManager.IsEmailConfirmedAsync(user))
              {
                  ModelState.AddModelError(string.Empty, 
                              "You must have a confirmed email to log in.");
                  return View(model);
              }
          }

Finally, in the ForgotPassword function uncomment the following to enable sending the user a password reset link.

var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.Action("ResetPassword", "Account", 
                             new { userId = user.Id, code = code }, 
                             protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Reset Password",
   $"Please reset your password by clicking here: <a          
     href='{callbackUrl}'>link</a>");
return View("ForgotPasswordConfirmation");
Forgot password view

To enabled the UI related to sending an email for a forgotten password open ForgotPassword.cshtml found in the Views/Account/ directory and uncomment the following.

<form asp-controller="Account" asp-action="ForgotPassword" 
      method="post" class="form-horizontal">
    <h4>Enter your email.</h4>
    <hr />
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Email" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Email" class="form-control" />
            <span asp-validation-for="Email" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
             <button type="submit" 
                     class="btn btn-default">Submit</button>
        </div>
    </div>
</form>

Warning for sites with existing users

The changes above will cause issues for any existing users since they will not have completed the email confirmation step keeping them from being able to log in or reset passwords. Manually marking existing users as confirmed can be done by updating the EmailConfirmed bit field to true in the AspNetUsers table.

Mailgun

Mailgun is an email service run by Rackspace that provides a simple API for sending emails. The free level of the service allows up to 10k emails to be sent a month.

You can sign up for an account here. Once logged in go to the Domains section.

Next, select your domain should only be one if you are on a new account. This will take you to a screen that looks like the following some of which will be needed to connect with the Mailgun API. I took the time to replace my information with a fake version so this screen shot could be referenced using the values from the screenshot for the rest of the post.

Configuration

Settings class

In order to hold and load Mailgun email related settings add a new EmailSettings class. In the sample project, this class can be found in the Configuration directory. The following is the full contents of the file.

public class EmailSettings
{
    public string ApiKey { get; set; }
    public string ApiBaseUri { get; set; }
    public string RequestUri { get; set; }
    public string From { get; set; }
}
User secrets introduction

User secrets is a concept in ASP.NET Core used to set configuration items and have them stored outside of the project so they will be excluded from version control. They are a great way to store private API key and related items which is why they will be used to store our Mailgun configuration items. I will be coving the basics here, but for a more detail explanation check out the official docs on the topic of app secrets.

Setting user secrets

In the Solution Explorer right-click on the project and select Manage User Secrets.

This will open the secrets.json file which will be used to store secrets related to the select project. Keep in mind this file is stored in your user directory in an unencrypted way so don’t view it as a secured store.

Based on the screenshot above from Mailgun’s domain detail page the json file would look like the following. The RequestUri is the only setting not pulled from the domain settings above and would just need fakesandbox replaced with the sandbox ID for your domain.

{
  "EmailSettings": {
    "ApiKey": "api:key-fakeapikey",
    "ApiBaseUri": "https://api.mailgun.net/v3/",
    "RequestUri": "fakesandbox.mailgun.org/messages",
    "From": "[email protected]"
  }
}
Loading user secrets in Startup

In the ConfigureServices function of the Startup class the EmailSettings section of our user secrets can be loaded and made available via the dependency injection system using the following line of code.

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

Not that user secrets are only meant to be used for development and for a production build of the applications the settings would need to be moved to a different location such as environment variables or Azure Key Vault.

Using Mailgun to send email

Not that the application has the email sending portion of the UI enabled the SendEmailAsync function of the AuthMessageSender class needs to be implemented. The class can be found in the MessageServices.cs file of the Services directory.

Injection of email settings

The first change needed is to add a class level variable to store email settings and to add a constructor that will allow the email setting to be injected.

private readonly EmailSettings _emailSettings;

public AuthMessageSender(IOptions<EmailSettings> emailOptions)
{
    _emailSettings = emailOptions.Value;
}
Sending an email

The body of the SendEmailAsync function is where the call to Mailgun’s API will be made using the email setting injected via the class’s constructor. The following is the full body of the function.

using (var client = new HttpClient { BaseAddress = 
                                     new Uri(_emailSettings.ApiBaseUri) })
{
    client.DefaultRequestHeaders.Authorization = 
      new AuthenticationHeaderValue("Basic",
    Convert.ToBase64String(Encoding.ASCII.GetBytes(_emailSettings.ApiKey)));

    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("from", _emailSettings.From),
        new KeyValuePair<string, string>("to", email),
        new KeyValuePair<string, string>("subject", subject),
        new KeyValuePair<string, string>("html", message)
    });

    await client.PostAsync(_emailSettings.RequestUri, 
                           content).ConfigureAwait(false);
}

The Mailgun API key is sent as an authentication header value with the rest of the parameters being sent via form URL encoded content. Finally, the Request URI from the email settings is used to send the post request to Mailgun.

If you just need to send a plain text instead of HTML the “html” key can be replaced with “text”.

Authorized recipients required for test domain

When using Mailgun with the default test domain note that only emails addressed to Authorized Recipients will be delivered. To add a recipient click Authorized Recipients button on Mailgun’s Domains page.

This will take you to the Authorized Recipients page where you can use the Invite New Recipient button to add a recipient.

Enter the email address you want to add and click the Send Invite button. After the email address is confirmed mail to that address will be delivered. Keep in mind this is only for test accounts and doesn’t have to be done when being used with a real domain.

Using logs to verify state of emails

During my testing, I wasn’t seeing emails come through and I thought something was wrong with my code, but it turned out that Mailgun was getting the request to send the mail they just hadn’t be processed yet. The Logs section of your Mailgun account is helpful for determining if they are getting your request to send an email or not.

As you can see in the screenshot the email request was accepted, but not yet delivered. It was 10 minutes later before the email was actually delivered. I am not sure if this delay is just for test domains or if would apply to live ones as well.

Other Email Options

Mailgun is obviously not the only option for sending emails. This post from Mashape lists 12 API providers. In addition SMTP is also an option which this post by Steve Gordon covers.

Wrapping up

The code finished code that goes with this post can be found here. Thank you to all the commenters on the original post for stepping in when I didn’t have all the answer or code available.

Email with ASP.NET Core Using Mailgun Read More »

Angular 2 with an ASP.NET Core API

This week’s post is going to take the Angular 2 application from a couple of weeks ago and add the same functionality currently present in the Aurelia application found the ASP.NET Core Basic repo. This release is the starting point for the solution used in this post.

Starting point overview

When you download a copy of the repo you will find an ASP.NET Core solution that contains three projects. The Angular project is where this post will be focused.

The Contacts project has a set of razor views and a controller to go with them that support standard CRUD operations, which at the moment is the best way to get contact information in the database. It also contains the ContactsApiController which will be the controller used to feed contacts to the Angular 2 and Aurelia applications.

Multiple startup projects in Visual Studio

In order to properly test the functionality that will be covered here both the Contacts project and the Angular project will need to be running at the same time. Visual Studio provides a way to handle this. The Multiple startup projects in Visual Studio section of this post walks through the steps of setting up multiple startup project. The walk through is for the Aurelia project, but the same steps can be applied to the Angular project.

Model

Create a contacts directory inside of ClientApp/app/components/ of the Angular project. Next create a contact.ts file to the contacts directory. This file will be the model of a contact in the system. If you read the Aurelia version of this post you will noticed that this model is more fully defined since this project is using TypeScript the more fully defiled model provides more type safety. The following is the contests file.

export class Contact {
    id: number;
    name: string;
    address: string;
    city: string;
    state: string;
    postalCode: string;
    phone: string;
    email: string;

    constructor(data) {
        Object.assign(this, data);
    }

    getAddress() {
        return `${this.address} ${this.city}, ${this.state} ${this.postalCode}`;
    }

}

Service

To isolate HTTP access the application will use a service to encapsulate access to the ASP.NET Core API. For the service create a contact.service.ts file in the contacts directory of the Angular project. The following is the code for the service.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Contact } from './contact';

@Injectable()
export class ContactService {

    constructor(private http: Http) {
    } 

    getAll(): Promise<Contact[]> {
        return this.http.get('http://localhost:13322/api/contactsApi/')
            .toPromise()
            .then(response => response.json())
            .then(contacts => Array.from(contacts, c => new Contact(c)))
            .catch(error => console.log(error));
    }
}

This class uses Angular’s HTTP client to access the API and download a list of contacts. Angular’s HTTP client uses reactive extensions and returns an observable. In this case we don’t need an observable so for this service the observable is being converted to a promise. Then from there the response from the API is being converted an array of type contact.

Also make note of the Injectable decorator which tells Angular 2 the class should be available for dependency injection.

View Model

The next step is to create a view model to support the view that will be used to display the contacts download from the API. Add a file named contactlist.component.ts to the contacts directory of the Angular project. The following is the full contents of the view model file. This will be followed by a breakdown of the file in order to highlight some parts of the file.

import { Component, OnInit } from '@angular/core';
import { Contact } from './contact';
import { ContactService } from './contact.service';

@Component({
    selector: 'contactlist',
    template: require('./contactlist.component.html'),
    providers: [ContactService]
})
export class ContactListComponent implements OnInit {
    contacts: Contact[];

    constructor(private contactService: ContactService) { }

    ngOnInit(): void {
        this.contactService.getAll()
            .then(contacts => this.contacts = contacts);
    }
}

The import statements are pulling in a couple parts of the Angular 2 framework in addition to the contact model and contact service created above.

Next is a component decorator which marks the class as an Angular component and provides a method to set metadata about the class.

@Component({
    selector: 'contactlist',
    template: require('./contactlist.component.html'),
    providers: [ContactService]
})

The selector property sets the identifier for the class to be used in templates. The template property sets the view that should be used with the view model. In this case it is requiring in another file, but it could also contain the actual template that should be used to render the component. An alternate is to use templateUrl to point to an external file containing a template. The final property used in this example is the providers  property which is a list of providers that the framework needs to be made available to the component, in this case the ContractService. For more information on the component decorator check out the Angular docs.

The next thing of note on this class is that it implements OnInit.

export class ContactListComponent implements OnInit

OnInit is one of Angular’s lifecycle hooks, see the docs for the rest of the available hooks. OnInit is called once after component creation and runs the ngOnInit function which in the case of this class is being used to get a list of contacts from the ContactService.

View

For the view create a contactlist.component.html in the contacts directory of the Angular project. This is the file that the veiw model created above is bound with to display the contact data retrieved from the API. The following is the complete contents of the view file.

<ul>
    <li *ngFor="let contact of contacts">
        <h4>{{contact.name}}</h4>
        <p>{{contact.getAddress()}}</p>
    </li>
</ul>

The second line repeats the li tag for each contact in the contacts array of the view model class. {{expression}} is Angular’s syntax for one way data binding. {{contact.name}} does a one way binding to the name property of the current contact in the *ngFor loop. For more details on the different options available for data binding see the docs.

Add menu

The final piece is to add an item to the menu from with the contact list can be accessed. Open app.module.ts in the ClientApp/app/components/ directory. Add an imports for the ContactListComponent.

import { ContactListComponent } from './components/contacts/contactlist.component';

Next add a new path to the RouterModule. The third from the bottom is the line that was added for the contact list.

RouterModule.forRoot([
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent },
    { path: 'counter', component: CounterComponent },
    { path: 'fetch-data', component: FetchDataComponent },
    { path: 'contact-list', component: ContactListComponent },
    { path: '**', redirectTo: 'home' }
])

Finally open the navmenu.component.html file in the ClientApp/app/components/navmenu/  directory. Add a new li for the contact list matching the following.

<li [routerLinkActive]="['link-active']">
    <a [routerLink]="['/contact-list']">
        <span class='glyphicon glyphicon-list-alt'></span> Contact List
    </a>
</li>

Wrapping up

That is all it takes to consume some data from an ASP.NET Core API and use it in an Angular 2 application. I can’t stress enough how easy working with in the structure provided by JavaScriptServices helped in getting this project up and going quickly.

The completed code that goes along with this post can be found here. Also note that the Aurelia project has be redone as well also based on JavaScriptServices and TypeScript so that the applications will be easier to compare.

Angular 2 with an ASP.NET Core API Read More »

Migration from ASP.NET Core 1.0.x to 1.1

UPDATE: For a guide dealing with the conversion to csproj/Visual Studio 2017 check out this post.

On November 16th .NET Core 1.1 was released including ASP.NET Core 1.1 and Entity Framework 1.1. Each of the links contain the details of what was including in the 1.1 release. Unlike some of the previous migrations this is pretty simple.

I will be using my normal ASP.NET Basics solution for this upgrade. The examples will be out of the Contacts project. This post is coming out of order so the repo that goes with this post will contain some items not covered in posts yet. The starting point of the repo can be found here.

Installation

Make sure you already have Visual Studio 2015 Update 3 installed with .NET Core 1.0.1 tools Preview 2 installed. If not use the previous links to install the needed versions. Next head over to the download page for .NET Core and under All downloads and select Current and SDK and select the download for your OS.

downloaddotnet

Another option is to install Visual Studio 2017 RC which can be found here.

Project.json

Project.json is the file that contains all the versions of assembles used by the application. A couple of items need to edited by hand and the rest can be updated using NuGet UI or you can change them all by hand if you like.

First the by hand items. The platform version needs to be updated to 1.1.

Before:
"Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    }

After:
"Microsoft.NETCore.App": {
      "version": "1.1.0",
      "type": "platform"
    }

The second by hand item is the net core app version in the frameworks section.

Before:
"frameworks": {
  "netcoreapp1.0": {
    "imports": [
      "dotnet5.6",
      "portable-net45+win8"
    ]
  }

After:
"frameworks": {
  "netcoreapp1.1": {
    "imports": [
      "dotnet5.6",
      "portable-net45+win8"
    ]
  }

Here is the resulting dependencies and tools sections.

"dependencies": {
  "Microsoft.NETCore.App": {
    "version": "1.1.0",
    "type": "platform"
  },
  "Microsoft.AspNetCore.Authentication.Cookies": "1.1.0",
  "Microsoft.AspNetCore.Diagnostics": "1.1.0",
  "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.1.0",
  "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.0",
  "Microsoft.AspNetCore.Mvc": "1.1.0",
  "Microsoft.AspNetCore.Razor.Tools": {
    "version": "1.1.0-preview4-final",
    "type": "build"
  },
  "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
  "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
  "Microsoft.AspNetCore.StaticFiles": "1.1.0",
  "Microsoft.EntityFrameworkCore.SqlServer": "1.1.0",
  "Microsoft.EntityFrameworkCore.SqlServer.Design": {
    "version": "1.1.0",
    "type": "build"
  },
  "Microsoft.EntityFrameworkCore.Tools": {
    "version": "1.0.0-preview3-final",
    "type": "build"
  },
  "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
  "Microsoft.Extensions.Configuration.Json": "1.1.0",
  "Microsoft.Extensions.Configuration.UserSecrets": "1.1.0",
  "Microsoft.Extensions.Logging": "1.1.0",
  "Microsoft.Extensions.Logging.Console": "1.1.0",
  "Microsoft.Extensions.Logging.Debug": "1.1.0",
  "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
  "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.1.0",
  "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
    "version": "1.1.0-preview4-final",
    "type": "build"
  },
  "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
    "version": "1.1.0-preview4-final",
    "type": "build"
  },
  "BundlerMinifier.Core": "2.2.301"
},

"tools": {
  "BundlerMinifier.Core": "2.2.301",
  "Microsoft.AspNetCore.Razor.Tools": "1.1.0-preview4-final",
  "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final",
  "Microsoft.EntityFrameworkCore.Tools": "1.1.0-preview4-final",
  "Microsoft.Extensions.SecretManager.Tools": "1.1.0-preview4-final",
  "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
    "version": "1.1.0-preview4-final",
    "imports": [
      "portable-net45+win8"
    ]
  }
}

Make note that using the NuGet UI will update the dependencies but not the tools section. For some reason the tools section doesn’t seem to have intellisense so I ended up searching the NuGet site to find the new versions. If you do end up changing the tooling version I recommend doing a dotnet restore in the project directory from the command prompt to ensure the proper versions get downloaded.

Wrapping up

As I said this was a really pain less migration. Make sure you check out the release pages ( .NET Core 1.1, ASP.NET Core 1.1 and Entity Framework 1.1) for the details on what has changed. For example ASP.NET Core has gotten significant performance increases with this release as well as URL Rewriting Middleware and Response Caching Middleware.

It has been less than six months since the initial release of ASP.NET Core until the 1.1 release which a huge increase in the pace of releases compared regular ASP.NET. From what I have see this is a pace the team will continue. Check out the roadmap for a preview of things coming in 1.2.

The code in its final state can be found here.

Migration from ASP.NET Core 1.0.x to 1.1 Read More »

Aurelia with an ASP.NET Core API

In last week’s post I covered creating a new ASP.NET Core project and then adding in Aurelia. The Aurelia application did nothing except output hello world. This week I am going to take an existing contacts API and the Aurelia project from last week use them together to make the Aurelia application display the name of the contacts from the API.

Part 1 – Add Aurelia to an ASP.NET Core Project
Part 2 – Aurelia with an ASP.NET Core API (This Post)
Part 3 – Aurelia with an ASP.NET Core API: Modeling and Displaying Data in Aurelia
Part 4 – Aurelia with ASP.NET Core: Host Aurelia from a Controller
Github repo with the code for all of the parts with a release to go with each post

Starting point overview

When you download a copy of the repo you will find an ASP.NET Core solution that contains two projects. The Aurelia project, obviously, contains the Aurelia application.

The Contacts project has a bit more going on. It has a set of razor views and a controllers to go with them that support standard CRUD operations, which at the moment is the best way to get contact information in the database. It also contains the ContactsApiController which will be the controller used to feed contacts to the Aurelia application.

Multiple startup projects in Visual Studio

In order to test this application both the Contacts and Aurelia projects to startup when the solution is run. Visual Studio provides an easy way to accomplish this. In the Solution Explorer window right click on the Solution and click Set StartUp Projects.

sestartup

This will launch the Solution Property Pages dialog. Looks for the Startup Project page under Common Properties.

multiplestartupprojects

Match the screenshot above by selecting the radio button for Multiple startup projects. Then using the arrows on the right to make sure that Contacts project will start first. Also set the Action on Contacts to be start without debugging since that project will just be feeding data and won’t need to be debugged at the moment.

Then on the Aurelia project set the Action to Start. Click OK and now both projects will start up when solution is run from Visual Studio.

Accessing Data from the API

In order to get data from the API we will need away to talk HTTP from Aurelia. Aurelia provides two libraries that provide this functionality which you can read about here. For this post I will be using Aurelia’s fetch client which based on the experimental Fetch API. The Fetch API isn’t supported by all browsers at point so if you need it there a polyfill can be found here.

Installing the Aurelia Fetch Client

If you started with the project from GitHub repo linked about then the fetch client will already be included in the projects dependencies, but if not I wanted to cover getting it installed. Using a command prompt run the following npm command in the project’s directory.

npm install aurelia-fetch-client -save

Alternately add the following line to the dependencies section of the project’s package.json file and when the file is saved Visual Studio will automatically restore the new package.

"aurelia-fetch-client": "^1.0.0"

The last step to making sure the fetch client available in the client application is to make sure it is included in the vendor-bundle.js that is created by the Aurelia CLI’s build process. To do this open the aurelia.json file found in the aurelia_project folder. In the bundles section look for the bundle named vendor-bundle.js and in its dependencies section add “aurelia-fetch-client”. The following an abbreviated example from my file to to make it clear where the new line should go.

"name": "vendor-bundle.js",
"prepend": [
  "node_modules/bluebird/js/browser/bluebird.core.js",
  "wwwroot\\scripts/require.js"
],
"dependencies": [
  "aurelia-binding",
  "aurelia-bootstrapper",
  "aurelia-dependency-injection",
  "aurelia-event-aggregator",
  "aurelia-fetch-client",

Create a client side service

It is important to not spread HTTP across the whole application and in order to achieve this goal it is a good idea to create a service that encapsulates the HTTP actions. For this example a contact service will be created that will handle all interactions with the ASP.NET Core API and the rest of the Aurelia application will just interact with the contact service.

To start create a services folder inside the src folder which contains the Aurelia client side application and added a new file to contain the new service called contactService.js.

nfcontactservice

The contact service will use the Aurelia fetch client to get all the contacts from the ASP.NET Core API. To do so it needs a constructor to allow injection and configuration of a HTTP client as well as a single function to get all the contacts. The following is the complete service.

import { HttpClient } from 'aurelia-fetch-client';

export class ContactService {
    static inject() { return [HttpClient] };

    constructor(http) {
        this.http = http;

        this.http.configure(config => {
            config
                .useStandardConfiguration()
                .withBaseUrl('https://localhost:13322/api/contactsApi/');
        });
    }

    GetAll() {
       return this.http.fetch('')
            .then(response => response.json())
            .catch(error => console.log(error));
    }
}

A future post will come back to this code and make it more robust, but this post is just about getting data for the Aurelia application so the service is being kept as simple as possible.

Using the Contact Service

Again to keep the code as simple as possible the contact servers will be utilized directly in existing the existing app.js file. The following is the class before any changes.

export class App {
  constructor() {
    this.message = 'Hello World!';
  }
}

The following is the class after the changes to import and inject the contact service via the constructor as well as using the contact service to download and show the name of each contact.

import { ContactService } from './services/contactService';

export class App {
    static inject() { return [ContactService] };

    constructor(contactService) {
        this.message = 'Hello World!';
        contactService.GetAll()
            .then(result => {
                this.message = `Contact Results: 
                                ${result.map((contact) => contact.name)}`;
            });
    }
}

Does it work?

At this point I used Visual Studio to launch both projects. In the Aurelia MVC application I navigated to http://localhost:37472/index.html which is the page that contains the Aurelia client application. Instead of being greeted by a list of contact names the application output “Hello World!”. That means that the Aurelia client application was running, but the contact service had failed for some reason. The console in the Chrome developer tools show the following error.

Fetch API cannot load http://localhost:13322/api/contactsApi/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:37472’ is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

The work around

Turns out that having two projects caused an issue I hadn’t considered. I now have to worry about cross-origin resource sharing. Not a topic that will be covered in this post. In order to work around this issues the Contacts project can be changed to added the following to the Configure function of the Startup class.

app.UseCors(builder =>
    {
        builder.AllowAnyHeader();
        builder.AllowAnyMethod();
        builder.AllowAnyOrigin();
    }
);

I am in no way saying that the above is the proper way to fix this issue. CORS is a subject I haven’t dug in to yet. The above is only meant to get this sample working. Please make sure to locate other resources on CORS for anything that is more than a demo.

Final thoughts

Running at this point will return the names of contacts as expected. Future posts will expand this application more. I want to get Angular 2 up as a new project in this same solution. When this solution has projects that contains the basics for MVC/razor, Aurelia and Angular 2 it will be in a good replacement the ASP.NET SPAs comparison reference application. Having each type of front end in a different project should make it easier to follow how each is set up. The code for today’s post can be found here.

Aurelia with an ASP.NET Core API Read More »

Create a .NET Standard Library for use with Full .NET Framework

Updated version for Visual Studio 2017 can be found here.

Recently I needed to create a library that would be shared between an UWP application and a Winforms application. My first thought was to create a portable class library with a profile that covered .NET 4.5.1 and Windows 10 which actually works out to be Profile44. At some point I was reminded of the new .NET Standard Library and decided that would be a better option.

.NET Standard Library

The .NET Standard Library specifies what .NET APIs are available based on the version of the .NET Standard Library being implemented. The following is a comparison to portable class libraries that really helped me understand the difference. This was pulled form the .NET Standard Library link above.

.NET Standard Library can be thought of as the next generation of Portable Class Libraries (PCL). The .NET Standard Library improves on the experience of creating portable libraries by curating a standard BCL and establishing greater uniformity across .NET runtimes as a result. A library that targets the .NET Standard Library is a PCL or a “.NET Standard-based PCL”. Existing PCLs are “profile-based PCLs”.

The .NET Standard Library and PCL profiles were created for similar purposes but also differ in key ways.

Similarities:

  • Defines APIs that can be used for binary code sharing.

Differences:

  • The .NET Standard Library is a curated set of APIs, while PCL profiles are defined by intersections of existing platforms.
  • The .NET Standard Library linearly versions, while PCL profiles do not.
  • PCL profiles represents Microsoft platforms while the .NET Standard Library is agnostic to platform.

.NET Standard Library Project Type?

Since I need to use my library in a winforms and UWP applications I need to create a csproj based library and not a xproj based library. This part of the process that took me the longest to figure out. Thankfully this Stack Overflow post helped clear up what is required. Basically if any of your projects need to use msbulid (which both winforms and UWP do) then your library should be csproj based.

Create a Portable Class Library

For csproj based .NET Standard library we must start with a Portable Class Library project type. To start click File > New Project which shows the New Project dialog.

nsnewproject

Locate the Class Library (Portable) type of project. Here I am using the C# version. Click OK. Next the Add Portable Class Library dialog will be shown.

nsaddpcl

Since this well be converted to use .NET Standard your selections don’t mean much here, but you will have to keep your target platforms when selecting which version of the .NET Standard your library will support. Click OK and the project will be created.

Convert a Portable Class Library to .NET Standard

Right click on your project and select properties. Alternately select the project in Solution Explorer and use the Project > [Project Name] Properties menu.

nsprojectpropertiesmenu

In project properties on the Library tab there is a link for Target .NET Platform Standard in the Targets section just below the Change button. Click the link.nsprojectpropertiesThis will show a warning message about saving changes and that the available APIs could change. Click yes to continue.

nstargetwarning

This will return you back to the library page of the project’s properties with the PCL related options replaced with a drop down used to select the version of the .NET Standard you want your library to target. I am going with version 1.2 based on where I need my library to run. Use the .NET Platform Support section of this page to help you decided on the proper version of the .NET Standard for your library.

nsselectversion

Save the project and it will now produce a .NET Standard library when built!

.NET CLI

It is hidden by default, but if you show all file you will see that the project now contains a project.json file which means the project can be used by the .NET CLI. Open a command prompt in the project directory. The following command can be used to build the project.

dotnet build

Or if you would like to create a Nuget package you can use the following.

dotnet pack

Inspecting the resulting dll in dotPeek

Just out of curiosity I wanted to see what showed when I opened up my .NET Standard library using a decompiler. I used dotPeek which is a free .NET decompiler created by JetBrains the company behind ReSharper.

As you can see in the following screenshot the platform shows as .Net Framework v4.6.1.

nsdotpeek46

Now here is a screenshot of the same library on a computer with an older version of .NET and it show a platform of .Net Framework v4.0.

nsdotpeek40

For some reason I was surprised by the fact the platform changed, but when I thought about it more I realized how else could it work because the library isn’t build to a specific platform. Seeing the platform change for the same library between two different machines really solidified how awesome the .NET Standard is.

Caution

As I said before I was hoping to use a .NET Standard library between a winform and UWP application. I did all the thing above and things were looking great. I added a project reference to my UWP application in Visual Studio 2015 with no trouble. Unfortunately the winforms application is stuck on Visual Studio 2013 (due to performance issue, 2015 is painfully slow with this solution) and Visual Studio 2013 doesn’t support this project type making a project reference impossible.

I could have gotten the library to work by adding it to the winforms solution as a Nuget reference, but for this project that was not a viable solution.

Create a .NET Standard Library for use with Full .NET Framework Read More »

Add Aurelia to an ASP.NET Core Project

In this post I am going to add a new project to the my existing ASP.NET Core Basics solution which can be found in this repository. The new project will be MVC 6  to which I will add in Aurelia. With both ASP.NET and Aurelia now being at RTM I thought this would be a good time to cover getting a new project setup.

Over time the ASP.NET Core Basics repo used in this post is going to be replacing my ASP.NET Core SPAs repo based on some feedback that having Aurelia and Angular 2 in the same project made it harder to see how each individual framework is setup.

Part 1 – Add Aurelia to an ASP.NET Core Project (This Post)
Part 2 – Aurelia with an ASP.NET Core API
Part 3 – Aurelia with an ASP.NET Core API: Modeling and Displaying Data in Aurelia
Part 4 – Aurelia with ASP.NET Core: Host Aurelia from a Controller
Github repo with the code for all of the parts with a release to go with each post

 Adding a new project to an existing solution

To add a new project to the existing solution right click on the solution and then click Add > New Project.

AddProjectExistingSolution

On the Add New Project dialog select ASP.NET Core Web Application (.NET Core), enter a name and then click OK.

AddNewProjectDialog

On the New ASP.NET Core Web Application (.NET Core) dialog select Web Application. This application doesn’t need authentication so leave it set to No Authentication. Finally click OK.

NewASPNetCoreWebApplication

After a few seconds the project creation will complete and the solution will contain two projects. The existing Contacts project that contains both a razor/normal implementation of a contacts list as well as an API implementation. The second project is the newly created Aurelia project.

SolutionWithTwoProjects

Changing the startup project

Notice in the screenshot above that the Contacts project is in bold. This means that the Contacts project is set as the startup project and it will be the project that starts when the application is run (F5 or Cntrl + F5). In this post we will just be working with the Aurelia project so we need to make it the startup project. To do this right click the Aurelia project and select Set as StartUp Project.

SetAsStartupProject

Now if you hit F5 the Aurelia project will run. Visual Studio provides a lot of flexibility around which projects start up. You can select a single, have which ever project you have to have select, or even multiple projects.  In a later post we will need both projects to start up and I will cover that when we have the need.

Install the Aurelia CLI

Make sure you have a minimum of NodeJs 4.x or above installed. If you need the installer it can be found here. After the install is complete open a command prompt and run the following command to install the Aurelia CLI.

npm install aurelia-cli -g

Add Aurelia to existing ASP.NET Core Project

In a command prompt navigate to the folder that contains the xproj file for the ASP.NET Core project created above. Now the Aurelia CLI can be used to setup a new Aurelia project at the current location using the following command.

au new --here

There will be a series of prompts the first of which is the selection of which platform to use. Select the option for ASP.NET Core (option 2). I used the defaults for most of the remaining prompts. The exception was for unit testing which I selected no on just to keep the project simpler not because I think testing is a bad idea.

When the Aurelia CLI finishes its file creation and dependency restore your project will contain the highlighted new files and folders.

auaddedfiels

Notice that I have a warning on Dependencies that something is not installed. There is a quirky issue with Visual Studio that Scott Hanselman has blogged about here. He goes in to a good bit of detail about what is going on as well as suggesting a work around. It has to do with npm and not being about to restore an optional package that isn’t meant for Windows machines.

gulp

The Aurelia CLI creates a set of tasks to help with building, transpiling the Aurelia part of the applications. I wrote a couple of posts over the couple few weeks dealing with converting a project to use glup as well as how to get gulp working with ES 2015.

I am going to cover the abbreviated version of those two post here. Add a new file called gulpfile.babel.js in the root of the project, where your project.json is located. The Aurelia CLI added all the needed items in the devDependencies section of package.json.

gulp no go

At this point I attempted to include the tasks under aurelia_project/tasks using require(‘require-dir’)(‘aurelia_project/tasks’);. This failed completely. I couldn’t get any of the items in the tasks folder to show up. I am not sure why this didn’t work. My best guess is that the tasks in the tasks folder are exporting gulp.series and not gulp.task. I just don’t know enough about gulp at this point to now how to fix/work around this or if what I am trying to do is just not the right way it should be used.

The gulp work around

I spent more time that I would have like working on getting gulp to pick up the items in the tasks folder, but I don’t want to have to run a CLI command every time I do a build to make sure all the Aurelia related files are up to date. As a work around I decided to add a gulp task to invoke the CLI command for me.

To start open package.json  and add the following to the devDependencies section which allows shell commands to be run from gulp.

"gulp-shell" :  "0.3.0"

Next in gulpfile.babel.js added the proper imports and created tasks for the CLI commands I wanted to run. In the case I am just showing the build command.

import gulp from 'gulp';
import shell from 'gulp-shell';

gulp.task('bulid', shell.task(['au build']));

Using the Task Runner Explorer this task can now be set to run after a build of the MVC project.

treafterbuild

This accomplishes what I wanted, but it feels like a hack. If anyone knows a better way please let me know.

It’s Alive!

At this point if you run the application it will go to the normal default home page that gets created by the Visual Studio template. For me that address is http://localhost:37472/. From there if you add index.html, the full address is http://localhost:37472/index.html, you will be invoking the Aurelia application.

At this point all you will see is “Hello World!”. Not that impressive I know, but it is a starting point that we will build on in future posts.

The associated code can be found here.

Add Aurelia to an ASP.NET Core Project Read More »