Monday, 20 September 2021

Creating And Hosting ASP.NET Core Application On Linux

 It has been a while since I wanted to write something about ASP.NET Core hosting stuff. Kestrel is another interesting topic from my own perspective. Previously, I have written a lot to cover the basics of ASP.NET Core programming. 

In this one, I will guide you through hosting the ASP.NET Core application natively, using .NET Core libraries that you download during the installation process.

Secondly, it has been a while since I have written anything at all and I might have forgotten the interests of my readers. So, excuse me if I miss a few things.

 Image captured from Scott Hanselman’s blog
Figure 1: Image captured from Scott Hanselman’s blog.

There is a lot of stuff to share in this post today. So, stay tuned and hold your breath. I will be covering the following steps in this article -
  1. Installation of the latest version of .NET Core on Linux environment

    • If you already have a .NET Core framework installed, upgrade your system if it doesn’t support ASP.NET programming as of now.
    • In the previous versions, web development wasn’t supported in .NET Core for Linux operating systems. In the recent versions, it has been added. That's why I insist that you at least install the latest version of .NET Core, before continuing.

  2. Setup an ASP.NET Web Application in your Linux environment

    • I will guide you through many stages, such as development, editing, maintenance, and using an IDE for all of these things.
    • I will walk you through many different areas (not the ASP.NET Area!) in ASP.NET web application’s file hierarchy. Plus, I will tell you what is back and what is about to change (or subject to change in the hierarchy).

  3. Build and run the project

    • In this section, I will guide you through a few of the tips that I  deem helpful to you.
    • Before running the project, I will give you an overview of Kestrel — the webserver for ASP.NET 5.
    • I will, then, move onwards to using the website, which has the same feel as it had in the Windows operating system while developing ASP.NET web applications.
    • Tip- I will give you a tip. By default, an application is uploaded at 5000 port which you would need to change in many cases. I will show you how to change the port of the web application’s hosting service.

  4. Final Words

    Finally, I will head over to final words that I put at the end of every post I write, on any of the platforms that I have to write about.

Installing or upgrading .NET Core

I wrote an article that covered how you can start using .NET Core in a Linux environment. You can read it here. That article was written entirely, to give you a concept of the .NET Core architecture, and a few commands that you can use to do most of the stuff. The only difference between the older article and this section of the post is that this would just contain a later version of .NET Core to be installed on the system. Whereas in the previous one, you had to install the older one.

Try the following.

sudo apt-get update && dist-upgrade


If that doesn’t work or it doesn’t show the updates, head over to the main website for .NET Core, and install the latest version from there.

Creating a new web application

Previously, .NET Core only supported creating libraries or console applications. Currently, it supports ASP.NET web application development too; it also supports the templates for ASP.NET. At the moment, just a simple ASP.NET MVC-oriented web application is created, and I don’t think there is any need for other templates, like Web API, SignalR, single page applications, etc. I believe that is complete at the moment.

To create a new web application, create a new project in .NET Core and pass the type parameter as a web application. This would guide .NET Core (dotnet) to create a new application with the template of the web application.

Creation of a new .NET Core project using web template
Figure 2: Creation of a new .NET Core project using web template.

As you can see in the command above, we are passing a type (-t parameter) to the command, in order to create a new web templated application. The content is as follows.

ASP.NET Web application files and directories in .NET Core
Figure 3: ASP.NET Web application files and directories in .NET Core.

The project looks similar to what we have in the Windows environment. Just a difference of one thing: It includes web.config as well as project.json file. Remember that Microsoft is mostly moving back to MSBuild, and of course, a few of the hosting modules are based on IIS servers. So, that is why web.config file is available in the project. However, the project at the moment uses project.json file for project-level configuration, and (as we have heard mostly during these days) these would be migrated to the MSBuild way of managing the project and other related stuff.

Editing and updating the web application

Microsoft has been pushing the limits for a while. Obviously, in Linux, you already had a few of the best tools for development, but Visual Studio Code is still a better tool. In my previous posts, I said that I don’t like it enough — I still don’t like it very much, it needs work! — but it is better than many tools and IDEs available for C# or .NET-related programming. Since in this post, I said that I won’t be talking about anything third-party, Visual Studio Code is the tool that I am going to suggest, support, and use in this case.

You can install Visual Studio Code from their official website. Note one thing - The Debian packages take a little longer for installation. So, if you also don’t like to wait too much like me, then I would recommend that you download the archive packages and install the IDE from those. There is no installation required at all. You just move the extracted files to a location where you want to store it. Finally, you create a symbolic link to your executable, which can be done like this.

sudo ls -s /home/username/Downloads/VSCode-linux-x64/code /usr/local/bin/code

This would create a link where you can use Visual Studio Code IDE, just by executing this “code” command anywhere in the directory (using the terminal). It would, then, load the directory itself as a project in the IDE, which can be used to update your application’s source code and other stuff that you want to.

Tip- Install the C# extension from the marketplace for a greater experience.

Once this is done, head over to the directory where you created the project. Execute the following command - 

code.

This would trigger the Visual Studio Code to load your directory as the project in the IDE. This is how my environment looks.

Visual Studio Code showing the default ASP.NET directory as a project
Figure 4: Visual Studio Code showing the default ASP.NET directory as a project.

