Building Your First API with ASP.NET Core – Part I

Getting Familiar with ASP.NET Core

Introduction to ASP.NET Core

ASP.NET Core is a new open-source and cross-platform framework for building modern cloud-based Internet-connected applications, such as web apps, IoT apps and mobile backends. It was architected to provide an optimized development framework for apps that are deployed to the cloud or run on-premises. It consists of modular components with minimal overhead, so you retain flexibility while constructing your solutions. You can develop and run ASP.NET Core apps on Windows, Mac and Linux. ASP.NET Core apps can run on .NET Core or on the .NET Framework.

Create ASP.NET Core project

To start the development of our application. I am going to create a new ASP.NET Core application using visual studio 2015.

Steps: File -> New ->Project

Select the ASP.NET Core and then select empty type. Reason why I selected empty type I just want to use the minimum codes that required to start the project and that is the best way to understand what is going on.

cp1cp2

Before we jump in to the development will go through the project structure and specific classes added to the project when we create this.

cp3

Once you create the project you can see its added a ASP.NET Core project which is includes Program.cs and Startup.cs. Let’s go and explore those classes.

Program.cs

Program is our starting point of the application. Most of you familier with this because you use aconsole applications before. Asp.Net core project also a console application. More specifically its call ASP.Net specific libraries.  In our case, will be running a web application so we need to host this application. Because of that WebHostBuilder instance is initialized.

program

SO, we are hosting a web application we need a web server.Asp.NET Core completely decoupled from the environment that host the web application. It’s ships with two different http servers.Web listener which is windows only server and Kestrel cross flat form web server. Kestrel is the default but we  are  using visual studio here so it will use IIS express as web server.

Startup.cs

Startup class is the entry point of an application. At this moment its included two methods, ConfigureServices and Configure.Configuration services used to add services to container and configured those services. This container used for dependency injection. We will talk about dependency injection later in this article series. But what are services in ASP.NET Core world. Service is a component that is intended for common consumption in an application. Those services can be built in services or custom service that we are creating during our application development.

startup

The ASP.NET Core Request Pipeline and Middleware

Whenever HTTP request comes in something must handle that request so eventually it’s a result of HTTP response. Those pieces of codes that handle the request and resolved in responses that make up the request pipeline. What we can do is configure that pipeline by adding middleware which are software components that are assembled in to an application pipeline to handle requests and responses. If you worked with older version of ASP.NET you know that module and handlers to care of this for us. In ASP.NET Core those are taken over by middleware. Few samples that we can add to this pipeline are diagnostic middleware or middleware to handle authentication. Even MVC is a piece of middleware that can be added to request pipeline.

pipeline

Now will look at such a request. The Asp.Net request pipeline consist of a sequence of request delegates called one after the next from one piece of middleware to the next. Each of those can perform operations before and after the next delegates. Important to know that each component choices whether to pass the request to next component in the pipeline or not. So, the order in which we added the middleware to the request pipeline matters. Good example is authentication middleware, if authentication not success request should not pass to the next middleware and immediate response unauthorized request.

Configuring the ASP.NET Request Pipeline

In this section I am going to show you how to configure the ASP.NET Core request pipeline. I am going to show you when we are in the development environment I want to show the developer friendly Error message when exception thrown. To do this actually we no need to do anything its already built in.

Let’s have a look at this statement app.UseDeveloperExceptionPage();

pc

This configures the request pipeline by adding a developer exception page middleware to the request pipeline. So now when exception thrown this piece of middleware will handle it.

To test this, I will do a small change to my code to throw and exception.

ex

If you run the application you can see a nice error page lot of useful information’s.

Now check the code belove carefully and you can identify there is a specific condition check before use the developer friendly error page. That condition used to make sure this developer friendly error only show when application running in development environment.

ex2.png

May be this is a good time to talk about separate environments. Because we might need to execute different piece of code depending on environment and this is a good example of that. The developer exception page that is not something we want to show everyone. We need this during development but not in production.

Let’s have a look debug tab of the project properties.

debug.png

Here we can find ASPNETCORE_ENVIRONMENT variable its set to development. ASP.NET Core references environment variable hosting environment, to describe the application currently running. Three values are used Development, staging and production.

Now will change our code to handle the error differently when application running in production. What I want is catch the exception and log it. There is a middleware for that as well, the exception handler middleware.

addex.png

Go to the debug tab and change the ASPNETCORE_ENVIRONMENT to production and run the application you will get the blank page. If you still get the developer error page you need to restart the IIS express.

This is the complete of the part one of the Building Your First API with ASP.NET Core series of article. This covered all the basic information that you should know about the ASP.NET Core.

Code Sample: Part One Code Sample

Next article: Building Your First API with ASP.NET Core Part II – Creating the API and Returning Resources (Coming Soon)

 

Building an Owin Authentication Middleware

