Create a RESTful API with authentication using Web API and Jwt

Published on March 15, 2016 in .NET, C#, Entity Framework · Read time 24 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…

ASP .NET 5 (vNext), first thoughts

Published on August 21, 2015 in C#, Career · Read time 4 minutes

Microsoft ASP .NET 5 is a major shift from traditional ASP .NET methodologies. Whilst I am not actively developing ASP .NET 5 applications at the minute, .NET has always been my bread and butter technology. When I look at industry trends here in the UK, all I see is .NET .NET .NET, therefore it is important to have one eye on the future. I’ve watched all the introduction videos on the ASP .NET website , but I also wanted to take a look at what ASP .NET 5 means to me . This is not meant to be a fully formed post. This will come later down the line. Right now, I think ASP .NET 5 is evolving too quickly to be “bloggable” fully. Version disambiguation and terminology Lets take a second to disambiguate some terminology. Microsoft’s understanding of versioning has always been different to everybody else. This tweet from Todd Motto really sums it up; Bill Gates on counting to ten. 1, 2, 3, 95, 98, NT, 2000, XP, Vista, 7, 8, 10. Todd Motto (@toddmotto) August 3, 2015 Looks like versioning is not going to get any simpler for the time being ASP .NET 5 (ASP .NET 4.6 is the current version) Previously known as ASP .NET vNext, ASP .NET 5 is the successor of ASP .NET 4.6 . In the past…

Quick tip - Avoid 'async void'

Published on August 30, 2014 in C# · Read time 3 minutes

