How To Add Docker Support For Existing ASP.NET Project

In this article we will learn how to add docker support for existing ASP.NET  or any .NET application, before enabling docker support let's know about the docker in brief

What is Docker?

Docker is one of the platform for containerizing the applications which allows to deliver the application in packages over the operating machine level virtualization. Docker allows to run and create the images in Linux and windows containers etc.

Step 1: Install Prerequisites

You need to install the docker client based on your operating system on your machine. you can download the docker by using the following link

The installed docker desktop client will be look like as shown in the following image, 


Hope you installed the prerequisites.

Step 2: Open Existing Application

Open your existing application in visual studio as shown in the following image


Docker client helps to create and run the docker images locally as well as created images you can push in to the any image container registry such as ACR or docker hub.

Step 3: Add Docker Support

Now right click on the solution explorer of your existing project and follows the steps which are shown in the following image


Once you click on the Docker Support option , It will prompt the screen which is shown in the step 4.

Step 4: Choose the Container

Choose the target operating system on which type of container you wants to run the application. Let's choose the Linux option which creates the image size smaller than windows container image.


In the preceding image click on the OK button, it will create the Docker file in your project solution as shown in the following image



Step 5: Open the Docker File

Now double click on docker file, it has following auto generated code from visual studio which has pre-configured steps to create and run the docker image 


Step 6:  Run the image in Docker Container

Choose the docker option to run the application as shown in the following image


After clicking on docker option, application runs inside the docker container as shown in the following image
 

Now our application running inside the Docker container instead of IIS express.

Note

This tutorial is for beginner so there is no command line tool used to build , run the docker container images in this tutorial. The intend of this tutorial to make familiar to beginners about docker and let them know docker is not difficult to learn.

Summary

I hope the preceding article is useful to understand how to enable the docker support for existing ASP.NET project with less efforts.

If you like my efforts and intend then support me by subscribing my YouTube Channel and blog by using the following links

Get Data in ASP.NET MVC Using Web API

This article  explains step by step how to get data in ASP.NET MVC using web api. To demonstrate this lets create simple ASP.NET MVC application before it if you are new and wants to learn web API REST service from creating to hosting to consuming in client application.
In this article, we will use the same hosted Web API REST service  to consume in our created ASP.NET MVC web application. Now, let's start consuming Web API REST service in ASP.NET MVC application step by step.

Step 1 - Create ASP.NET MVC Application.

  1. "Start", followed by "All Programs" and select "Microsoft Visual Studio".
  2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name as you wish and click OK.
  3. After clicking, the following Window will appear. Choose empty project template and check on MVC option.

The preceding step creates the simple empty ASP.NET MVC application without model, view, and controller, the solution explorer of created web application will look like the following.


Step 2 - Install HttpClient library from NuGet

We are going to use HttpClient to consume the web api, so we need to install this library from nuget package manager

What is HttpClient ?

HttpClient is base class which is responsible to send HTTP request and receive HTTP response resources i.e from REST services.

To install HttpClient, right click on Solution Explorer of created application and search for HttpClient, as shown in the following image.


Step 3 - Install WebAPI.Client library from NuGet

This package is used for formatting and content negotiation which provides support for System.Net.Http. To install, right click on Solution Explorer of created application and search for WebAPI.Client, as shown in following image.



Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds depending on your internet speed. We have installed necessary NuGet packages to consume Web API REST services in web application. I hope you have followed the same steps.

Step 4 - Create Model Class 

Now, let us create the model class named Employee.cs  or as you wish, by right clicking on models folder with same number of entities which are exposing by our hosted Web API REST service to exchange the data. The code snippet of created Employee.cs class will look like as follows

    public class Employee  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
                 
        public string City { get; set; }  
      
    }   

Step 5 - Add Controller Class

Now, let us add ASP.NET MVC controller, as shown in the screenshot given below.


After clicking add button, it will show in the window. specify the controller name as Home with suffix controller. Now, let's modify the default code of  Home controller . Our hosted Web API REST Service includes these two methods, as given below.
  • GetAllEmployees (GET )
  • GetEmployeeById (POST ) which takes id as input parameter 