The rest is history — I mean, the rest is the similar effect and feeling that you can get on Windows environment. First of all, when you work this way and follow my lead, you will get the following errors in the IDE window.

Error messages in Visual Studio Code
Figure 5: Error messages in Visual Studio Code.

We will fix them in a moment. But first, understand that these are meant to act like this. If you have had ever programmed in .NET Core, you must have known that before anything else, you need to restore the NuGet packages for your project, even before building the project. Visual Studio Code uses the same IntelliSense and tries to tell you what is going wrong. In doing so, it requires the binaries which are not available. So, you are shown that last error message. The above two are optional while the middle one is a bit optional-required.

Build and run the project

So far, we have created the project. But now, we need to restore the dependencies for our project, which are going to be used by the .NET Core to actually execute our code. By default, a lock file is not generated. So, we need to create a new file and after that, we will be able to build the project.

Execute the following command.

dotnet restore

After this, .NET Core will automatically generate the lock file, and building process can be easily triggered.

Project.lock.json file created after restoring the project
Figure 6: Project.lock.json file created after restoring the project.

We can continue to building the project. I want you to pay attention to this point now. See what happens.

Build and run process of ASP.NET web application on .NET Core
Figure 7: Build and run process of ASP.NET web application on .NET Core.

Now, notice a few things in the above terminal window. First of all, notice that it keeps logging everything.

Secondly, notice that it has a port “5000” appended. We didn’t train it to use that at all, and that also didn’t come from Program.cs file either (you can see that file!). But before I dig any deeper into an explanation of how to change that, I want you to praise Kestrel — The web server of ASP.NET 5.
 
Kestrel is the implementation of libuv async I/O library that helps hosting the ASP.NET applications in a cross-platform environment. The documentation for Kestrel and the reference documentation is also available, and you can get started reading most of the documentation about Kestrel, on the namespace Microsoft.AspNetCore.Server.Kestrel, at the ASP.NET Core reference documentation website.

This is the interesting part because ASP.NET Core can run even on a minimal HTTP listener that can act as a web server. Kestrel is a new web server; it isn’t a full-featured web server but adapts as the community needs updates. It supports HTTP/1 only as of now but would support other features in the coming days. But remember, pushing every single feature and module on one server would actually kill the major purpose of using the .NET Core itself.
 
.NET Core isn’t developed to push everything on the stack, but instead, it is developed to use only the modules and features that are required. Yes, if you want to add a feature, you can update the code and build the service yourself. It is open-sourced on GitHub.

Changing the port number of the application

In many cases, you might want to change the port number where your server listens; or you may also want to make this server the default server for all of your HTTP-based communication on the network. In such cases, you must be having a special port number assigned (80-for default).

For that, head over to your Program.cs file, the main program file (the main function of your project), that is responsible for creating a hosting wrapper for your web application in ASP.NET Core environment. The current content for this object is displayed below.

 Source code for the Program.cs file
Figure 8: Source code for the Program.cs file.

In that chain of “Use” functions, we just need to add one more function call to use a special URL. The function of “UseUrls(“”)” would allow us to update the URLs that are to be used for this web application. So, I am just going to use that function here so that it would let us simply select which URL (and port) to use.

URLs being managed
FIgure 9: URLs being managed.

Now, if you try to run the application, you will run into the following problem in Linux-based system.

Unable to bind to the URL given, error message
Figure 10: Unable to bind to the URL given, error message.

That is pretty much simple — it doesn’t have permission to do the trick. So, what happens on Linux systems is that it is simply performed using the superuser credentials and account.

sudo dotnet run

It would prompt you for your password. Enter your password and this time, the application will run on the localhost:80. In the cases where you have to upload the website to the servers, Azure App Services etc., you are required to have the application running under the server that acts as the default server. So, in those cases, you must handle the default TCP port for HTTP communication for the requests. Otherwise, you might need to work at the backend of NGINX or Apache servers etc. But, that is a different story.

Web server running at port 80
Figure 11: Web server running at port 80.

Now that our server is running, we can go to a web browser to test it out. I am going to use Firefox but you can use any web browser (even a terminal-based one).

ASP.NET Core web application
Figure 12: ASP.NET Core web application being rendered in Firefox, running in Linux using Kestrel web server.

As you can see, the web application runs smoothly. Plus, it also logs any event that takes place. The terminal keeps a record of that. It can also allow you to actually transfer the output from main terminal’s output to a file stream, in order to store everything. But, that is a topic for a different post.

ASP.NET web application’s log in terminal window
Figure 13: ASP.NET web application’s log in terminal window.

As requests come and responses are generated, this window will have more and more content.

Final words

For a while, I wanted to write my own next web application for my own blog and stuff, in ASP.NET Core. At the moment, the framework is “almost” ready for production, but just not yet. Maybe in a couple of the next builds, it will be ready. There are many things that they need to look into. For example, the webserver needs to be more agile — the features need to be provided. That is not it. Visual Studio Code must be fully integrated with ASP.NET Core tooling. At the moment, it just allows us to edit the code. Then, we have to go back to the terminal to do the rest. It should provide us with the ability to do that.

To Microsoft’s team related to .NET Core

