Create a RESTful API with authentication using Web API and Jwt

Published on March 15, 2016 in .NET, C#, Entity Framework · Read time 23 minutes

Web API is a feature of the ASP .NET framework that dramatically simplifies building RESTful (REST like) HTTP services that are cross platform and device and browser agnostic. With Web API, you can create endpoints that can be accessed using a combination of descriptive URLs and HTTP verbs. Those endpoints can serve data back to the caller as either JSON or XML that is standards compliant. With JSON Web Tokens (Jwt), which are typically stateless, you can add an authentication and authorization layer enabling you to restrict access to some or all of your API. The purpose of this tutorial is to develop the beginnings of a Book Store API, using Microsoft Web API with (C#), which authenticates and authorizes each requests, exposes OAuth2 endpoints, and returns data about books and reviews for consumption by the caller. The caller in this case will be Postman , a useful utility for querying API’s. In a follow up to this post we will write a front end to interact with the API directly. Set up Open Visual Studio (I will be using Visual Studio 2015 Community edition , you can use whatever version you like) and create a new Empty project, ensuring you select the Web API option…

Entity Framework - Use a Guid as the primary key

Published on July 13, 2014 in Entity Framework · Read time 2 minutes

Using a Guid as your tables primary key, when using Entity Framework, requires a little more effort than when using a integer. The setup process is straightforward, after you’ve read/been shown how to do it. The process is slightly different for the Code First and Database First approaches. This post discusses both techniques. Code First Using a Guid as the primary key when taking the code first approach is simple. When creating your entity, add the DatabaseGenerated attribute to your primary key property, as shown below; Entity framework will create the column as you would expect, with a primary key and data type. [ Database First The database first approach follows a similar line to the code first approach, but you’ll have to manually edit your model to make it work. Ensure that you edit the primary key column and add the or function as the default value before doing anything. Next, open you EDMX diagram, select the appropriate property and open the properties window. Ensure that StoreGeneratedPattern is set to identity. [ Important Note: Your Guid field MUST be a primary key, or this does not work. Entity Framework will give you a rather cryptic error message! Summary…

Quick look - Add indexes to tables with Entity Framework 6.1 Beta 1

Published on February 26, 2014 in Entity Framework · Read time 1 minutes

At the time of writing, beta 1 of Entity Framework 6.1 has recently been released. This is mostly a maintenance release , however, there are several new feature of note, including the ability to add indexes using a new data annotation when developing using the code first approach. Add indexes using the Index attribute To add an index, simply add the Index attribute as required; A quick look in SQL Server Management studio reveals that the index has been added for us. The key created was non-unique, non-clustered. There are overloads available to override these defaults; Which results in a unique index as shown below; Summary This is a fantastic new feature for potentially improving the performance of your code first applications by reducing the time required to query data. You can add indexes to your database using the attribute, and override the default and settings to get the index best suited to your scenario.

Resilient Connection for Entity Framework 6

Published on February 05, 2014 in Entity Framework · Read time 2 minutes

Disclaimer : I cannot take a shred of credit for the code you are about to see. I simply went over to the Entity Framework source code repository on CodePlex , copied some code, butchered it, hammered it, and rolled it until it fitted nicely into the slot that was my requirements. Please direct your thanks to the Entity Framework team . I had a requirement whereby I needed a resilient Entity Framework connection, and by that I mean a connection that could retry a certain number of times automatically before giving up. After searching around I found a class, called DbExecutionStrategy , which provided exactly the functionality I needed. The problem is, as far as I can tell, this class can only be used with the Code First approach. So it is all but useless to me, as the project I was working on was based on the database first approach. I directly copied the code provided in the aforementioned class, removed all the bits that didn’t interest me, and then reworked the code into a simple extension method that can be used against any DbContext; So if you want resilient connections in your project, all you need is the following; The logic is simple to test, simply use SQL Server…

In the spotlight - Demystifying IQueryable (Entity Framework 6)

Published on November 24, 2013 in Entity Framework · Read time 12 minutes

I’m not afraid to admit it. I can’t be the only one who has been confused by IQueryable when working with Entity Framework or LINQ to SQL. When using the web to research the topic, I have seen many conflicting blog posts and contradicting answers on StackOverflow. I have read various posts on MSDN about the subject, and I find them difficult to understand and incomplete. I seek to at least attempt to clarify the subject a little with this post. Entity Framework has become such a powerful object rational mapper (ORM) that performance of desktop and web applications seems to be drifting towards the back of developers minds. Personally, I’m so used to doing things the “traditional way” (using ADO.NET , etc and testing/optimizing using a combination of SQL Server Management Studio and SQL Profiler) that I find it hard to “write code and forget”. So naturally, I keep a close eye on what queries are being ran against my database. The purpose of this blog post is to have a closer look at , see how it is implemented in Entity Framework, what happens to our code at compile time, and understand what impact has on our repositories. All code samples in this post use Entity Framework…

Exploring logging in Entity Framework 6

Published on November 13, 2013 in Entity Framework · Read time 4 minutes

A project I am working on at the minute was recently upgraded to use Entity Framework 6.0.1 . There were many reasons why we wanted to do this, but one of the most compelling reasons was the new logging (SQL Interception) functionality that ships out of the box. A colleague demonstrated this new functionality and I immediately noticed a problem (limitation if you will) that I foresaw becoming a bigger issue when the time comes to performance tune the application. Implementing simple logging Take the very simple code below. We tell Entity Framework about our initializer (which adds some seed data for us) and then use our context as normal (in this case simply outputting the number of customers, and then exiting). This is pretty standard stuff, except for one simple difference (notice line 20). is somewhat helpful to us. If you run the above code, you will see various SQL statements outputted to the console window, as well as execution time and/or any error information. At first glance this is all useful information, but what about when your application grows and/or becomes more complex? Well the importance of having this information stays very high, but the raw nature of the…

How to fix 'Project failed to build' error when adding an Entity Framework migration (add-migration)

Published on September 06, 2013 in Entity Framework · Read time 1 minutes

I recently spent several hours tearing my hair out try to figure out why Entity Framework was preventing me from adding a migration to my project. I made some very simple changes to my existing model (I’m developing using the Entity Framework Code First approach) and when trying to add a migration, I was presented with the following error message; But how can this be? For you see, my project does build… My project not only builds, but it runs and works just fine … (up until the point where Entity Framework complains about the out of date model of course!). The solution It was only after considerable head scratching, and tinkering, that I came across the solution. My project specifically targets the x86 platform, as shown below; If I go ahead and change the build configuration to ‘Any CPU’ … I am greeted with a couple of dozen build errors, all relating to missing references! Once I resolved these issues, I was once again able to create migrations. Apparently Entity Framework builds your project in ‘Any CPU’ when creating migrations (and probably when issuing other commands as well). Hopefully this will help resolve your problem as well.

WPF Entity Framework Code First migrations

Published on August 16, 2013 in Entity Framework · Read time 6 minutes

Recently I wrote a WPF application using Entity Framework Code First and released it into the wild. Shortly after, the business requirements changed and I had to make changes to the model. Thus, I was introduced to Code First migrations. I did a lot of research on Code First migrations and could only really find the most simple of examples, and almost robotic documentation on MSDN that provided minimal help. This post aims to provide a clearer view on migrations, and how to properly create them. Before we can start with migrations, we need to create our normal C# code and then add in Entity Framework using NuGet. Once done, we can create our first migration and then explore a second migration. The Code The code is going to revolve around the common idea of customers and orders. Code structure; An has a collection of and a , the has a . Any properties that are marked as virtual are navigation properties, and are lazy loaded by Entity Framework at runtime. With the code structure in place, we can now introduce Entity Framework. Go ahead and use the package manager console, or the library package manager to install Entity Framework. Enabling Migrations Before enabling…

Entity Framework Code First In 15 Minutes

Published on July 12, 2013 in Entity Framework · Read time 7 minutes

Entity Framework is an Object Relational Mapper (ORM), created by Microsoft and built on top of the popular ADO.NET framework. Entity framework was first released in the second half of 2008. In 2011, with the release of version 4.1, a new feature was introduced… known as “Code First”. Code first allows us to write code without having to care (to a certain extent) about the make-up of the database, its tables and their relationships. The idea is that Entity Framework figures all this out for us, and it does a pretty good job! Entity Framework code first is designed around the “convention over configuration” principal, meaning as long as things are named in a consistent way your code should “just work” with very little effort. If its not possible to write your code in a way that Entity Framework understands, it is possible to tell Entity Framework about your model using attributes, the Fluent API, or a combination of both. Adding Entity Framework to your project The quickest way to add Entity Framework to your project is using the Package Manager Console (NuGet). In Visual Studio, click “View > Other Windows > Package Manager Console”, and type the following command; This process…