Create a Web API application in .NETCore

Let’s try to create a .NETCore application from Visual Studio 2015

Create .NETCore web application from Visual Studio

Create a new project from Visual Studio 2015, In .NETCore tab, select ASP.NET Core Web Application (.NET Core) . Give it a name and click on OK.

Select Web API from ASP.NET Core templates

Select Web API from ASP.NET Core templates and click on OK.

build the project and see changes

Check folder structure of the application, It includes a Program.cs and Startup file. It includes a project.json file to define all required packages for your application. appsettings.json file maintains application settings same as web.config file in a ASP.NET Web application. Controllers folder has all Web API Controllers.

If you want to create a Web API application from Yeoman template generator, follow this post, http://hansamaligamage.github.io/2016/09/16/Create-a-web-application-with-Yeoman/

Open service application from Visual Studio Code.

Open your application in Visual Studio Code

cd into the application directory and open Visual Studio Code using code . command. You can see folder structure of your application as above. Add assets to build and debug your application as the info dialog box suggests.

vscode folder is added

vscode folder is added into the solution with launch.json and tasks.json file.

Dependencies in project.json file

Let’s see what are the dependencies required for a mvc application.

To find out more about project.json file and launch.json file, You can check this post, http://hansamaligamage.github.io/2016/09/15/Hello-World-in-NETCore-Ubuntu/

basic packages required for a mvc application

Since We create a Web API application, in project.json file, It shows Microsoft.AspNetCore.Mvc package dependency.

Run ValuesController and check service calls.

If you want to check how a web application is going to run, check this post, http://hansamaligamage.github.io/2016/09/15/Web-Application-in-NETCore-Ubuntu/

Let’s run Web API application and check available services.

Read service in ValuesController

Build (Ctrl + Shift + b) and run (Ctrl + F5) your application and ping to the Read service as above. Its shows return values in the browser.

Let’s build the movie service

Create Movie model.

Add Movie model

Create a Model folder to define entities in your application. Then create Movie class and add properties into it. We follow Code First approach in this example. So when we create the database Movie table will be created.

Create Context class to build the database.

Create db context class

public class MovieDbContext : DbContext
{
}

From context class, our database will be generated. Context class should be inherited from DbContext class. In order to do that, we have to add references from Entityframework core.

Install Entityframework Core (EF Core)

Add entityframeworkcore references into project.json file

Add entityframeworkcore reference as a dependency into project.json file, “Microsoft.EntityFrameworkCore”: “1.0.0” and resolve reference error in MovieDbContext class by adding using Microsoft.EntityFrameworkCore statement.

Define the connectionstring

Define the connectionstring in appsetings.json file

Define the connectionstring in appsettings.json file to connect to the Sql server, “ConnectionStrings”: { “DefaultConnection”: “Data Source=localhost;Initial Catalog=movieDB;Integrated Security=true” }

Check MovieDbContext class

MovieDbContext class with constructor

In MovieDbContext class, define constructor with context options and call base class method.

Add entities in moviecontext class

run EFCore migrations

Try to run migrations for MovieDbContext class, dotnet ef migrations add InitialMigration It gives an error. No executable found matching command “dotnet-ef” , We have to install entityframeworkcore tools to run migrations from .NET cli. Let’s try to do that.

Add EFCore tools

Add EFCore tools and run migrations

Add “Microsoft.EntityframeworkCore.Tools” : “1.0.0-preview2-final” in tools section of project.json. Try to run migration and it gives an error again!!, Could not invoke this command with the startup project ‘demo’. Check that ‘Microsoft.EntityFrameworkCore.Design’ has been added to “dependencies” in the startup project and that the version of ‘Microsoft.EntityFrameworkCore.Tools’ in “tools” and ‘Microsoft.EntityFrameworkCore.Design’ are the same. See http://go.microsoft.com/fwlink/?LinkId=798221 for more details, What’s we are missing,

We haven’t added ‘Microsoft.EntityFrameworkCore.Design’ as a reference, We have to add EFCore Design references to run migrations scripts. Let’s add it and check. And also it mentions ‘Microsoft.EntityFrameworkCore.Design’ and ‘Microsoft.EntityFrameworkCore.Tools’ version should be same.

Add EFCore Design reference.

Add entityframeworkcore design reference