Why isn’t .NET Core being published on Linux? I am pretty sure the framework is fully functional, despite the bugs. But there are bugs in the main .NET framework too. There are some minor issues every now and then. My major concern here is to be able to do “sudo apt-get install dotnet”. I can’t remember the longer version names.

To readers

If you are willing to use ASP.NET Core for your production applications, wait for a while. Although ASP.NET Core is a better solution than many other solutions available, but my own recommendation is to stick to ASP.NET 4.6 as of now because that is a more stable version as compared to this one.

How To Deploy .Net Core Application On Linux

 When Microsoft launched their .Net Core framework the key selling point was it is a cross-platform framework, which meant that now we can host our .Net application not only on  Windows but on Linux too, so let’s see how we can deploy .Net core application on Linux.

 
Step 1 - Publish your .Net Core application
 
First, create a .Net core application on VS; you can make an MVC project or Web API project and if you already have an existing project, then open it.
  1. Right Click on your project
  2. Click on publish
  3. Now create a new publish profile, and browse the folder where you want to publish your project dll
  4. Click on publish so it will create your dll in the folder
Step 2 - Install required .Net Module on Linux
 
Now we have our web application dll and now we need to host it on the Linux environment. First, we need to understand how the deployment works in Linux. .Net applications run on Kestrel servers and we run Apache or Nginx server in Linux environments, which acts as a proxy server and handles the traffic from outside the machine and redirects it to the Kestrel server so we will have Apache or Nginx server as the middle layer.
 
In this article, we will use Apache as a proxy server.
 
First, we need to install the .Net core module in our Linux environment. For that run the following commands,
  • sudo apt-get update
  • sudo apt-get install apt-transport-HTTPS
  • sudo apt-get update
  • sudo apt-get install dotnet-sdk-3.1
  • sudo apt-get install dotnet-runtime-3.1
  • sudo apt-get install aspnetcore-runtime-3.1
Step 3 - Install and configure Apache Server
 
So now we have all the required .Net packages. I have installed an additional package so if you are running a different project it will help.
 
Now install the Apache server,
  • sudo apt-get install apache2
  • sudo a2enmod proxy proxy_http proxy_html proxy_wstunnel
  • sudo a2enmod rewrite
Now we need to make a conf file to set up our proxy on Apache. Create the following file:
  • sudo nano /etc/apache2/conf-enabled/netcore.conf
Now copy the following configuration in that file,
  1. <VirtualHost *:80>  
  2.    ServerName www.DOMAIN.COM  
  3.    ProxyPreserveHost On  
  4.    ProxyPass / http://127.0.0.1:5000/  
  5.    ProxyPassReverse / http://127.0.0.1:5000/  
  6.    RewriteEngine on  
  7.    RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]  
  8.    RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]  
  9.    RewriteRule /(.*) ws://127.0.0.1:5000/$1 [P]  
  10.    ErrorLog /var/log/apache2/netcore-error.log  
  11.    CustomLog /var/log/apache2/netcore-access.log common  
  12. </VirtualHost>  
<VirtualHost *:80>
 
This tag defines the IP and port it will bind Apache so we will access our application from outside our Linux environment through this Ip:Port.
 
Now restart the Apache server,
  • sudo service apache2 restart
  • sudo apachectl configtest
Step 4 - Configure and Start Service 
 
Move your dll to the defined path with the below command.

"sudo cp -a ~/release/ /var/netcore/" 

Create a service file for our .Net application
 
"sudo nano /etc/systemd/system/ServiceFile.service"
 
Copy the following configuration in that file and  it will run our application,
  1. [Unit]  
  2. Description=ASP .NET Web Application  
  3. [Service]  
  4. WorkingDirectory=/var/netcore  
  5. ExecStart=/usr/bin/dotnet /var/netcore/Application.dll  
  6. Restart=always  
  7. RestartSec=10  
  8. SyslogIdentifier=netcore-demo  
  9. User=www-data  
  10. Environment=ASPNETCORE_ENVIRONMENT=Production  
  11. [Install]  
  12. WantedBy=multi-user.target  
ExecStart=/usr/bin/dotnet /var/netcore/Application.dll in this line replace Application.dll with your dll name that you want to run.
 
Now start the service. Instead of the service name in the below commands use the name of the file made above,
  • sudo systemctl enable {Service Name}
  • sudo systemctl start {Service Name}
Now your proxy server and kestrel server is running and you can access your application through any ip with port 80.
 
To redeploy the code your need to replace the dll and stop and start your service again through the following commands
  • sudo systemctl stop {Service Name}
  • sudo systemctl start {Service Name}

Wednesday, 15 September 2021

CRUD Operations Using Web API 2 And Knockout.js

 In this article, I will demonstrate how we can perform simple CRUD (Create, Read, Update, Delete) operations using ASP.NET Web API 2 and Knockout.js library. Here, the purpose is to give you an idea of how to use knockout.js with Web API 2. I hope you will like this.

Prerequisites

As I said before, to achieve our requirement, you must have Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.

In this post, we are going to

  • Create an MVC application.
  • Configuring Entity framework ORM to connect to database.
  • Implementing all HTTP Services needed.
  • Calling Services using Knockout.js library.

So, let’s understand a bit about knockout.js

What’s Knockout.js?

Knockout is a JavaScript library that helps you to create a rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainable.