When developing a Web API application recently with an AngularJS front end, I made a basic mistake and then lost 2 hours of my life trying to figure out what was causing the problem … async void . Its pretty common nowadays to use tasks to improve performance/scalability when writing a Web API controller. Take the following code: At a high level, when is executed the call will be moved off onto another thread and the execution of the method will only continue once the operation is complete (when the data is returned from the database in this case). This is great because it frees up the thread for use by other requests, resulting in better performance/scalability (we could argue about how true this is all day long, so lets not do this here!. So what about when you still want to harness this functionality, but you don’t need to return anything to the client? ? Not quite Take the following method: The client uses the property to do what it needs to do, so it doesn’t care what actually gets returned…as long as the operation (deleting the entity) completes successfully. To help illustrate the problem, here is the client side code (written in AngularJS, but it really doesn’t…

5 AutoMapper tips and tricks

Published on August 23, 2014 in C# · Read time 6 minutes

AutoMapper is a productivity tool designed to help you write less repetitive code mapping code. AutoMapper maps objects to objects, using both convention and configuration. AutoMapper is flexible enough that it can be overridden so that it will work with even the oldest legacy systems. This post demonstrates what I have found to be 5 of the most useful, lesser known features. Tip: I wrote unit tests to demonstrate each of the basic concepts. If you would like to learn more about unit testing, please check out my post C# Writing Unit Tests with NUnit And Moq . Demo project code This is the basic structure of the code I will use throughout the tutorial; I will refer back to this code in each example. AutoMapper Projection No doubt one of the best, and probably least used features of AutoMapper is projection. AutoMapper, when used with an Object Relational Mapper (ORM) such as Entity Framework, can cast the source object to the destination type at database level. This may result in more efficient database queries. AutoMapper provides the extension method, which extends the interface for this task. This means that the source object does not have to be fully retrieved before…

How to create your own ASP .NET MVC model binder

Published on August 11, 2014 in C# · Read time 3 minutes

Model binding is the process of converting POST data or data present in the Url into a .NET object(s). ASP .NET MVC makes this very simple by providing the DefaultModelBinder . You’ve probably seen this in action many times (even if you didn’t realise it!), but did you know you can easily write your own? A typical ASP .NET MVC Controller You’ve probably written or seen code like this many hundreds of times; Where did Id come from? It probably came from one of three sources; the Url ( ), the query string ( ), or the post data. Under the hood, ASP .NET examines your controller method, and searches each of these places looking for data that matches the data type and the name of the parameter. It may also look at your route configuration to aid this process. A typical controller method The code shown in the first snippet is very common in many ASP .NET MVC controllers. Your action method accepts an Id parameter, your method then fetches an entity based on that Id, and then does something useful with it (and typically saves it back to the database or returns it back to the view). You can create your own MVC model binder to cut out this step, and simply have the entity itself passed…

Create custom C# attributes

Published on February 22, 2014 in C# · Read time 4 minutes

You have probably added various attributes to your ASP .NET MVC applications, desktop applications, or basically any software you have developed using C# recently. Attributes allow you to provide meta data to the consuming code, but have you ever created and consumed your own attributes? This very quick tutorial shows how to create your own attribute, apply it to your classes, and then read out its value. Sample Project To demonstrate this concept, I have created a Console application and added a few classes. This is an arbitrary example just to show off how its done. The basic foundation of our project is as follows; We will create an attribute, and apply it to each of the Mammal classes, then write some code to display the value of the attribute to the user. The attribute will hold the latin (scientific) name of the mammal. Create/Apply an attribute There are two ways to create an attribute in C#, the easy way or the manual way. If you want to make your life a whole lot easier, you should use the Attribute code snippet. To use the Attribute snippet, simply start typing Attribute and press Tab Tab on the keyboard. Call the attribute LatinNameAttribute , accept the other…

Use T4 Templates to create enumerations from your database lookup tables

Published on February 15, 2014 in C# · Read time 11 minutes

T4 (Text Template Transformation Toolkit) has been around for a while now… its been a part of Visual Studio since the 2005 release . In case you don’t know, T4 can be used to automatically generate files based on templates. You create a text template, which is then transformed (interpreted) by Visual Studio into a working file. T4 can be used to create C# code files, and indeed it forms the basis of the current scaffolding templates you have probably used when creating ASP .NET web applications. You’re not limited to using T4 to create code classes, but this is one of its most common usages. I’ve known of T4 templates for quite a while, and I’ve edited some of the existing T4 templates in the past (see Scott Hanselman’s post for details on how to do this). To be honest, I’ve only recently found a practical scenario where I would want to write my own T4 templates, mapping lookup tables to enumerations ( C# enum ). What is a lookup table? A lookup table consists of data that is indexed and referenced from other tables, allowing the data to be changed without affecting existing foreign key constraints. Its common to add new data to these tables, and even make occasional changes…

Check TFS Online service status using C#

Published on January 10, 2014 in C# · Read time 1 minutes

If you use TFS Online you may have experienced some unexpected downtime over the last few months. Whilst the service is getting better and better all the time, downtime is still an issue. I have written a little screen scraping tool based on the HTML Agility Pack that will scrape the service status page and report back the current status. Add the following class to your project; The usage for this code is as follows; I hope you find this little helper useful. Please leave a comment below.

C# Create a custom XML configuration section

Published on December 21, 2013 in C# · Read time 3 minutes

It is common when developing either Desktop or Web based applications to need to persist settings in an easily updateable location. Developers often choose to add normal application settings in the form of key value pairs, as shown below, and this is a great approach when you only have a small number of settings. However, as your applications configuration becomes more complicated, this approach soon becomes hard for the developer and end user alike. This blog post looks at how you can create a configuration settings section to help ease this problem. Simple approach If you want to take the more conventional approach to making your application configurable, you could create a list of key value pairs in the section of your application configuration file; You then access these settings via the ConfigurationManager class; An alternative approach - Configuration sections Configuration sections give our XML more structure. Take the following example; The best approach to structuring your C# code is to copy each configuration section/element with matching C# code files. Starting with , create a new class with the same name and derive it from , as follows; Unfortunately…

How to create a new Outlook 2013 Email using C# in 3 simple steps

Published on December 14, 2013 in C# · Read time 2 minutes

It has traditionally been quite painful to interact with any part of the Microsoft Office product family from a C# application, but thanks to the introduction of dynamics and optional parameters over recent years, the process has dramatically improved. Step 1 - Prerequisites and Assembly References Before doing anything, it is important to note that you must have Microsoft Office 2013 installed for this to work. Seems obvious, but, its still worth mentioning. You also need two references; The quickest way to add these references to your project is to right click on the References folder in your project, and click Add Reference . The Reference Manager dialog window will appear as shown below; Click the COM tab Type Outlook into the search box Tick Microsoft Outlook 15.0 Object Library Click OK You should now see that the appropriate references have been added to your project; Step 2 - Using Directives and Initialization Next, add the appropriate using directives to your code file. The second directive is a recommendation to avoid ambiguity with other classes with the name Application . In the constructor of your application (or wherever you want this code to go…

How to write more efficient and maintainable C# code

Published on August 23, 2013 in C# · Read time 4 minutes

When you are writing your C# applications, you are aware that you want to make your applications as efficient, maintainable, and as scalable as possible. These are some great keywords that look great on blog posts like this, but how do you actually set about achieving this goal? We will look at some simply guidelines which try to make this goal more achievable. Write single purpose methods Your methods should have a single purpose… a single task to perform. For example, a single method should not try to access a database, create objects, read text files, and create images. Instead, create a single method for each task. Why? Multipurpose methods are typically long, hard to read, difficult to maintain and inefficient. Pros: Reduces reuse, improves readability and maintainability. Cons: None Keep methods short A method should be an absolute maximum of 50 lines long. Methods that are longer than this are typically multipurpose, which is bad. You want your code to be reusable where possible. Pros: More maintainable code, which is more reusable. Cons: None. Keep classes short Classes should be no more than 300 lines long. If you have a “DocumentHelper” class which creates Microsoft…

Getting started with SQLite and C#

Published on August 07, 2013 in C# · Read time 2 minutes

SQLite is a powerful, extremely light-weight transactional SQL database provider. SQLite is free and open source, and it does not require any server processes to handle it. SQLite is cross platform and runs on multiple architectures, making it ideal for use on the major operating systems such as Windows, Mac OS, Linux, and even lower powered devices such as PDAs, MP3 players etc. Prerequisites It is possible to get up and running with SQLite quickly in C#, by adding the System.Data.SQLite package to your project. Open the package manager console window run the following; Or alternatively, right click your project and click Manage NuGet Packages and search the online gallery for System.Data.SQLite . A Helpful Wrapper Class I have put together a very simple wrapper class that will get you up and running quickly. Here it is; This wrapper is loosely based on some code written by Mike Duncan . Usage The constructor takes the database path (the extension is completely up to you); To execute a standard non query command, you first create your command and call the method; You can retrieve data from the database in the form of the timeless object; Summary SQLite gives us the…