Add “Microsoft.EntityFrameworkCore.Design”: “1.0.0-preview2-final” reference into project.json file. Note that, ‘Microsoft.EntityFrameworkCore.Design’ and ‘Microsoft.EntityFrameworkCore.Tools’ version are same.

Then try to run migrations command again and it gives another error, No parameterless constructor was found on ‘MovieDbContext’. Either add a parameterless constructor to ‘MovieDbContext’ or add an implementation of ‘IDbContextFactory‘ in the same assembly as ‘MovieDbContext’.

Startup class implementation

Configure services in startup class

In Configure services method, it’s going to add some services into the application.

services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString(“DefaultConnection”)));

Add the database context and define the connectionstring of your database, in configure service method, it’s missing some references, since we havent add any EntityframeworkCore sqlserver references.

Add EFCore Sqlserver references

Add EntityFrameworkCore sqlserver reference

Add “Microsoft.EntityFrameworkCore.SqlServer”: “1.0.0” reference in project.json file and restore them.

Add EFCore sqlserver references

Now sqlserver reference is added. Configure service method looks fine.

Run Migrations

Let’s create movieDB in sql serever.

run migrations and check what happens

Run Sqlserver migrations, It doesn’t give any errors in .NET cli, Migrations folder is created with migrations scripts. In Initial Migration class, it defines Up and Down methods to create and drop movie table respectively.

Update the database

movie database is created

run dotnet ef database update command to update the database. In sqlserver movieDB got created.

Add Movie controller

In Visual studio code, We can’t use scaffolding. So i created a Movie Controller with all the CRUD operations of Movie entity in visual studio. Let’s add it.

Movie controller with all the CRUD operations

In Movie Controller, it works with application/json type data, and the route is api/Movies. Note that in .NET Core Api controllers inherit from Controller class, not from API Controller class.

ping to api/movies method

Go to api/movies method and check Network tab in developer tools. method returns 200 - OK. as a response. We don’t have data in movie database, Let’s try to add some data.

Add data using Postman

ping to api/post a movie

Postman is a tool to test your service apis. Although we can test GET requests through browser, to test POST requests, we need to use Postman. Add a movie using Postman and retrive it using web browser.

We have created a service API using .NETCore and Sql Server. Let’s try to run this same application on Ubuntu with MySQL.

Clone your application in Ubuntu

Let’s try to open your application in Ubuntu, We are going to connect this application to MySQL server,

Clone your application in Ubuntu

Type git clone … with repository url, Your project will be downloaded. Then cd into application directory and open it in visual studio code.

Restore packages and build your application

Restore packages and build application

Restore packages defined in project.json file and Build your application. It all works fine.

Let’s try to run our application

Run your application

Let’s try to run our application without any modifications, It seems working fine. Let’s navigate to api/values , It calls READ service of Values service. It returns 200 - OK as response.

Read service in movie controller

Ping to api/movies, it returns an empty array, since we don’t have a database. Check the terminal and try to find any erros, It shows a fail error in red. It says Microsoft.EntityFrameworkCore.Query.Internal.SqlServerQueryCompilationContextFactory[1]
An exception occurred in the database while iterating the results of a query. System.NotSupportedException: The keyword ‘integrated security’ is not supported on this platform. at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) …

It says an error as The keyword ‘integrated security’ is not supported on this platform. If you remember, where we have used integrated security , that’s in sql server connectionString. We can’t operate with Sql server on Ubuntu. We have to install My SQL server to store data in your application. Let’s do that.

Add MySQL connectionString

Define mysql connectionString

Add mysql connectionString in appsetings.json file, movieDB will get created in mysql server.

“DefaultConnection” : “server=localhost;database=movieDB;uid=root;pwd=hansamali;sslmode=none;”

Add MySQL service in your application

Add mysql service into your application

If you remember, we added Sql service into the application when we run in winodows. In Ubuntu also same thing we have to do. Add MySQL service into your application with dbContext class. But it seems we are missing something in here.
Note that, Microsoft.EntityframeworkCore has been highlighted. Your application doesn’t use that reference anymore. It’s a reference from Sql server. We have to add a reference from MySQL to proceed with this. Let’s try to add it.

Add MySQL EFCore reference in project.json file

Add mysql EFCore reference

Add “MySql.Data.EntityFrameworkCore” : “7.0.4-ir-191” reference in project.json file and restore them.

Add mysql reference in Startup class