The url of the hosted web API REST Service is 

http://192.168.95.1:5555/api/Employee/GetAllEmployees

In the preceding url
  • http://localhost:56290 Is the base address of web API service, It can be different as per your server
  • api It is the used to differentiate between Web API controller and MVC controller request
  • Employee This is the Web API controller name
  • GetAllEmployees This is the Web API method which returns the all employee list
After modifying the code of Homecontroller class, the code will look like the following.

Homecontroller.cs
using ConsumingWebAapiRESTinMVC.Models;  
using Newtonsoft.Json;  
using System;  
using System.Collections.Generic;  
using System.Net.Http;  
using System.Net.Http.Headers;  
using System.Threading.Tasks;  
using System.Web.Mvc;  
  
namespace ConsumingWebAapiRESTinMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
        //Hosted web API REST Service base url  
        string Baseurl = "http://192.168.95.1:5555/";      
        public async Task<ActionResult> Index()  
        {  
            List<Employee> EmpInfo = new List<Employee>();  
              
            using (var client = new HttpClient())  
            {  
                //Passing service base url  
                client.BaseAddress = new Uri(Baseurl);  
  
                client.DefaultRequestHeaders.Clear();  
                //Define request data format  
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
                  
                //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
                HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");  
  
                //Checking the response is successful or not which is sent using HttpClient  
                if (Res.IsSuccessStatusCode)  
                {  
                    //Storing the response details recieved from web api   
                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;  
  
                    //Deserializing the response recieved from web api and storing into the Employee list  
                    EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);  
  
                }  
                //returning the employee list to view  
                return View(EmpInfo);  
            }  
        }  
    }  
}  

I hope, you have gone through the same steps and understood about the how to use and call Web API REST service resource using HttpClient .

Step 6 - Create strongly typed View

Now, right click on Views folder of the created application and create strongly typed View named by Index by choosing Employee class to display the employee list from hosted web API REST Service, as shown in the following image.


Now, click on "Add" button. It will create View named index after modifying the default code. The code snippet of the Index View looks like the following.

Index.cshtml 
@model IEnumerable<ConsumingWebAapiRESTinMVC.Models.Employee>  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
<div class="form-horizontal">  
  
    <hr />  
    <div class="form-group">  
  
  
        <table class="table table-responsive" style="width:400px">  
            <tr>  
                <th>  
                    @Html.DisplayNameFor(model => model.Name)  
                </th>  
                <th>  
                    @Html.DisplayNameFor(model => model.City)  
                </th>  
                  
            </tr>  
  
            @foreach (var item in Model) {  
                <tr>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.Name)  
                    </td>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.City)  
                    </td>  
                      
                </tr>  
}  
  
        </table>  
    </div>  
</div>  

The preceding View will display all employees list . Now, we have done all the coding.


Step 7 - Run the Application

After running the application, the employee list from hosted web api REST service will look like this.



I hope, from the above examples, you have learned how get data in ASP.NET MVC using web api

Note
  • In this article, the optimization is not covered in depth; do it as per your skills.
Summary

I hope, this article is useful for all the readers to learn about getting data from web api in ASP.NET MVC. If you have any suggestions, please contact me. 

Fix Missing XML comment for Publicly Visible Type or Member

While working with swagger documentation in an API, we have to enable the XML file to be generated for documentation from the project setting. For this reason, all the public members in the project solution start giving the warning "CS1591: Missing XML comment for publicly visible type or member" 

we can simply define the XML comment for those members, and the same warning will disappear. But what about those members who are not a part of the swagger documentation? If we ignore them, then there will be lots of warnings in the code, which looks very ugly in the code.

In this article we will discuss how to resolve the "CS1591 missing XML comment for publicly visible type or member" warning by using one of three different solutions.

  • Create an XML Comment for All Public Members 
  • Disable Warning by Decorating Each Public Member
  • Disable all warnings at the project level. (Recommended)



Define XML Comment for All Public Members

The best way is to define the XML comment for all public members, whether it is part of the swagger UI document or not. Because of comments, our method becomes more meaningful, which helps new developers learn about the method by comments instead of going through the code and understanding the logic.