Recently I worked on a project which is used Oauth as authentication mechanism. In this project we need to implement a custom authentication mechanism as well to validate some users. While I am researching on this I found Owin and Katana offers a flexible pipeline for external authentication with existing providers for authentication by Google, Facebook, Twitter and more. Good news for me it is also possible to write your own custom authentication provider and get full integration with the Owin external authentication pipeline and ASP.NET Identity.

In this article I am going to explain how we can develop your own custom authentication provider and get full integration with the Owin external authentication pipeline and ASP.NET Identity.

Normally Katana middleware is made up of 4 classes.

  • The main MyCustomAuthenticationMiddleware class.
  • The internal MyCustomAuthenticationHandler class doing the actual work.
  • A MyCustomAuthenticationOptions class for handling settings.
  • An extension method in MyCustomAuthenticationExtensions for easy setup of the middleware by the client application.

 

MyCustomAuthenticationOptions class

Any middleware will need some kind of configurations. It is stored in an options class. To work with the Katana base classes, it must inherit AuthenticationOptions class in Microsoft.Owin.Security namespace, which contains some mandatory options that are used by the framework. In my class I am going to use authentication type option only.

options

MyCustomAuthenticationHandler class (Inside MyCustomAuthConfig.cs)

This is where a real handler would inspect the incoming authentication ticket from the external authentication server. My Custom middleware just creates an identity with the values from the configuration (See custom middleware below).

handler

MyCustomAuthenticationMiddleware class

The middleware is a factory that creates instances of the handler that does the actual work of processing requests. Only one instance of the middleware is instantiated. The middleware constructor checks the configuration in the options class and if certain properties are null, it adds some defaults that are dependent on the previous middlewares in the pipeline.

middleware

MyCustomAuthenticationExtensions

The IAppBuilder.Use method takes an object as the first parameter, which has the advantage that a middleware won’t need to have a reference to a particular assembly containing a specific middleware interface. But using an untyped object makes it more confusing for callers. This is where the extension method comes into the play, it makes it easy to register the middleware in the Owin pipeline.

extention

Finally my MyCustomAuthConfig look like this.

config

In your startup class you need to call the  MyCustomAuthConfig.SetupVerification(app) method to apply your implementation.

 

Ref:

http://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin.Security.Google/GoogleAuthenticationHandler.cs

Better way to handle Ajax call in your AngularJs code

If you are working on web applications especially, we have to use JavaScript to handle our front end code in most projects. In this article I am going to discuss a better way of handling Ajax calls within my project.

I have created a new MVC 4 project using visual studio 2012. In this project I have written couple of methods in an angular service, to access MVC controller methods in order to get and save data. Those methods are shown below.

service with ajax calls

The above service can access any angular controller to consume the data from the back end. In my code the user angular controller works with this service.

controller code

Now within our project we can write many number of Ajax calls like in the above sample. There will be no problems if you do it correctly, your application will work nicely. But just think if you want to change settings of your Ajax calls, you will have to do it may places. Not only that but if at a later point if you decide to change all these Ajax calls to angular $resource or some other technique, that will be a lot of work for you isn’t it?

So how can we control this and make your code more maintainable? I am going to use angular service to do this. I added a new service that manages all Ajax calls. All my other angular services or controllers use that service to do any Ajax calls that requires to access the data.

ajaxservice

The code below shows how we can use this common service within other services and controllers.

new user service

Now you can understand that my change brings more control on these Ajax calls because changing one place will affect all the Ajax calls. Or if you want to do it only for one of your Ajax calls you can do it as well.

To prove the above two points I will do the following changes to my code.

Make all Ajax get calls dataType property be equal to ‘json’. Changing one place will affect all the Ajax get calls.

ajaxserviceChange data type

My second change is changing the cache property to be equal to ‘false’ when I call the user service user details get call.

new user service changes

Hope this article will help you to improve your JavaScript code. Also you can get sampe code form here

JavaScript Constructor Pattern

In Object Oriented programming languages a constructor is a special method used to initialize a new object once memory has been allocated for it. When we take JavaScript almost everything is an object.

Object constructors are used to create specific types of objects. Constructor preparing the object for use and accepting parameters a constructor can use to set the values to properties and methods when object is first created.

Object Creation
Two common ways used in JavaScript to create objects. Those methods are as follows:

//Create a new empty object
var myCar = {}


//Which is a shorthand for the object constructor
var myNewCar = new Object();

Basic Constructor
As we know JavaScript doesn’t support the concept of class, but importantly it does support constructor functions that work with objects. For a call to a constructor function with the keyword new, we can tell JavaScript would like the function to behave like a constructor and instantiate a new object with members in the function.

Inside our constructor, the keyword this references the new object that’s being created. So now we are going to create a basic constructor like follow:

function Car(model, year, mileage, color) {
     this.model = model;
     this.year = year;
     this.mileage = mileage;
     this.color = color;

     this.toString = function () {
         return this.model + "has done " + this.mileage + ' miles'
     }
}

//Usage
var civic = new Car("Honda Civic", 2012, 5000, "Black");