services.AddDbContext(options =>
options.UseMySQL(Configuration.GetConnectionString(“DefaultConnection”)));

Add using MySQL.Data.EntityFrameworkCore.Extensions; statement in startup class, It works fine now.

In windows with Sql server, We run migration scripts and ensure database is created. But with Ubuntu, we can’t do that. Somehow we have to ensure our database is created. Let’s give it a try.

Ensure MySQL database got created

Ensure mysql database is created

Add this lines of code to ensure MySQL database got created.

var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseMySQL(Configuration.GetConnectionString(“DefaultConnection”));

var context = new MovieDbContext(optionsBuilder.Options);
context.Database.EnsureCreated();

Run your application

run your application

Then build and run the application, navigate to movies read service and verify it works fine. read service returns empty array. Let’s check database is created in MySQL server.

View MySQL databases

Check whether your database is created

run mysql -u root -p command to access mysql shell, then type show databases; to view all the available databases. You can see movieDB. is successfuly created.

Let’s add some data into Movie database in MySQL

Add a movie into database

Call POST service in movie controller and add a movie into the mysql database. Refresh read movie service, it shows available movies in your mysql database.
Connect to the mysql shell and try to view data in Movies table.

Go to mysql shell by typing mysql -u root -p , Then type show database; to view available databases, to go inside a database and query it type use movieDB; , You can see available tables in movieDB using show tables; Type a select query to view data as select * from Movies;

In this blog post, I described how to run a web api application in windows with Sqlserver. And then we tried to configure same service application on Ubuntu with MySql server, with less amount of coding we could achieve that.
It was a really cool feature in .NETCore

You can find a sample application from here, https://github.com/immysl/fav-movies

Create a web application with Yeoman!

Run Yo command

First of all create a new directory and cd into it. Then run yo command.

If you haven’t installed Yeoman yet, follow this post http://hansamaligamage.github.io/2016/09/15/Yeoman-go-easy-with-NETCore/ It shows how to install Yeoman in Linux environment.

Yo command

Run Yo command, and check what happens.
It points to Install a generator by default. It doesn’t point to Run a generator, until we install a generator.

install a generator

search for aspnet generator in npm package management store.

install a generator

We get a permission issue when installing aspnet generator, Let’s try what yo says, will run npm install command and see what happens.

install a generator using npm install command

We tried to install generator using npm install command, But it shows the same error!!!!
Since this is a permission issue, will run the command with sudo and check what happens.

install a generator as administrator

When installing generator as an administrator, it installs without getting any errors.
Let’s run Yo command and select a template.

create empty web application using Yo

Select aspnet as generator, and then select what type of application you want to create.
Select Empty Web Application and give a name to it.

How it looks like after restoring packages

Go inside the project folder and open it in visual studio code.
In visual studio code add .vscode folder and restore relevant packages. It shows solution like this.

program.cs file

In program.cs file, It shows WebHostBuilder class, with cross platform Kestrel server and IIS integration both.
It has defined a seperate Startup class, to configure the http request pipeline.

dotnet build and run application
Build and run .NETCore application and check terminal window,
You can see logging is enabled for browser navigations.

We can see complete project is created using Yeoman template generator. It includes program.cs, project.json and web.config files.
It includes Startup class to manage the http request pipeline. And also it has a wwwroot folder to host our web application.
Since Yeoman is generating complete application, We don’t have to do anything manually. We can only focus on the application logic and start working on it.

You can check sample code from here, https://github.com/hansamaligamage/WebAppWithYeoman

Install Yeoman in Ubuntu

What is Yeoman

Yeoman is a free open source tool. It’s more like visual studio project templates. It’s going to create a complete project with given set of tools. Yeoman has set of generators, It complies with industry best practices. Developers can easily start with their applications with specific tool set, without worrying about the setup or template of the application. Yeoman templates includes building, testing and minification in your application, So developer can focus on the logic of their application.

Install node js

install node

Install node js, before installing Yeoman. Yeoman is going to run on a node server, After installing node js check the version of it.

Install npm

install npm

When we install nodejs, npm is also comes along with it. If you start installing npm before installing node js, follow like this.
npm is a package manager for Yeoman, It’s going to download any dependencies in your application, You don’t want to manually download and install it.

Let’s try to install Yeoman!!

install Yeoman

Run Yo installer command,

Yeoman permission issue when installing