Another advantage of defining the XML comment is that when a developer implements any method in another class, it shows the IntelliSense about the method, which helps the developer to know what the functionality of the method is without navigating to the method defined class.

Suppress Warning by Decorating each Public Member

Even though the first approach has lots of advantages but it requires lots of time and it will increase the size of the project .

The alternate solution to the preceding mentioned problem is  we can suppress each public member by decorating with the following line, which does not require you to provide the XML comment.

#pragma warning disable CS1591


If you don't know the syntax, then simply follow the visual studio suggestion by keeping the mouse on a specific method or member.









Suppress all Warnings at Project Level

The previous two approaches necessitate a significant amount of time spent either defining the XML comment or disabling the warning for each project member.

To save time and minimise the swagger comment related warnings, we can disable these warnings at the project level itself with just one line of configuration. To achieve this, follow the following steps:
 
Right-click on the api project solution & find the properties 


or just use Alt + Enter by putting control of project solution which opens the following window, find the options by following the below image & enter the 1591 in the suppress warnings text box & save it.



Now check any class file. You will not see any warnings related to the swagger XML comment.


Summary

I hope this article helped you to fix Warning CS1591: Missing XML comment for publicly visible type or member.

Display Data From Hosted Web API REST Service in ASP.NET MVC Using HttpClient

Many reader asking me to write on how to get data from remotely hosted web API REST service , So I have decided to write this article to explain step by step how to display data from hosted web API REST Service in ASP.NET MVC using HttpClient. To demonstrate this lets create simple ASP.NET MVC application
If are new and wants to learn web API REST service from creating to hosting to consuming in client application.

In this article, we will use the same hosted Web API REST service  to consume in our created ASP.NET MVC web application. Now, let's start consuming Web API REST service in ASP.NET MVC application step by step.

Step 1 - Create ASP.NET MVC Application.

  1. "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".
  2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name as you wish and click OK.
  3. After clicking, the following Window will appear. Choose empty project template and check on MVC option.

The preceding step creates the simple empty ASP.NET MVC application without Model, View, and Controller, The Solution Explorer of created web application will look like the following.



Step 2 - Install HttpClient library from NuGet


We are going to use HttpClient to consume the Web API REST Service, so we need to install this library from NuGet Package Manager .


What is HttpClient ?


HttpClient is base class which is responsible to send HTTP request and receive HTTP response resources i.e from REST services.


To install HttpClient, right click on Solution Explorer of created application and search for HttpClient, as shown in the following image.



Step 3 - Install WebAPI.Client library from NuGet

This package is used for formatting and content negotiation which provides support for System.Net.Http. To install, right click on Solution Explorer of created application and search for WebAPI.Client, as shown in following image.



Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds depending on your internet speed. We have installed necessary NuGet packages to consume Web API REST services in web application. I hope you have followed the same steps.

Step 4 - Create Model Class 

Now, let us create the Model class named Employee.cs  or as you wish, by right clicking on Models folder with same number of entities which are exposing by our hosted Web API REST service to exchange the data. The code snippet of created Employee.cs class will look like this.

    public class Employee  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
                 
        public string City { get; set; }  
      
    }   

Step 5 - Add Controller Class

Now, let us add ASP.NET MVC controller, as shown in the screenshot given below.



After clicking Add button, it will show in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller . Our hosted Web API REST Service includes these two methods, as given below.

  • GetAllEmployees (GET )
  • GetEmployeeById (POST ) which takes id as input parameter 
The url of the hosted web API REST Service is 

  http://192.168.95.1:5555/api/Employee/GetAllEmployees

In the preceding url
  • http://localhost:56290 Is the base address of web API service, It can be different as per your server.
  • api It is the used to differentiate between Web API controller and MVC controller request .
  • Employee This is the Web API controller name.
  • GetAllEmployees This is the Web API method which returns the all employee list.
After modifying the code of Homecontroller class, the code will look like the following.