//browser console will show the output
console.log(civic.toString());

This sample code shows us the simple version of the constructor pattern. Still this implementation has few problems. Those are

  • It makes inheritance difficult.
  • Function such as toString() are redefined for each of new object created using car constructor.

So That means this is not optimal, as the function toString() should be ideally be shared between all instances of the car type. Next section will see how we can overcome these issues.

Constructors with Prototype
JavaScript functions have a property called a prototype. When we call a JavaScript constructor to create new object, all the properties of the constructor’s prototype are available to the new object. In this way, multiple car objects can be created that access the same prototype. Now will extend our example as follows:

function Car(model, year, mileage, color) {
    this.model = model;
    this.year = year;
    this.mileage = mileage;
    this.color = color;

}

Car.prototype.toString = function () {
    return this.model + "has done " + this.mileage + ' miles'
}

//Usage
var civic = new Car("Honda Civic", 2012, 5000, "Black");


//browser console will show the output
console.log(civic.toString());

After new prototype implementation, the single instance of toString() will now be shared between all car objects.

In this article we learn constructor pattern and used prototype property to make it optimal. Hope this will help you to understand this pattern.

Developer Tips – Part Two

When we work on our project we always press F5 or use the build menu to build the application to make sure our code is compiling. After we see the build successful message most of us think our code is correct. Sometimes even though the code is working there can be mistakes or bad coding practices used within the code. So how can we find them? Warnings section in error list will show these.

image1

In this article I am going to discuss about warnings in visual studio. Most of the developers forget or do not care about this section. Remember that this a really useful and important section just as the errors. You might ask why the warnings are of any importance if your code can execute. The reasons are

  • Warnings show most of the mistakes in your coding
  • Fixing the warnings will improve the performance of the application
  • It will help to develop maintainable code of good quality

As a start check about the settings for warnings in visual studio. In the solution explorer select a project and right click and select property. Then you will see the Build tab. using the build tab we can do the following

  • Set warning level

The minimum warning level you can set for the build chose from this option. Valid values are 0-4.

0 – Turns off emission of all warning messages.

1 – Displays severe warning messages.

2 – Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.

3 – Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.

4 – Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line.

  • Treat warnings as errors

This option is important if a developer wants to fix the warnings before he commits the code. If you enable this option it will force you to fix the warnings.

image2

Now I am going to discuss a couple of warnings to give you an idea of how important these can be.

  • Variable declared but never used

image3

Now you can see that I created a variable called total and never used it. What is the effect of this mistake? Every time when we call this method it will create a variable and when we exit, the method run time will delete it. This is an unwanted step to run-time. If we make the same mistake many times our application can have some performance issues. By avoiding these type of mistakes we can improve our application quality.

  • Possible mistaken empty statement

image4

When you see the code you can identify that this is a mistake. If we do not consider warnings this will not get identified until we run and test this code. If we consider warnings we can identify our mistakes upfront and reduce the bugs within our code.

I took two simple examples to give you an idea about warnings and how important they are to developers. If you want more details about warning you can refer following MSDN link:

http://msdn.microsoft.com/en-us/library/ms228296(v=vs.90).aspx

After reading this article I hope you all think seriously about warnings. Happy coding.

Developer Tips – Part One

When we work on our projects most of the time we think about the most important concepts like security, performance, etc. Unfortunately most of us do not consider the maintainability of our applications. 

Most of the developers think about how to complete the task that is assigned to them. I think we should consider the quality of our code as well. When we deliver some development work we should deliver it as quality work. Most of the developers face the difficulty of delivering quality work within the given time because we know we have a very limited time for our tasks.

In this series of articles I am going to give you some good practices that we can use for our development work. Most of the things are well known concepts. Only thing is we have to use them in our code.

As a start I am going to talk about constant variables and how we can use them effectively within the code.

What is a constant variable?

The const keyword is used to change a declaration of a field or variable. It requires that the value of the field or the variable is constant, which means it cannot be modified. Some Examples:

1

How can we use it?

We can use constants in many ways to improve our code quality and maintainability. Some examples given below.

Use them to handle session variables

 When we use session variables to store data we must use constant variables to store the session keys. Following example shows you how we can do this.

  1. Create a common class that can access everywhere in the project. Name it as “SessionKeys”session keys
  2.  Then use that class to access your session datasession usage

Advantages:

  1. When you write the code that access the session every developer uses the same key to store or access session data. This will ignore the mistakes like using wrong session variable or naming conflicts in session.
  2. Changes become easier.

Use them to manage hard code strings

If you want to store any values within the code use constant and use it within the code.

const sample

Above example shows you how we can use the constant variables. Main advantage in this method is that when you want to access this same value in multiple locations it is very easy. Because in order to change the value, just changing the constant variable value is enough. It will affect all the places in your code where the value is used.

In this article I have given a few examples for you to get an idea on how we can use a simple option like this to improve the quality of your code. On another day I will give you more tips.