But it doesn’t seem work, We get an ugly permission issue, Let’s try to fix this.
It says permission denied for some paths. It suggests to run installer command as root/Administrator, Let’s try out that.

Install Yeoman as administrator

It looks perfectly fine, when we use sudo command with yo installer command.

check whether Yeoman is installed properly

We can check whether Yeoman is installed properly using Yo command.
We have successfully installed Yeoman. Now we don’t want to manualy create .NETCore applications. We can use generated templates using Yo. Let’s start using Yeoman templates.

Listen to me in http://localhost:5000/ with .NETCore on Ubuntu

In my previous post, We saw how to write a console application in .NETCore. Let’s see how to write a web application in this post.

Create a new project

Create a new project

Create a new project and open it in Visual Studio Code.

Initiate a WebHost Builder object

Create a WebHostBuilder instance, since we need a server to run our web application, It’s little bit different to a Console application.
We get an error here, Some packages seem to be missing, ok!!! First of all let’s add a server to run our application.

Add Kestrel to our package list

Add Kestrel to our package list

Add Kestrel server into project.json file and restore the package.

Add relevant using statement for kestrel server

In program.cs file, Add relevant using statement.

run WebHostBuilder

When initiating a WebHostBuilder, It turns your console application into a web application.

Now, Ask the host to build using Build method, and run the webhost. When hit on Run method, It’s going to give a signal to the host to listen on a port and start accepting http traffic.

Let’s run and see the changes

run web application and see what has happened

When we run our application, It gives an error!!!!
It says we haven’t provided a service to startup the application. It means we haven’t mentioned we want to use Kestrel or not when starting our application. Let’s check how we can start our application with kestrel server,

run web application and see what has happened

In here we asked Kestrel to accept a http request and turn it into a http context. In configure, we accept an Application Builder instance, it’s going to perform some actions in our application.
When hit on app.Run(), It’s going to add a terminal to the http request pipeline. Inside app.Run() method, we pass an http context object kestrel has created.

In the terminal window, It shows Hello World - web .
Then it shows Hosting Environment as production., default hosting environment for a .NETCore application.
Then it shows Content root path of our application,
Our web project listen into http://localhost:5000/ which is default url and the default port of our application.

You can download code sample from here, https://github.com/hansamaligamage/WebAppin.NETCore

Hello World in .NETCore Ubuntu

Let’s start our first application on .NETCore - Ubuntu

Create a new project

Create a new project

Create a folder in your desktop, myprojects , go inside of it and create a new project using dotnet new command.
You can see Program.cs and project.json file is created. To build our first project in .NETCore, Let’s install Visual Studio Code editor.

Install Visual Studio Code

Install Visual Studio Code

Download correct version of Visual Studio Code relevant to Ubuntu and install it.

Open a project in Visual Studio Code

Go to your project location and open your project in visual studio code. It shows a message to install a extension. Extensions allow you to add languages, debuggers and tools to your development environment, Click on Show Recommendations to view recommended extensions.

Visual Studio Code Extensions

Select C# powered by Omnisharp , since We are using C# code in .NETCore. It provides intellicense for .NET. Omnisharp provides a set of tooling and libraries to IDEs like Visual Studio Code, Sublime, Atom, Emacs, Vim and Brackets. After installing C# extension, enable it.

program.cs file

program.cs file shows entry point to the application as usual.

project.json File

project.json file

project.json file shows nuget dependencies required to build the application.

Let’s see what is the meaning of these attributes in project.json file

version”: “1.0.0-* specifies version of the .NETCore, It says version should starts with 1.0.0
buildOptions defines how the project should be built.
dependencies lists all the dependencies in your application.
frameworks defines target framework that will be used with specifies dependencies.
imports defines where our application runs, When we add dnxcore50 , it says we are running in Core CLR on the dnx.

build and debug assets

You can see a message to install build and debug assets, install them. And another message to restore the packages in project.json, restore them as well.

After adding assets folder and restoring packages

After adding assets folder, you can see .vscode folder with launch.json and tasks.json files. All the build errors are gone. Check the output window, It shows packages restoring is completed.

project.lock.json File

project-lock.json file

After packages restoring is completed, project-lock.json file has been added into the solution.
It’s going to capture entire dependency graph that your application depends on. In project.json file, you define the top level dependencies, more detailed level description is available in project-lock.json file.

launch.json File

