Testing EF Core Repositories with xUnit and an In Memory Db

I came across the EF Core In Memory database recently. It obviously won’t have all the features of a relational database but it might be useful when unit testing simple repository methods.

Let’s take it for a spin …

Starting point

We have the following repository that we want to test. We’re just going to test the Add method in this post:

Here’s the EF data context and models behind our repository:

xUnit

So, let’s bring in xUnit by adding the following entries into project.json:

We also need to tell Visual Studio that xUnit is going to be our test runner by setting the following as a root property in project.json as well:

Now we can start adding xUnit tests. Let’s just add a couple of simple tests to double check xUnit is wired up properly. Let’s add the following class containing a test that should pass and a test that should fail:

If we open up Test Explorer you’ll see our tests and if you run them, 1 should pass and should 1 fail.

As a bonus, you can also run these tests from the command line by browsing to the app’s folder and running the following command:

Again, you should see 1 passing and 1 failing test.

In Memory Database

Before we test our repository, let’s bring in the In Memory database into our solution by adding the following dependency in project.json:

Repository Tests

So, let’s start testing our Add method in our repository by creating a class and a method to test the storyline when a person has no email address:

GetInMemoryPersonRepository is a method that all our tests will use to spin up a PersonRepository containing no data. Line 26 tells our data context to use the In Memory database. Lines 29 and 30 ensures we have a new database with no data in it.

The test is straight forward. Lines 6-12 creates a repository and a person with no email address. Line 14 calls the Add method in our repository passing in the person. Lines 16-19 carry our checks.

If you run the tests, all should be good.

Now, let’s add a couple more tests to test adding a person with single and multiple email addresses:

The tests are straightforward, following the same structure as the 1st test, using GetInMemoryPersonRepository to spin up a PersonRepository with an In Memory database behind it.

If you run the tests, all should be good.

The tests are also quick – on my machine the three tests took 7, 13 and 624 ms.

Connect with me:RSSGitHubTwitterLinkedIn

Getting Started With EF Core Migrations

Entity Framework (EF) migrations are a way to modify the database through different iterations of the software. Let’s have a play with these in EF Core in a web API project …

Models

Lets start with the following simple models to hold data about people:

Adding Entity Framework

Now let’s add EF to our solution in project.json (I’m still using .NET core 1.0):

DataContext

Let’s add the following data context:

Wiring EF up

To wire the app up to EF, first let’s add the following line to Startup.ConfigureServices:

We then need to add the following line in appsettings.json:

First migration

So, let’s have a go at our first migration …

Open a command prompt, browse to your solution directory and enter the following command:

After a second or so, our first migration will have been created in a Migrations folder in our solution:

Let’s have a look in the *_init.cs file. Cool, I can see an Up() method creating the 3 database tables and a Down() method droping the 3 tables. So, we have code that is going to create our schema which we can nicely source code control.

Let’s have a look at the PersonDataContextModelSnapshot.cs. As the name suggests, this looks like a copy of the schema – to faciliate the next migration generation.

But what will the generated migration SQL look like? Go back to the command prompt and enter:


The SQL will be output to the screen (you can output to a file by using the command dotnet ef migrations script -o {filename}).

The script creates a table called __EFMigrationsHistory which I didn’t create in my model. This will hold the list of migrations. You can see it adding our *_init migration at the bottom of the script.

I like that the primary keys have been correctly implemented as identities in the script. I like the foreign keys … I’m not liking the varchar(max) all over the place though!

Let’s fix the varchar(max) problem by adding the following code into PersonDataContext which specifies table names, field lengths and required fields in our schema:

So, let’s see what the script looks like now. First we need to remove our last migration by entering the following command:


You’ll notice the Migrations folder is now empty in our Visual Studio solution.

Now run the following command to generate the new migration and output the SQL script:

That’s much better!

Creating the database

So, let’s create the database by running the following command:


After a few seconds, the database will have been created. You should be able to see the database in Visual Studio in the SQL Server Object Explorer

Second migration

Now, let’s implement a model change. We’re going to add a Created property to our Person model:

Let’s create that migration:

If you open up *_Person_Created.cs you’ll see the migration to add our new column.

Before updating our database again, let’s check our SQL migration script. We need to specify the migration we want to start from which in my case in 20170125045706_init:

This looks good.

Updating the database

So, let’s update the database by running the following command:


After a few seconds, the column will have been added to the database:

Connect with me:RSSGitHubTwitterLinkedIn

Getting the right version of TypeScript in a Visual Studio ASP.NET Core Project

I’m building an ASP.NET Core Angular 2 app. I think I’m using the latest version of TypeScript (2.1 at the moment) but I’m not sure …

If I open a command prompt and type:

it gives me:

So, great, my app must be using the 2.1?

Let’s check this by writing some 2.1 code:

Visual Studio complains straight away, putting a red squiggly line under the ...‘s. If you hover over the complaints, you get a tooltip saying “property assignment expected“.

Lets try running the app. It runs perfectly fine with mergedPerson correctly outputted to the console.

What’s going on? The visual studio compiler must be using a different version of TypeScript.

For classic ASP.NET projects, TypeScriptToolsVersion in csproj used to define the TypeScript version but that is no longer the case in ASP.NET core. In ASP.NET Core, this appears to be defined in a file called Microsoft.TypeScript.targets at C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\TypeScript:


So, this makes sense – Visual Studio appears to be using v1.8 (line 4).

Unfortunately, simply changing the 1.8 to 2.1 didn’t work for me.
I looked in my C:\Program Files (x86)\Microsoft SDKs\TypeScript directory. I only had a folder for 1.8.

Visual studio was obviously missing something, so, I downloaded and installed the latest version of TypeScript for Visual Studio.

Voila! The red squiggly lines disappeared in Visual Studio, my app still ran fine and the version references in C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0\TypeScript\Microsoft.TypeScript.targets has been upgraded to 2.1.

Connect with me:RSSGitHubTwitterLinkedIn

Enforcing HTTPS in ASP.NET Core

Enforcing ASP.NET Core web apps to use HTTPS is a little different to how you used to do it in previous versions of ASP.NET …

Setting HTTPS Up in Dev

Setting HTTPS up on our development version is simple. Just open the project properties, go to the Debug section, make sure you are running under IIS Express and tick Enable SSL.

Now, you should be able to run the app using the HTTPS URL.

The first time you navigate to the URL you’ll get a warning because the certificate is self-signed. You can however nagivate past this warning to the app’s home page:

Using middleware to enforce HTTPS

Our web app still doesn’t force users to use the HTTPS URL though. In my example, I can still browse to the web app via http://localhost:36313/.

We can force use of the HTTPS URL in ASP.NET Core’s middleware pipeline using the following code in startup.cs in the Configure method. Lines 17-28 is where we redirect if the URL is not HTTPS.

However, when we run the app we get the following error.:

This is because the HTTP and HTTPS ports are different and we haven’t taken that into consideration in our code.

Now, for development, the SSL port is stored in launchSettings.json (under the Properties folder in Visual Studio) under iisSettings > sslPort.

We can retreive this setting using the following code:

The redirect URL can then be built up as follows:

So, here’s our final pipeline code:

Connect with me:RSSGitHubTwitterLinkedIn

Taking Stripe Payments with Angular 2 and ASP.NET Core

Stripe is a service that allows you to very easily take payments online. In this post, I’ll go through how to take a payment via stripe using an Angular 2 frontend and an ASP.NET Core backend.

Sign up to Stripe

Firstly, we need to sign up for a stripe account. You can signup for a free test account here

After you have signed up, we need the Secret and Publishable keys. You can get these from Your account > Account settings > API Keys

Frontend Page

Let’s build the frontend first, using an Angular 2 component.

We are going to use stripe checkout which is super easy to implement and protects us from any PCI headaches (as long as our site runs on HTTPS).

First, we need to add a reference to the standard stripe checkout JavaScript in our server side ASP.NET Core view (line 3). This adds the global variable StripeCheckout which we’ll reference in our angular component. Note that we can not add this script into our angular component template because angular will remove it.

Now let’s add our angular payment component …