Headline features,

  • Elegant dependency tracking - automatically updates the right parts of your UI whenever your data model changes.
  • Declarative bindings - a simple and obvious way to connect parts of your UI to your data model. You can construct complex dynamic UIs easily using arbitrarily nested binding contexts.
  • Trivially extensible - implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.

SQL Database part

Here, find the script to create a database and table.

  1. Create Database  
  2. USE [master]  
  3. GO  
  4.   
  5. /****** Object  Database [DBCustomer]    Script Date 3/4/2017 32357 PM ******/  
  6. CREATE DATABASE [DBCustomer]  
  7.  CONTAINMENT = NONE  
  8.  ON  PRIMARY   
  9. NAME = N'DBCustomer', FILENAME = N'c\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBCustomer.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  10.  LOG ON   
  11. NAME = N'DBCustomer_log', FILENAME = N'c\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBCustomer_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  12. GO  
  13.   
  14. ALTER DATABASE [DBCustomer] SET COMPATIBILITY_LEVEL = 110  
  15. GO  
  16.   
  17. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  18. begin  
  19. EXEC [DBCustomer].[dbo].[sp_fulltext_database] @action = 'enable'  
  20. end  
  21. GO  
  22.   
  23. ALTER DATABASE [DBCustomer] SET ANSI_NULL_DEFAULT OFF   
  24. GO  
  25.   
  26. ALTER DATABASE [DBCustomer] SET ANSI_NULLS OFF   
  27. GO  
  28.   
  29. ALTER DATABASE [DBCustomer] SET ANSI_PADDING OFF   
  30. GO  
  31.   
  32. ALTER DATABASE [DBCustomer] SET ANSI_WARNINGS OFF   
  33. GO  
  34.   
  35. ALTER DATABASE [DBCustomer] SET ARITHABORT OFF   
  36. GO  
  37.   
  38. ALTER DATABASE [DBCustomer] SET AUTO_CLOSE OFF   
  39. GO  
  40.   
  41. ALTER DATABASE [DBCustomer] SET AUTO_CREATE_STATISTICS ON   
  42. GO  
  43.   
  44. ALTER DATABASE [DBCustomer] SET AUTO_SHRINK OFF   
  45. GO  
  46.   
  47. ALTER DATABASE [DBCustomer] SET AUTO_UPDATE_STATISTICS ON   
  48. GO  
  49.   
  50. ALTER DATABASE [DBCustomer] SET CURSOR_CLOSE_ON_COMMIT OFF   
  51. GO  
  52.   
  53. ALTER DATABASE [DBCustomer] SET CURSOR_DEFAULT  GLOBAL   
  54. GO  
  55.   
  56. ALTER DATABASE [DBCustomer] SET CONCAT_NULL_YIELDS_NULL OFF   
  57. GO  
  58.   
  59. ALTER DATABASE [DBCustomer] SET NUMERIC_ROUNDABORT OFF   
  60. GO  
  61.   
  62. ALTER DATABASE [DBCustomer] SET QUOTED_IDENTIFIER OFF   
  63. GO  
  64.   
  65. ALTER DATABASE [DBCustomer] SET RECURSIVE_TRIGGERS OFF   
  66. GO  
  67.   
  68. ALTER DATABASE [DBCustomer] SET  DISABLE_BROKER   
  69. GO  
  70.   
  71. ALTER DATABASE [DBCustomer] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  72. GO  
  73.   
  74. ALTER DATABASE [DBCustomer] SET DATE_CORRELATION_OPTIMIZATION OFF   
  75. GO  
  76.   
  77. ALTER DATABASE [DBCustomer] SET TRUSTWORTHY OFF   
  78. GO  
  79.   
  80. ALTER DATABASE [DBCustomer] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  81. GO  
  82.   
  83. ALTER DATABASE [DBCustomer] SET PARAMETERIZATION SIMPLE   
  84. GO  
  85.   
  86. ALTER DATABASE [DBCustomer] SET READ_COMMITTED_SNAPSHOT OFF   
  87. GO  
  88.   
  89. ALTER DATABASE [DBCustomer] SET HONOR_BROKER_PRIORITY OFF   
  90. GO  
  91.   
  92. ALTER DATABASE [DBCustomer] SET RECOVERY SIMPLE   
  93. GO  
  94.   
  95. ALTER DATABASE [DBCustomer] SET  MULTI_USER   
  96. GO  
  97.   
  98. ALTER DATABASE [DBCustomer] SET PAGE_VERIFY CHECKSUM    
  99. GO  
  100.   
  101. ALTER DATABASE [DBCustomer] SET DB_CHAINING OFF   
  102. GO  
  103.   
  104. ALTER DATABASE [DBCustomer] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  105. GO  
  106.   
  107. ALTER DATABASE [DBCustomer] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  108. GO  
  109.   
  110. ALTER DATABASE [DBCustomer] SET  READ_WRITE   
  111. GO  
  112.   
  113.   
  114. Create Table  
  115. USE [DBCustomer]  
  116. GO  
  117.   
  118. /****** Object  Table [dbo].[Customer]    Script Date 3/4/2017 32449 PM ******/  
  119. SET ANSI_NULLS ON  
  120. GO  
  121.   
  122. SET QUOTED_IDENTIFIER ON  
  123. GO  
  124.   
  125. SET ANSI_PADDING ON  
  126. GO  
  127.   
  128. CREATE TABLE [dbo].[Customer](  
  129.     [CustID] [int] IDENTITY(1,1) NOT NULL,  
  130.     [FirstName] [varchar](50) NULL,  
  131.     [LastName] [varchar](50) NULL,  
  132.     [Email] [varchar](50) NULL,  
  133.     [Country] [varchar](50) NULL,  
  134.  CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED   
  135. (  
  136.     [CustID] ASC  
  137. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  138. ON [PRIMARY]  
  139.   
  140. GO  
  141.   
  142. SET ANSI_PADDING OFF  
  143. GO   

Create your MVC application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.


Next, a new dialog will pop up for selecting the template. We are going to choose the Web API template and click the Ok button.


After creating our project, we are going to add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

For adding ADO.NET Entity Framework, right-click on the project name, click Add > Add New Item. A dialog box will pop up. Inside Visual C#, select Data >> ADO.NET Entity Data Model, and enter a name for your Dbcontext model as CustomerModel.

Finally,  click Add.
 

Next, we need to choose EF Designer from the database as a model container.


As you can see below, we need to select Server name, then via drop-down list, connect to a database panel. You should choose your database name. Finally, click OK.




Now, the dialog Entity Data Model Wizard will pop up for choosing the object which we need to use. In our case, we are going to choose the Customers table and click the "Finish" button.

Finally, we see that the EDMX model generates a Customer class.
 



Create a Controller

Now, we are going to create a Controller. Right-click on the Controllers folder and go to Add > Controller> selecting Web API 2 Controller with actions using Entity Framework > click Add.


In the snapshot given below, we are providing three important parameters

  • Model class Customer represents the entity that should be used for CRUD operations.
  • Data context class used to establish a connection with the database.
  • Finally, we need to name our Controller (in this case Customers Controller).


As we already know, Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients including browsers and mobile devices.

It has four methods where

  • Get is used to select data.
  • Post is used to create or insert data.
  • Put is used to update data.
  • Delete is used to delete data.

CustomersController.cs 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web.Http;  
  10. using System.Web.Http.Description;  
  11. using CustomerApp;  
  12. using CustomerApp.Models;  
  13.   
  14. namespace CustomerApp.Controllers  
  15. {  
  16.     public class CustomersController  ApiController  
  17.     {  
  18.         //DbContext  
  19.         private DBCustomerEntities db = new DBCustomerEntities();  
  20.   
  21.         // GET api/Customers  
  22.         public IQueryable<Customer> GetCustomers()  
  23.         {  
  24.             return db.Customers;  
  25.         }  
  26.   
  27.          
  28.   
  29.         // PUT api/Customers/5  
  30.         [ResponseType(typeof(void))]  
  31.         public IHttpActionResult PutCustomer(int id, Customer customer)  
  32.         {  
  33.             if (!ModelState.IsValid)  
  34.             {  
  35.                 return BadRequest(ModelState);  
  36.             }  
  37.   
  38.             if (id != customer.CustID)  
  39.             {  
  40.                 return BadRequest();  
  41.             }  
  42.   
  43.             db.Entry(customer).State = EntityState.Modified;  
  44.   
  45.             try  
  46.             {  
  47.                 db.SaveChanges();  
  48.             }  
  49.             catch (DbUpdateConcurrencyException)  
  50.             {  
  51.                 if (!CustomerExists(id))  
  52.                 {  
  53.                     return NotFound();  
  54.                 }  
  55.                 else  
  56.                 {  
  57.                     throw;  
  58.                 }  
  59.             }  
  60.   
  61.             return StatusCode(HttpStatusCode.NoContent);  
  62.         }  
  63.   
  64.         // POST api/Customers  
  65.         [ResponseType(typeof(Customer))]  
  66.         public IHttpActionResult PostCustomer(Customer customer)  
  67.         {  
  68.             if (!ModelState.IsValid)  
  69.             {  
  70.                 return BadRequest(ModelState);  
  71.             }  
  72.   
  73.             db.Customers.Add(customer);  
  74.             db.SaveChanges();  
  75.   
  76.             return CreatedAtRoute("DefaultApi"new { id = customer.CustID }, customer);  
  77.         }  
  78.   
  79.         // DELETE api/Customers/5  
  80.         [ResponseType(typeof(Customer))]  
  81.         public IHttpActionResult DeleteCustomer(int id)  
  82.         {  
  83.             Customer customer = db.Customers.Find(id);  
  84.             if (customer == null)  
  85.             {  
  86.                 return NotFound();  
  87.             }  
  88.   
  89.             db.Customers.Remove(customer);  
  90.             db.SaveChanges();  
  91.   
  92.             return Ok(customer);  
  93.         }  
  94.         //GetCustomerByCountry returns list of nb customers by country   
  95.        [Route("Customers/GetCustomerByCountry")]  
  96.         public IList<CustomerData> GetCustomerByCountry()  
  97.         {  
  98.             List<string> countryList = new List<string>() { "Morocco""India""USA""Spain" };  
  99.             IEnumerable<Customer> customerList = db.Customers;  
  100.             List <CustomerData> result = new List<CustomerData>();  
  101.   
  102.             foreach (var item in countryList)  
  103.             {  
  104.                 int nbCustomer = customerList.Where(c => c.Country == item).Count();  
  105.                 result.Add(new CustomerData()  
  106.                 {  
  107.                     CountryName = item,  
  108.                     value = nbCustomer  
  109.                 });  
  110.             }  
  111.   
  112.             if(result != null)  
  113.             {  
  114.                 return result;  
  115.             }  
  116.   
  117.             return null;  
  118.   
  119.   
  120.   
  121.         }  
  122.   
  123.         protected override void Dispose(bool disposing)  
  124.         {  
  125.             if (disposing)  
  126.             {  
  127.                 db.Dispose();  
  128.             }  
  129.             base.Dispose(disposing);  
  130.         }  
  131.   
  132.         private bool CustomerExists(int id)  
  133.         {  
  134.             return db.Customers.Count(e => e.CustID == id) > 0;  
  135.         }  
  136.     }  
  137. }   

Calling Services using Knockout.js library

First of all, we are installing the knockout.js library. From the solution explorer panel, right-click on references > Manage NuGet Packages…


Next, type Knockout.js in the search text box, select the first line as below and click on the Install button.


Now, we need to add new js file. Right click on scripts folder > Add > JavaScript File.


App.js

Here, we create our View Model that contains all the business logic, and then, we bind it with ko.applyBindings(new ViewModel()) which is enabled to activate knockout for the current HTML document.

As you can see in the below code, ko provides observables to bind to the Model.

  • observable() is used to define Model properties that can notify the changes and update the Model automatically.
  • observableArray([]) is used to bind list of elements.
    1. var ViewModel = function () {  
    2.   
    3.     var self = this;  
    4.     self.CustID = ko.observable();  
    5.     self.FirstName = ko.observable();  
    6.     self.LastName = ko.observable();  
    7.     self.Email = ko.observable();  
    8.     self.CountryList = ko.observableArray(['Morocco''India''USA''Spain']);  
    9.     self.Country = ko.observable();  
    10.   
    11.     self.customerList = ko.observableArray([]);  
    12.   
    13.     var CustomerUri = '/api/Customers/';  
    14.   
    15.       
    16.   
    17.     function ajaxFunction(uri, method, data) {  
    18.   
    19.         //self.errorMessage('');  
    20.   
    21.         return $.ajax({  
    22.   
    23.             type method,  
    24.             url uri,  
    25.             dataType 'json',  
    26.             contentType 'application/json',  
    27.             data data ? JSON.stringify(data)  null  
    28.   
    29.         }).fail(function (jqXHR, textStatus, errorThrown) {  
    30.             alert('Error  ' + errorThrown);  
    31.         });  
    32.     }  
    33.   
    34.   
    35.     // Clear Fields  
    36.     self.clearFields = function clearFields() {  
    37.         self.FirstName('');  
    38.         self.LastName('');  
    39.         self.Email('');  
    40.         self.Country('');  
    41.     }  
    42.   
    43.     //Add new Customer  
    44.     self.addNewCustomer = function addNewCustomer(newCustomer) {  
    45.   
    46.         var CustObject = {  
    47.             CustID self.CustID(),  
    48.             FirstName: self.FirstName(),  
    49.             LastName self.LastName(),  
    50.             Email self.Email(),  
    51.             Country self.Country()  
    52.         };  
    53.         ajaxFunction(CustomerUri, 'POST', CustObject).done(function () {  
    54.   
    55.             self.clearFields();  
    56.             alert('Customer Added Successfully !');  
    57.             getCustomerList()  
    58.         });  
    59.     }  
    60.   
    61.     //Get Customer List  
    62.     function getCustomerList() {  
    63.         $("div.loadingZone").show();  
    64.         ajaxFunction(CustomerUri, 'GET').done(function (data) {  
    65.             $("div.loadingZone").hide();  
    66.             self.customerList(data);  
    67.         });  
    68.   
    69.     }  
    70.   
    71.     //Get Detail Customer  
    72.     self.detailCustomer = function (selectedCustomer) {  
    73.   
    74.         self.CustID(selectedCustomer.CustID);  
    75.         self.FirstName(selectedCustomer.FirstName);  
    76.         self.LastName(selectedCustomer.LastName);  
    77.         self.Email(selectedCustomer.Email);  
    78.         self.Country(selectedCustomer.Country);  
    79.   
    80.         $('#Save').hide();  
    81.         $('#Clear').hide();  
    82.   
    83.         $('#Update').show();  
    84.         $('#Cancel').show();  
    85.   
    86.     };  
    87.   
    88.     self.cancel = function () {  
    89.   
    90.         self.clearFields();  
    91.   
    92.         $('#Save').show();  
    93.         $('#Clear').show();  
    94.   
    95.         $('#Update').hide();  
    96.         $('#Cancel').hide();  
    97.     }  
    98.   
    99.     //Update Customer  
    100.     self.updateCustomer = function () {  
    101.   
    102.         var CustObject = {  
    103.             CustID self.CustID(),  
    104.             FirstName self.FirstName(),  
    105.             LastName self.LastName(),  
    106.             Email self.Email(),  
    107.             Country self.Country()  
    108.         };  
    109.   
    110.         ajaxFunction(CustomerUri + self.CustID(), 'PUT', CustObject).done(function () {  
    111.             alert('Customer Updated Successfully !');  
    112.             getCustomerList();  
    113.             self.cancel();  
    114.         });  
    115.     }  
    116.   
    117.     //Delete Customer  
    118.     self.deleteCustomer = function (customer) {  
    119.   
    120.         ajaxFunction(CustomerUri + customer.CustID, 'DELETE').done(function () {  
    121.   
    122.             alert('Customer Deleted Successfully');  
    123.             getCustomerList();  
    124.         })  
    125.   
    126.     }  
    127.   
    128.     //Chart Line function used to display a chart which represents nb of customers by country  
    129.     function chartLine() {  
    130.   
    131.         ajaxFunction('http//localhost50706/Customers/GetCustomerByCountry''GET').done(function (result) {  
    132.             console.log(result);  
    133.             Morris.Line({  
    134.                 element 'line-chart',  
    135.                 data result,  
    136.                 xkey 'CountryName',  
    137.                 // A list of names of data record attributes that contain y-values.  
    138.                 ykeys ['value'],  
    139.                 // Labels for the ykeys -- will be displayed when you hover over the  
    140.                 // chart.  
    141.                 labels ['Value'],  
    142.   
    143.                 parseTime false  
    144.             });  
    145.   
    146.   
    147.         });  
    148.   
    149.     };  
    150.   
    151.     chartLine();  
    152.     getCustomerList();  
    153.   
    154. };  
    155.   
    156. ko.applyBindings(new ViewModel());  

Now, from Solution Explorer panel, we are going to add index.html file as shown below.


Index.html 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.   
  5.     <meta charset="utf-8">  
  6.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.   
  9.     <title>. Customer App . Web API2 Á KnockOutJS</title>  
  10.     <meta charset="utf-8" />  
  11.   
  12.     <!-- CSS -->  
  13.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  14.     <link href="https//cdn.oesmith.co.uk/morris-0.5.1.css" rel="stylesheet" />  
  15.       
  16.     
  17.   
  18. </head>  
  19. <body>  
  20.   
  21.     <nav class="navbar navbar-default navbar-fixed-top">  
  22.   
  23.         <div class="container-fluid">  
  24.   
  25.             <div class="navbar-header">  
  26.                 <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">  
  27.                     <span class="sr-only">Toggle navigation</span>  
  28.                     <span class="icon-bar"></span>  
  29.                     <span class="icon-bar"></span>  
  30.                     <span class="icon-bar"></span>  
  31.                 </button>  
  32.                 <a class="navbar-brand" href="#">WEB API2 - KnockOutJS</a>  
  33.             </div> <!-- END HEADER NAV -->  
  34.   
  35.         </div> <!-- END CONTAINER -->  
  36.   
  37.     </nav><!-- END NAV-->  
  38.   
  39.     <div class="container" style="margin-top 7%;">  
  40.   
  41.   
  42.         <div class="row">  
  43.   
  44.             <div class="col-md-4">  
  45.   
  46.                 <!-- FORM -->  
  47.                 <div class="panel panel-default">  
  48.   
  49.                     <div class="panel-heading"> <span class="glyphicon glyphicon glyphicon-tag" aria-hidden="true"></span> <b>Add New Customer</b></div>  
  50.                     <div class="panel-body">  
  51.   
  52.                         <form>  
  53.   
  54.                             <div class="form-group" style="displaynone;">  
  55.                                 <label for="CustomerID">Customer ID</label>  
  56.                                 <input type="text" id="CustomerID" class="form-control" data-bind="valueCustID" placeholder="Customer ID" />  
  57.                             </div><!-- END CUSTOMER ID -->  
  58.   
  59.                             <div class="form-group">  
  60.                                 <label for="FirstName">First Name</label>  
  61.                                 <input type="text" id="FirstName" class="form-control" data-bind="valueFirstName" placeholder="First Name" />  
  62.                             </div><!-- END FIRST NAME -->  
  63.   
  64.                             <div class="form-group">  
  65.                                 <label for="LastName">Last Name</label>  
  66.                                 <input type="text" id="LastName" class="form-control" data-bind="value LastName" placeholder="Last Name" />  
  67.                             </div><!-- END LAST NAME -->  
  68.   
  69.                             <div class="form-group">  
  70.                                 <label for="Email">Email</label>  
  71.                                 <input type="email" id="Email" class="form-control" data-bind="value Email" placeholder="Email" />  
  72.                             </div> <!-- END EMAIL -->  
  73.   
  74.                             <div class="form-group">  
  75.                                 <label for="Country">Country</label>  
  76.                                 <select class="form-control" data-bind="options CountryList, value Country, optionsCaption 'Select your Country ...' " ></select>  
  77.                             </div> <!-- END COUNTRY -->  
  78.   
  79.   
  80.                             <button type="button" class="btn btn-success" data-bind="click addNewCustomer" id="Save">  
  81.                                 <span class="glyphicon  glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save  
  82.                             </button>  
  83.   
  84.                             <button type="button" class="btn btn-info" data-bind="click clearFields" id="Clear">  
  85.                                 <span class="glyphicon  glyphicon glyphicon-refresh" aria-hidden="true"></span> Clear  
  86.                             </button>  
  87.   
  88.                             <button type="button" class="btn btn-warning" data-bind="clickupdateCustomer " style="display:none;" id="Update">  
  89.                                 <span class="glyphicon  glyphicon glyphicon-pencil" aria-hidden="true"></span> Update Customer  
  90.                             </button>  
  91.   
  92.                             <button type="button" class="btn btn-default" data-bind="clickcancel " style="displaynone;" id="Cancel">  
  93.                                 <span class="glyphicon  glyphicon glyphicon-remove" aria-hidden="true"></span> Cancel  
  94.                             </button>  
  95.   
  96.                         </form> <!-- END FORM -->  
  97.   
  98.   
  99.                     </div> <!-- END PANEL BODY-->  
  100.   
  101.                 </div><!-- END PANEL-->  
  102.   
  103.             </div> <!-- END  col-md-4 -->  
  104.   
  105.             <div class="col-md-8">  
  106.   
  107.                 <div class="panel panel-default">  
  108.   
  109.                     <div class="panel-heading"><span class="glyphicon  glyphicon glyphicon-stats" aria-hidden="true"></span><b> Charting Customer</b>   </div>  
  110.   
  111.                     <div class="panel-body">  
  112.   
  113.   
  114.                         <!-- <img src="images/Chart.png" style="width60%; margin6px 70px;" /> -->  
  115.   
  116.                         <div id="line-chart" style="height 300px;"></div><br/><br/>  
  117.   
  118.                     </div> <!-- END PANEL-BODY-->  
  119.   
  120.                 </div> <!-- END PANEL-->  
  121.   
  122.             </div> <!-- END col-md-8-->  
  123.   
  124.         </div>  
  125.   
  126.         <div class="row">  
  127.   
  128.             <div class="col-md-12">  
  129.   
  130.                 <div class="panel panel-default">  
  131.   
  132.                     <div class="panel-heading">  
  133.                         <span class="glyphicon  glyphicon glyphicon-zoom-in" aria-hidden="true"></span>  <b>Customer List </b>  
  134.                         <div class="loadingZone" style="color #000; displayblock; floatright; displaynone;"> <img src="images/ajax-loader.gif" /> Refresh Data ...</div>  
  135.                     </div>  
  136.   
  137.                     <div class="panel-body">  
  138.   
  139.                         <table class="table table-hover">  
  140.   
  141.                             <thead>  
  142.                                 <tr>  
  143.                                     <th><span class="glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span></th>  
  144.                                     <th>#</th>  
  145.                                     <th>First Name</th>  
  146.                                     <th>Last Name</th>  
  147.                                     <th>Email</th>  
  148.                                     <th>Country</th>  
  149.                                     <th></th>  
  150.                                 </tr>  
  151.                             </thead> <!-- END THEAD -->  
  152.   
  153.                             <tbody data-bind="foreach customerList">  
  154.   
  155.                                 <tr>  
  156.   
  157.                                     <td> <button type="button" class="btn btn-default btn-xs" data-bind="click $root.detailCustomer"> <span class="glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span></button> </td>  
  158.                                     <td> <span data-bind="text CustID"></span> </td>  
  159.                                     <td> <span data-bind="text FirstName"></span></td>  
  160.                                     <td> <span data-bind="text LastName"></span></td>  
  161.                                     <td> <span data-bind="text Email"></span> </td>  
  162.                                     <td> <span data-bind="text Country"></span> </td>  
  163.   
  164.                                     <td>  
  165.   
  166.                                         <button type="button" class="btn btn-danger btn-xs">  
  167.                                             <span class="glyphicon glyphicon glyphicon-trash" aria-hidden="true" data-bind="click $root.deleteCustomer"></span>  
  168.                                         </button>  
  169.                                     </td>  
  170.   
  171.                                 </tr>  
  172.   
  173.                                   
  174.   
  175.                             </tbody> <!-- END TBODY -->  
  176.   
  177.                         </table> <!-- END TABLE -->  
  178.   
  179.   
  180.                     </div>  
  181.   
  182.                 </div>  
  183.   
  184.             </div>  
  185.   
  186.         </div>  
  187.     </div> <!-- END CONTAINER-->  
  188.   
  189.     <!-- JS -->  
  190.     <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->  
  191.     <script src="Scripts/jquery-1.10.2.min.js"></script>  
  192.     <!-- Include all compiled plugins (below), or include individual files as needed -->  
  193.     <script src="Scripts/bootstrap.min.js"></script>  
  194.     <script src="Scripts/knockout-3.4.0.js"></script>  
  195.   
  196.     <script src="https//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>  
  197.     <script src="https//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>  
  198.     <!-- app.js-->  
  199.     <script src="Scripts/app.js"></script>  
  200.      
  201. </body>  
  202. </html>   

In order to exchange the data between the HTML page and JavaScript file, knockout.js offers various types of bindings that should be used within the data-bind attribute.

  • Click represents a click event handler to call the JavaScript function.
  • The value represents the value binding with UI elements to the property defined into the view Model.
  • The text represents the text value to the UI element.
  • Foreach is used to fetch an array.

Now, you can run your application. Don’t forget to change the URL address as below.

http//localhost55192/index.html

Let’s see the output.




That’s all, Please send your feedback and queries in the comments box.