launch.json file

This file is going to confgure debugging and running in the application. In this example, It’s going to launch .NETCore console or even we can attatch to .NETCore console.

tasks.json File

tasks.json file

This file is used to automate tasks like building, packaging, testing and deploying softwares. In this example, It has define a build task, and specified to run as a build command.

Hello World on the terminal

Hello World on the terminal

That’s all we want to know about a .NETCore application, Let’s see the output of our first application, When we run dotnet run command, It shows the output of the application.

I created a github repository, You can check it from here, https://github.com/hansamaligamage/HelloWorld

Install .NETCore on Ubuntu

In .NET framework history, .NET have its full framework from .NET 1.0 to .NET 4.6.2, specially created for windows platform. Latest version of .NET framework is .NET 4.6.2 up to now, In the end of june Microsoft released a new .NET framework called .NET Core for Windows, Linux and Mac. A great feature of .NET core is, a solution build on windows can be run and modify in a linux based environment. We can build an application on winows, and can host it in a Linux server, how cool is that.

Add dotnet apt-get feed

apt-get Feed

First of all, setup the apt-get feed and update it.

apt-get is a free package manager program. It works with Ubuntu’s APT (Advanced Packaging Tool). Using that command line program, We can Install new packages, remove or upgrade packages.

for Ubuntu 16.04, run these commands,
sudo sh -c ‘echo “deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main” > /etc/apt/sources.list.d/dotnetdev.list’
sudo apt-key adv –keyserver apt-mo.trafficmanager.net –recv-keys 417A0893
Then update apt-get feed Using following command, sudo apt-get update

Install .NETCore top of apt-get

Install .NETCore

Install .NETCore using following command, sudo apt-get install dotnet-dev-1.0.0-preview2-003121

run dotnet command

Check whether .NETCore is properly installed using dotnet command. It shows .NETCore version as 1.0.1

Install Ubuntu in a Virtual Machine

Let’s try to create a virtual machine with Ubuntu. Later in these post series, will try to install .NET Core into Ubuntu.

Ubuntu run in a VM

Let’s see how we can run Ubuntu inside a virtual machine.

Create a virtual machine with Ubuntu

Select Create a new Virtual Machine , then New Virtual Machine Wizard appears. in this example I selected a disc image of ubuntu (.iso file) or else you can install a operating system using a dvd. Click on Next

Personnel information

Enter your personnel information, a username and a password for ubuntu.

Name the virtual machine

Give a name for the virtual machine and install location.

Specify the disk capacity

Specify the disk capacity and virtual hard disk information

Customise hardware in the virtual machine

Customise the hardware if you want, You can change name of the virtual machine, location, hard disk size, memory etc.

Installing Ubuntu in a vm

Installation of Ubuntu will take few minutes.

Ubuntu is ready

Ubuntu in vm is ready,

Install VMware tools

We are going to install VMware tools. We can’t go full screen mode, If we haven’t install VMware tools.

VMware tools installer

Download VMware tools, and Let’s try to install it.

I downloaded VMware tools - 10.0.6,

Extract VMware installer

Right click on VMware tools zip file and select Extract To option.

Select extract location as Desktop

Select Desktop as extract location, and press on Extract

cd into VMware installer

Go inside VMware installer using cd command.

run VMware installer

Run VMware installer, using above command with sudo , sudo command means, you run this installer as a super user. superuser do

Now you can go to full screen mode.

Check Ubuntu version from terminal

Open a terminal and check Ubuntu version, We have succesfully Installed Ubuntu in a virtual machine.

How to generate a license key for your system

When a web application develops, we need to protect user passwords from security attacks. When your application operates on a license key, we need to validate the license.
In todays world providing security to your system is bit crucial. We have to face malicious scripts, security threats and unwanted attacks in out there. Let’s see how we can prevent those kind of attacks.

Password Hashing

In hashing, we are going to convert password string into a byte array. Hashing is a one way funtion, we can’t reverse it. We can see many hashing algorithms available.
Let’s say we hashed the users password and stored in our database. When user second time logs in, we have to verify entered password is correct. What we can do is, we can hash the entered text into password field and compare it with the hashed value from the database. Since Hashing is a one way function, we can’t decrypt and retrieve original text.

Invalid username or password

When user enters wrong password, System should not let the user know it’s Invalid password , instead of it should tell Invalid username or password . Then if hacker tries to login into your system, he doesn’t know whether username or password got wrong.