Homecontroller.cs
using ConsumingWebAapiRESTinMVC.Models;  
using Newtonsoft.Json;  
using System;  
using System.Collections.Generic;  
using System.Net.Http;  
using System.Net.Http.Headers;  
using System.Threading.Tasks;  
using System.Web.Mvc;  
  
namespace ConsumingWebAapiRESTinMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
        //Hosted web API REST Service base url  
        string Baseurl = "http://192.168.95.1:5555/";      
        public async Task<ActionResult> Index()  
        {  
            List<Employee> EmpInfo = new List<Employee>();  
              
            using (var client = new HttpClient())  
            {  
                //Passing service base url  
                client.BaseAddress = new Uri(Baseurl);  
  
                client.DefaultRequestHeaders.Clear();  
                //Define request data format  
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
                  
                //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
                HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");  
  
                //Checking the response is successful or not which is sent using HttpClient  
                if (Res.IsSuccessStatusCode)  
                {  
                    //Storing the response details recieved from web api   
                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;  
  
                    //Deserializing the response recieved from web api and storing into the Employee list  
                    EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);  
  
                }  
                //returning the employee list to view  
                return View(EmpInfo);  
            }  
        }  
    }  
}  

I hope, you have gone through the same steps and understood about the how to use and call Web API REST service resource using HttpClient.

 

Step 6 - Create strongly typed View

Now, right click on Views folder of the created application and create strongly typed View named by Index by choosing Employee class to display the employee list from hosted web API REST Service, as shown in the following image.



Now, click on "Add" button. It will create View named index after modifying the default code. The code snippet of the Index View looks like the following.


Index.cshtml 
@model IEnumerable<ConsumingWebAapiRESTinMVC.Models.Employee>  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
<div class="form-horizontal">  
  
    <hr />  
    <div class="form-group">  
  
  
        <table class="table table-responsive" style="width:400px">  
            <tr>  
                <th>  
                    @Html.DisplayNameFor(model => model.Name)  
                </th>  
                <th>  
                    @Html.DisplayNameFor(model => model.City)  
                </th>  
                  
            </tr>  
  
            @foreach (var item in Model) {  
                <tr>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.Name)  
                    </td>  
                    <td>  
                        @Html.DisplayFor(modelItem => item.City)  
                    </td>  
                      
                </tr>  
}  
  
        </table>  
    </div>  
</div>  

The preceding View will display all employees list . Now, we have done all the coding.

Step 7 - Run the Application

After running the Application, the employee list from hosted web API REST service will look like this.



I hope, from the above examples, you have learned how to consume Web API REST Service in ASP.NET MVC using HttpClient.


Note

  • This article is just guideline on how to consume Web API REST Service in ASP.NET MVC application using HttpClient .

  • In this article, the optimization is not covered in depth; do it as per your skills.

Summary

I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

How To Publish ASP.NET Web API REST Service In File System

When you want any application available publicly, you need to host it on the server and before hosting, it requires certain processes in terms of making an Application code suitable to the host. Thus, in this article, we will learn how to publish ASP.NET Web API Applications, using File system method. Therefore, let's start step by step, so beginners can also understand.


What is Publishing ?

Publishing is the process to make an Application code suitable to host on the Server by merging multiple class codes into DLLs and by keeping only the required UI code.


The Web Application goes through the steps, mentioned below before hosting to the Server.
Develop an Application -- Publish an Application - Host an Application on IIS.


Now, just demonstrate the preceding concept step by step; i.e, how to publish ASP.NET Web API Applications practically. 

Step 1 : Create ASP.NET Web API application

If you want to publish any Application, first we need to create the Application. If you don't know how to create ASP.NET Web API Application, please refer to my previous article, mentioned below.

Also you can watch video which explains how to create ASP.NET Web API REST service step by step




I hope, you have created ASP.NET Application by reading the preceding article.

Step 2: Publish an Application


Right click on the created ASP.NET Web API project solution, as shown below.



Now, click the previously shown Publish option. It will open the Windows, mentioned below.

Step 3: Select Publish Target

Now, select the option, where you want to save the published file. There are lots of options given by Visual Studio to save the published files, as shown below.