Here’s the simple markup (referencing bootstrap classes) which allows a user to buy 3 products, a T-shirt, some trainers or some jeans. Each button will invoke a function in our component code to take the payment via stripe. We show whether the payment has been successful or not in the last div in the markup, referencing a property called takePaymentResult.

Our component code is below …

Our 3 button handlers at are the bottom of the code and simply call into openCheckout() passing the product name, amount (in pence) and a callback to get invoked when we receive a token from stripe.

openCheckout() references the global variable StripeCheckout from checkout.js. Firstly we configure StripeCheckout, passing our publishable key and then we open the stripe payment form passing in our product and amount for the transaction.

After the user enters their credit card details and presses the Pay button, these details will be sent to stripe to initiate the payment. Stripe will then return a token and our callback (takePayment()) will be invoked.

takePayment() will call our ASP.NET Core API (/api/stripepayment) using angular’s http service. This is where the stripe payment will be processed – we’ll implement this in a minute.

The status from the /api/stripepayment API response is put in takePaymentResult which will be presented in the UI by angular.

Web API

OK, on to our web API that processes the stripe payment …

First, we need to bring in stripe.net via nuget – it makes processing the payment very simple.

Below is the full API controller and the API request model, StripePaymentRequest

First we tell stripe our secret key (line 7). We then setup the stripe charge object, setting the token, amount and description (to the product name). We also set our payment reference in the MetaData dictionary so that we tie the payment in our app to the payment in stripe.

The charge is then made and the result (which includes whether the payment has been successful) is passed back down in the response.

Test it!

You can test different scenarios using stripe’s test credit card numbers here.

Connect with me:RSSGitHubTwitterLinkedIn

Calling an ASP.NET Web API from jQuery

I’ve been playing with ASP.NET Core Web API recently … here’s a quick post on calling one of these APIs using jQuery Ajax …

Creating the API

The API is going to allow clients to:

  • get a list of people
  • get a single person
  • create a new person

Here’s the very simple person model:

For simplicity, I’m going to use a hardcoded list of people and not going to persist the people in a database. Here’s the API controller constructor and the hardcoded list:

The action method in PersonController to get the list of all the people is very simple:

The action method in PersonController to get a single person is below. The person id will be passed in from the URL path. We return the “Not Found” HTTP status code if the id isn’t in our hardcoded list and the JSON represenation of the found person if it does exists.

The action method in PersonController to create a person is below. The person object is passed in from the HTTP body that has been posted. If the body is missing we return a “Bad Request” HTTP status code. If we do have a person object from the HTTP body then the person id is generated, the person is added to the hardcoded list and we return a “Created” HTTP status code with the person in the response body containing the generated person id.

As well as dealing with returning the HTTP status code and the response body, the call to CreatedAtRoute(), also sets the Location HTTP header to the URL that the client could use to request the person just created. This is the reason for the Get action method having the GetPerson name parameter in the attribute and being referenced as the first parameter in CreatedAtRoute().

Creating the frontend page

Below is the HTML markup (referencing bootstrap CSS classes) that allows the user get a list of people:

Below is JavaScript for the getPeople button click handler. We use $.ajax() to call our person API. It is important to set contentType to application/json or our API won’t be reached. We put the names of the people returned in a pipe delimited list into the getPeopleResult textbox if the API call is successful.

Below is the HTML markup (referencing bootstrap CSS classes) that allows the user to get a single person:

Below is JavaScript for the getPerson button click handler. The code is very simular to the getPeople button click handler except it calls the API to get a single person and outputs the single person’s name in the getPersonResult textbox.

Below is the HTML markup that allows the user to create a person:

Below is JavaScript for the create button click handler. Again we use $.ajax() to call our person API but this time we POST to it. We create an object literal containing the name and email of the person and use JSON.stringify() so this can be passed into the data option in $.ajax(). We set whether the operation has been successful in the postResult textbox along with the generated person id. It is worth noting that the data in the success callback is the original data and not the data in the response. The response body can be obtained from jqXHR.responseText.

Connect with me:RSSGitHubTwitterLinkedIn