Hash Functions

SHA1, MD5 are popular hashing algorithms. SHA1 got inspired from MD algorithms and created SHA algorithms. From these two algorithms, better to use SHA1, Because it’s high secure than MD5. MD5 is going to convert a string into 128 bits. But SHA1 convert a string into 160 bits. In MD5 less no of operations required to crack the message, when compared to SHA1. But MD is faster than SHA1. However it’s better to use SHA1 algorithm instead of MD5, since MD5 can be broken easily.

Hashes can be cracked easily

Hackers can guess passwords and simply hash them with a hashing algorithm and try it in your system. It takes few seconds to generate a hash. Within a limited amount of time, your passwords can be cracked easily. These type of guessing password and hashing is called as Dictionary attacks and Brute force attacks.
In dictionary attacks, it uses a file with some words. These words can be extracted from a database or else from set of paragraphs. Most hackers guess passwords from common terms like, hello, hellow, he11o3 etc. They take a string and try to replace letters in it, like hello, he33o, heiio, etc. Then these words are hashed and use against the password hash.
Brute Force attacks going to try out every possible of character combinations to a certain string length. It’s a very expensive computational process, But eventually it’s going to find out your password! That’s why we need lenghtier passwords, So it will take long time to crack your passwords.
By hashing your passwords, We can’t prevent Dictionary attacks or Brute force attacks, But we can minimize them.
While Dictionary attacks and Brute force attacks are time consuming, Hackers has another kid in their block, It’s Lookup Table. In Lookup table, It’s going to precompute the hashes of passwords and used to store them in a dictionary file.
So hundrends of guesses can be done in a second. It’s a very effective method to crack your passwords.
Rainbow Tables, Beware guys, it can crack any 8 characters lengthy MD5 password. Rainbow table is same as Lookup table. In here hash cracking speed is slower, compared to lookup table. But lookup table size is smaller, so more hashes can be stored in the same space. So Rainbow tables are more effective than Lookup tables.

Salted Password Hashing

If we use a salt with password hashing, It’s impossible to crack your passwords through Rainbow tables and lookup tables. In lookup tables, hackers are going to hash same list of passwords and try out in your system. Let’s say two users are having same password in your system. When we hash these passwords, It’s same password hash. In Salting, we are adding a random number along with hashed password. So two users never get same salted password hash. And mind you don’t use same salt with different user passwords, don’t repeat the salting. If new user registers into your system or else change password, generate a new salt. Use a new salt for every user password. If hacker is smart enough, He may be able to crack a one or two user passwords, But not more than that. Eventhough many users have same password, Hacker will not be able to crack their passwords using a lookup table. Don’t use shorter salt, Then hacker can create a lookup table to generate every possible salt.

Let’s see how we can generate a license key

Generate a license key

In this example, we are passing usernam and company code to generate a license key. Using GenerateSalt method, we can generate a random number. I used to create a 32 bytes lenth salt number using RNGCryptoServiceProvider class. Using Rfc289DeriveVytes class we can generate a salted hashing value. Along with the generated license key, we used to store salted number as well.

Let’s see how we can validate the license key.

Validate the license key

I used 64 byte array as a license key and 32 byte array as a salted value. We can use SequenceEqual method to compare entered license key with stored license key as above.

You can find a sample application from here, https://github.com/hansamaligamage/LicenseKey

I want to run a time consuming long process in a one web request

In my application, I want to run a time consuming long process in a one web request.

At the begining, I used to call a web api method to run that process. But it didn’t work. Since the process takes long time to complete its action, request is getting hanged.

We can work on few options to resolve this,

  • We can create a windows service to run this process, It’s a seperate process from the web request. We can periodically check whether action is completed or not until action gets completed, We can install this service in our local pc or server
  • Windows service installed in Azure worker role, If we want to host the windows service in cloud environment, we can host the service in azure worker role.
  • We can use a seperate thread to process the log runing action

Seperate Background worker thread

In my solution, I used to create a background worker process to handle the long running task.

How my code looks like

If we have to use a seperate thread to run a time consuming action, We can use Web backgrounder third party package. It’s going to run a background process in specific intervals. When the task gets completed, it’s going to automatically kill the background process.
Let’s see the code in action!!!

Install Web background worker

First of all, install the web background worker third party library into the project.