In the preceding image, we have seen that there are many options listed to publish the application, let's learn about them in brief.
  • Microsoft Azure App Service
    This is one of the services provided by Microsoft Azure to publish the different types of the Application such as Web, mobile, REST and other into Azure (Cloud). You need a Microsoft Azure subscription to use this option.
  • Import 
    This option is used to publish the Application, which is based on the predefined configuration files given by your hosting provider , which will directly publish the files in your hosting provider environment.
  • Custom 
    This option is used to publish the Application into your own machine location or FTP Server, as per your most convenient way.
  • Microsoft Azure API apps This option is used to publish REST API's Services in Cloud.
  • Microsoft Azure virtual machineThis option is used to publish the Application in Microsoft Azure virtual machine (Cloud), which requires an Azure subscription . 
There are many other options to publish the Application, using which we can publish .NET Application.

Step 4: Create Custom profile

Now, in this article, we are going to publish an Application in our local machine file system, so we need to choose custom target option. First, we need to create the profile to publish the Application, so it can be a consistent setting to publish the same Application in the future. Choose custom option from preceding explained target option, as shown below.


Now, give the profile name as per your requirement and click OK. It will create the custom profile, as per your given name.

Step 5: Choose Publish Method

Now, configure the created profile, which decides where and how to publish the files. Select the Publish method from the number of methods, which are shown below.


Now, choose the file system method from preceding methods and click Next button.

Step 6: Choose File System location

Now, choose the target location of your local system in which you want to store the published files, as shown below.


In the preceding screenshot, we have selected the target location E drive to store the published files. It may be different in your case, as per you machine and click Next button .

Step 7: Choose Publish code type

Now, choose what type of code you want in production environment by choosing release or debug option, as shown below.


Now, let's learn in brief about debug and release option.
  • DebugChoose this option when you want to debug your Application after the hosting.
  • ReleaseChoose this option when you do not want to debug the Application after hosting and make the Application faster . 

Step 8: Preview the configuration

After the configuration, publish configuration tool will look like, as shown below.


Now, click Publish option and watch the output Window, as shown below.


Now, as shown in the preceding screenshot's highlighted section, our Application code is published in our specified file system location. Now, navigate to the target folder and see the published files, as shown below.


We have seen our published code, which is used to host in IIS. I hope from all the preceding examples, we learned how to publish ASP.NET Web API Service in File system .
Note
  • Choose the publish target location, as per your system.
  • Select proper publish method, as per your requirement.
Summary

I hope, this article is useful for all the readers. If you have any suggestions, please contact me.

My Upcoming Speaking : Building Distributed Architecture using ASP.NET Web API with Azure SQL Database

Speaking at C# Corner Pune Chapter event on Building Distributed Architecture using ASP.NET Web API with Azure SQL Database , If you wants to learn how to build and decide architecture for application  then join my interactive session on Building Distributed Architecture using ASP.NET Web API with Azure SQL Database.

Agenda

 Date : 19-11-2016


Building Distributed Architecture using ASP.NET Web API with Azure SQL Database
  • User Story
  • What is a Distributed Architecture?
  • Tier Vs Layer Architecture
  • WCF REST Vs Web API REST?
  • Designing & understanding Distributed architecture diagram
  • Building REST Service Layer
  • Building Business Logic Layer
  • Building Entity Layer
  • Building Data Access Layer with Dapper ORM
  • Creating Azure SQL database
  • Connecting Data Access Layer with Azure SQL database
  • Building Client Layer with ASP.NET MVC
  • Hosting layers on different machines
  • Consuming Web API REST Services in ASP.NET MVC using HttpClient
  • Consuming Web API REST Services in Windows Phone and Windows Application
  • Q & A


        Where:

        Fujitsu Consulting India
        A-15, IT Tower, M I D C Technology Park, 
        Talwade , Pimpri-Chinchwad - 412114
        Pune Maharashtra INDIA


        Price: Free of cost

        Requirement: Optional to bring your laptop and internet card.

        Date : 19-11-2016
        Time :04:00 PM - 05:30 PM

                                      Register Now

        Don't forget to connect with me

        www.CodeNirvana.in

        Protected by Copyscape
        Copyright © Compilemode