Background worker installation

Background worker implementation

This code snippet shows how to initialise a job and how to perform a action on it,

Background worker as in library

I refered to the above code snippet and created a specific worker thread according to my requirements.
actual implementation of worker thread is shown below. Worker class should inherit from IDisposable interface.
In the constructor of the worker class, specify the time interval and then call long running action in a seperate thread.

Background worker

Dispose() method is getting called when process is completed.

Dispose method

Web api controller implementation

default methods

I call this worker process inside a web api controller. Create a private static variable and initialise it with worker class constructor.

note : I added log messages to identify starting point and end point of the worker process, Here is a sample of that log.

log file

Until the task is getting completed, worker thread runs. It’s going to complete the process in second interval. When the task is completed, it’s going to dispose the worker thread.

Schedule your tasks with a windows service

If you want to schedule something to run or your program takes long time to process, Sometimes we may have to create a seperate service application,
What i happened to write this post is, My client wanted me to write an application to send emails in specific time periods, So to achieve that I thought of writing a windows service application.
We can install this service in your server or local computer and configure it to run on intervals using a timer. Let’s start coding.

Create a Windows service

When we create a windows service from visual studio, It gives us a service class with constructor method, OnStart and OnStop methods as follows.

default methods

Scheduling the task with a timer

I need to periodically perform a task, for that i need a timer component, We can add a timer into our service design from toolbox

Adding a timer

Fill up OnStart method

we need to initialise timer component inside the OnStart method, then I set timer interval and added a elapsed event to track each interval.

onStart method

Actual scheduling done in here

inside timer elapsed event, actual task is going to run. elapsed event is called for each 2 minutes according to this code sample

timer Elapsed method

How to stop the execution

to stop the execution, OnStop event is used.

stop event

How to install the windows service

Before installing the service in your pc, we need to create a installer class,

Installer class

Add installer class as shown above

Installer Class

in Installer class, we need to give a service name, so we can identify the service by its name.

Installer class code

Let’s install the service

service is getting created after we build the application. we can find the .exe file in the bin folder. But we can’t install the service by double clicking on it
we have to install it to the local pc or server

InstallUtil

InstallUtil.exe is used to install/uninstall services in local machine or server. We can run installUtil command from Developer command prompt,
type InstallUtil.exe with full path to the service exe file.

Installutil

But this doesn’t going to install the service, It throws an error.

Installutil permission issue

It seems like we don’t have access to install the service, I had to spend few minutes to find the issue,
run Developer commad prompt as administrator, then this permission issue is getting resolved.

We can install a service using cmd as well,

installutil in cmd

run cmd as administrator, then we can install the service using cmd as well.

View services

We can check available services, by just typing services in your program list.

logic of the service

I gave service name as ‘test service’ in installer class.

Windows service on Local Computer started and then stopped

I tried to start the service from the panel, But it didnt work,
I came across with this issue as well, spent lot of hours to find the issue, this issue comes normally when code has some kind of a error. It’s somewhat difficult to debug a windows service application to find out errors,

Debug a windows service application easily

normally in a windows service, program.cs looks like this.

program.cs file

If we want to check whether our service implementation has any issue, we can use this trick

manually start the service

manually start a method that has exact same code as the service implementation.
inside of start method implementation, we can check whether service logic works properly.

logic of the service

using this trick, we can identify our service logic is working fine.

Another way of testing the program logic is, create another console application and call service logic method from console app and verify it works fine.

Debugger Launch

If we want to debug onStart method, we can launch the debugger in start method

launch the debugger

we can launch the debugger like this,

launch the debugger

we can debug the code like this.

launch the debugger

But in here specific file we attatched into debugger is getting loaded. So other files are not loaded. Only we can debug the service file as this code sample shows.

Windows service can’t connect to the database

In my service, i need to access to the database, But it gives me an error like this.

Login failed. Login failed for user ‘NT AUTHORITY\SYSTEM’

windows service is running on ‘NT AUTHORITY\SYSTEM’ login. this login doesn’t seem to have access to the database
To resolve this, add this in your connectionstring, Integrated Security=SSPI or else create a user account for ‘NT AUTHORITY\SYSTEM’ in your database server and give necessary permissions.

These are the guidelines to create a windows service, so it’s your time to try it.

You can find a sample windows service application from here, https://github.com/hansamaligamage/Scheduler