Containerised Asp.Net Core WebApi With Docker On Mac.

Containerised Asp.Net Core WebApi With Docker On Mac.

New .NET Core is the biggest change since the invention of .NET platform. It is fully open-source, components and is supported by Windows, Linux and Mac OSX. In this post I am going to give it a test ride by creating a containerised C# application with the latest .NET CORE.

Docker containers allow teams to build, test, replicate and run software, regardless of where the software is deployed.Docker containers assure teams that software will always act the same no matter where it is – there’s no inconsistency in behavior, which allows for more accurate and reliable testing.

The main advantage to using Docker containers is that they mimic running an application in a virtual machine, minus the hassle and resource neediness of a virtual machine. Available for Windows and Linux systems, Docker containers are lightweight and simple, taking up only a small amount of operating system capacity. They start-up in seconds and require little disk space or memory.

docker installation is available for Mac and windows and can be downloaded from office channel. clickhere

prerequisites:

  1. Install Visual studio for mac
  2. Install Docker for mac

here we will try to build asp.net core webapi and host/run on container with the help of docker.

1. Create New Project: choose asp.net core webapi template from visual studio 2017

D1.png

Now provide project name,solution name and other details like where to save the project.

D2.png

Now our newly created project structure looks as per below

D3.png

Here we have very simple case where service only returns some information about employees as our main objective to host this tiny application on container.

2.Add Docker Support To application

Now add docker file in project  and write instructions that how the docker image build from base image of asp.net core image.

 

Below are the instructions issue to daemon to create docker image.

 

3. Open Terminal on mac :

search for “Terminal” on mac machine and open new window.

D6.png

Once we click on new window option then command window will appear and now all set to issue/write docker command to create docker image.

D7.png

4. Navigate to application folder by issuing change directory command “CD” and make sure we are inside the application folder .We can verify that all items listed by issuing “LS” command that means we are in right place.

D8.png

5. Create Docker Image :

The docker build command builds Docker images from a Dockerfile and a “context”. A build’s context is the set of files located in the specified PATH or URL . The build process can refer to any of the files in the context

Command: Docker build -t .

here our image name is “firstapiwithdocker”,so command should be

docker build -t firstapiwithdocker .

at the moment we can see daemon accept the command start creating the docker image from the docker file instructions.

D9.png

at last we can see  image has been successfully created and tagged with “Latest” keyword.if we don’t provided any tag than daemon tagged the image with “Latest” keyword.

D10.png

5. List all Docker Images:

Now we have to verify that require image has been created or not,so below command have to issue list down all the images.we can see all the important information about images like image name,tag,imageid,created date and size. in below image we can see that out newly created image listed with other base images.

Command :  Docker Images

D11.png

6.Run image with in container:

Till now we have successfully created docker image for our webapi solution and contain all the necessary files and now we have to create container to run this image.

below command will create container.

Syntax: docker run -d -p : –name

example: docker run -d -p 9000:80 –name FirstContainer firstapiwithdocker

once we execute above command,a new container has been created and get random number that means container has been created successfully.

D12.png

Now List down all containers and we can see all the important metadata about containers like containerId,ImageName, Command,Created date,container status,Ports and container name.

here our newly created container is running and exposing 9000 from the host to 80 on the container.

D13.png

Let’s hit the url “http://localhost:9000/api/values” on browser or postman to verify that our application is running on container or not.

Below are the result of the webapi which is running on container instead of local machine.

D14

7. Push docker image on docker hub:

Docker Cloud uses Docker Hub as its native registry for storing both public and private repositories. Once you push your images to Docker Hub, they are available in Docker Cloud.

we need to create docker hub account to push the image on public/private repositories.

D15

 

Docker image should be tagged with well qualified name before issuing the push command. so below command will tagged the image with name “RakeshMahur/FirstApiWithContainer”.

Syntax: docker tag <ImageName> <TagName>

Example:  docker tag firstapiwithdocker rakeshmahur/webapicore-sample

Now login on docker hub from the terminal window by issuing the “docker login” command and provide the docker hub account details (username/password).

D16.png

once docker hub credentials has been validated successfully then a message comes on window and now we will able to push image to docker hub.

D17

Issue docker push command to push docker image to docker hub.

docker push rakeshmahur/webapicore-sample

once we execute above command then we can see our local docker image push to docker cloud repository and listed done over there and every one can pull this image start working on it.

D19.png

Docker Commands

Below are some important and comman used commands , refer to the docker documentation for more details and a more exhaustive list of flags.

  • docker build -t .
    • Builds an image from a given dockerfile. While still useful when handling individual images, ultimately docker-compose will build your project’s images.
  • docker exec -it
    • Runs a command in a running container. More than anything else, I’ve used exec to run a bash session (docker exec -it /bin/bash).
  • docker image ls
    • Lists images on your machine.
  • docker image prune
    • Removes unused images from your machine. Especially when building new images, I’ve found myself constantly wanting a clean slate. Combining prune with other commands helps clear up the clutter.
  • docker inspect
    • Outputs JSON formatted details about a given container. More than anything else I look for IP address via (docker inspect | grep IPAddress)
  • docker pull
    • Downloads a given image from a remote repository. For development purposes, docker compose will abstract this away, but if you want to run an external tool or run project on a new machine you’ll use pull.
  • docker ps
    • Without any flags, this lists all running containers on your machine. I’m constantly tossing on the ‘-a’ flag to see what containers I have across the board. While you are building a new image you inevitably have containers spawned from it exit prematurely due to some runtime error. You’ll need to do ‘docker ps -a’ to look up the container.
  • docker push
    • Once you have an image ready to be distributed/deployed you’ll use push to release it to either docker hub or a private repository.
  • docker rm
    • Removes an unstarted container from your system. Need to run docker stop first if it is running.
  • docker rmi
    • Removes an image. May need to add on the ‘–force’ flag to force removal if it is in use (provided you know what you are doing).
  • docker run
    • Runs a command in a new container. Learning the various flags for the run command will be extremely useful. The flags I’ve been using heavily are as follows:
      • –rm – Removes the container after you end the process
      • -it – Run the container interactively
      • –entrypoint – Override the default command the image specifies
      • -v – Maps a host volume into the container. For development, this allows us to use the image’s full environment and tools, but provide it our source code instead of production build files.
      • -p – Maps a custom port (ie. 8080:80)
      • –name – Gives the container a human readable name which eases troubleshooting
      • –no-cache – Forces docker to reevaluate each step when it runs the container, as opposed to using caching.
  • docker version
    • Outputs both the client vs. server versions of docker being run. This isn’t the same as ‘-v’.
  • docker volume ls
    • While there are variants on volumes, so far I mostly use the ‘ls’ command to list current volumes for troubleshooting. I’m sure there will more to come with using volumes.

 

 

Advertisements

MVC View With Multiple Models Using Tuples And Expendo Object.

DownLoad Sample Project: MvcViewWithMultipleModels 

In mvc programming a view can be associate with multiple models and developers have to send multiple models from controller to cshtml page.There are many  common approaches like ViewBag,ViewData,ViewModel etc can be use to achieve this functionality.

But here i am not going to demonstrate all above three approches.you can use .net framework 4.0 new features to pass the multiple models from controller to view effeciently.

  1. Expendo Object
  2. Tuples

1.) Using Dynamic Model (Expendo Object):

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute(“sampleMember”).

Let say you have two models named as “Department” and “Employee” and you want bind these two models with mvc view.Below are the model definitions:

Department.cs:

c1.PNG

Employee.cs

c2

Controller.cs :

c4

Method details fetch employee and department details as per below:

c5.PNG

View (Index.Html):

On the view you have to use dynamic property of .net framework 4.0 and need to be declared as @model dynamic.this is not strongly type of view.

c6

Rendered output:

c3.PNG

2.) Using Tuples:

In C#, tuples are used to store data. It’s sort of like a variable, but in order for it to be a tuple it must contain more than one value. Each instance of a tuple has a fixed number of items within it (and each item has its own distinct type, eg. a variable or an int), and once the tuple has been created, it can’t be altered in any way.

Let’s continue with previous create models and there are no changes in model class.the only change need to do in controller and view.

Now Controller looks like after code updating for tuples:

HomeController.cs

t4

View (index.html)

you have use tuples at top of the view and you have to declare as per below:

@model Tuples<List<Employee>,List<Department>

complete view looks like:

t2.PNG

Rendered Output:

t1.PNG

You can see there is no change in final rendered output.

This article describes how to pass multiple models from controller to view .I hope this will be helpful for programmers.

MVC5 Dependency Injection With Microsoft Unity.

Download Source Code: DIWithUnityMVC

Dependency injection separates the creation of a client’s dependencies from the client’s behavior, which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles.

Dependency injection allows a program design to follow the dependency inversion principle. The client delegates to external code (the injector) the responsibility of providing its dependencies. The client is not allowed to call the injector code.It is the injecting code that constructs the services and calls the client to inject them. This means the client code does not need to know about the injecting code.

The client does not need to know how to construct the services. The client does not need to know which actual services it is using. The client only needs to know about the intrinsic interfaces of the services because these define how the client may use the services. This separates the responsibilities of use and construction.

What is Unity: Unity is a lightweight, extensible dependency injection container that supports interception, constructor injection, property injection, and method call injection.Unity is a general-purpose container for use in any type of Microsoft .NET Framework-based application. It provides all of the features commonly found in dependency injection mechanisms, including methods to register type mappings and object instances, resolve objects, manage object lifetimes, and inject dependent objects into the parameters of constructors and methods and as the value of properties of objects it resolves.

https://msdn.microsoft.com/en-us/library/dn507457(v=pandp.30).aspx

I’m going to create sample web application for Employee details listing website. There I have Employee as main entities.

Let’s start to build mvc application step by step with snap shots.

1. Create Sample Web Application

let’s start by creating sample MVC web application using Visual Studio 2013.

d1d1-1

2. Install Unity.Mvc5 Library

To install Unity.Mvc5 Library using nuget, we have to right-click on project and click on manage nuget packages.

d2d2.1d2.2.jpg

After successfully completion of nuget packages,check the solution explorer and you can see newly added UnityConfig class inside App_Start folder. That’s where we register all our components with the container.

d3D3.1

3. Update Sample Application

first I’ll add two another Class Library projects called Entities and Services. There Entities project holds all the entity (model) classes we are going to use and Services project will be used to put our service classes.After adding two new projects your solution will look like this.

D4.JPG

Now i added all required model classes(entities) in entities project.

Employee Class (Employee.cs)

namespace Entities
{
   public class Employee
    {
       public int EmployeeId { get; set; }
       public string EmployeeName { get; set; }
       public string HomeTown {get;set;}
       public int DepartmentId { get; set; }
    }
}

 

Next I will add reference to Entities project from Services project and create service classes for Employee . And also I will add relevant interfaces for those classes.

D5.jpg

IEmployeeService Interface:

using Entities;
 
namespace Services
{
   public interface IEmployeeService
    {
      IList GetEmployeeBy();   
    }

EmployeeService Class (EmployeeService.cs):

using Entities;
 
namespace Services
{
   public class EmployeeService:IEmployeeService
    {
        public IList GetEmployeeBy()
        {
            IList empList = new List();
            empList.Add(new Employee() {EmployeeId=1001,EmployeeName="Rakesh Mahur",DepartmentId=111,HomeTown="Meerut" });
            empList.Add(new Employee() { EmployeeId = 1001, EmployeeName = "Siddhart Tandon", DepartmentId = 111, HomeTown = "Lucknow" });
            empList.Add(new Employee() { EmployeeId = 1002, EmployeeName = "Sumit Gupta", DepartmentId = 112, HomeTown = "Haldwani" });
            empList.Add(new Employee() { EmployeeId = 1003, EmployeeName = "Avay Azad", DepartmentId = 113, HomeTown = "Patna" });
            empList.Add(new Employee() { EmployeeId = 1004, EmployeeName = "Sachin Mittal", DepartmentId = 114, HomeTown = "Delhi" });
 
            return empList;
        }
    }
}

 4. Configure Unity:

Let’s register our components with the unity container. There first we have to update our UnityConfig class as below.

using Unity.Mvc5;
using Services;
namespace DIWithUnityMVC
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
			var container = new UnityContainer();
            
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType<itestservice, testservice>();
 
            container.RegisterType<IEmployeeService, EmployeeService>();
            
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }
}

This RegisterComponents method can be called within the Application_Start method in Global.asax. We can update our Global.asax as below.

namespace DIWithUnityMVC
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            UnityConfig.RegisterComponents();
 
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

5. Continue with Sample Application:

Now i am  going to display these employee  information in our web application. I’ll add new Empty Controller called Employee to our MVC application by right clicking Controllers folder.

D5.1.JPG

Normally if we want to use our EmployeeService within the EmployeeController, we need to create instance of EmployeeService inside EmployeeController.

Dependency injection is basically providing the objects that an object needs (here the EmployeeService ) instead of having it construct them itself. I’m going to use constructor injection in this application and let the unity to create new instance of EmployeeService for EmployeeController. There we need to add constructor to our EmployeeControllerwith parameter as below.

using Services;
 
 
namespace DIWithUnityMVC.Controllers
{
    public class EmployeeController : Controller
    {
 
        private readonly IEmployeeService employeeService;
 
        //Constructor Injection to inject the dependency at runtime
        public EmployeeController(IEmployeeService _employeeService)
        {
            employeeService = _employeeService;
        }
 
        //Get : EmployeeDetails
        public ActionResult Index()
        {
            return View(employeeService.GetEmployeeDetails());
        }
	}
}

You can see that i can not create any object of EmployeeService inside the controller.So how employee object available in controller. here DI (Dependency Injection) play vital role and i have use Constructor injection to instantiate the employee class.

Next I will add the view to show the employee details as per below:

D5.2.JPG

Enter a caption

After adding view successfully,your cshtml file will look likes below:

Snippet

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.EmployeeName)
        
        
            @Html.DisplayNameFor(model => model.HomeTown)
        
        
            @Html.DisplayNameFor(model => model.DepartmentId)
        
        
    
 
@foreach (var item in Model) {
    
        
            @Html.DisplayFor(modelItem => item.EmployeeName)
        
        
            @Html.DisplayFor(modelItem => item.HomeTown)
        
        
            @Html.DisplayFor(modelItem => item.DepartmentId)
        
        
            @Html.ActionLink("Edit", "Edit", new { id=item.EmployeeId }) |
            @Html.ActionLink("Details", "Details", new { id=item.EmployeeId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.EmployeeId })
        
    
}
 

It’s done, you can run your application and try /Institution/Index. You should get following output.

D5.3

6. Move Unity Configuration to Separate File

We can move unity configuration to separate file which enable us to do modifications without recompiling existing application. We can do this by adding config section to web.config file as below.

Updated Unity.Config:

 public static class UnityConfig
    {
        public static void RegisterComponents()
        {
			var container = new UnityContainer();
            
            // register all your components with the container here
            // it is NOT necessary to register your controllers
            
            // e.g. container.RegisterType<ITestService, TestService>();
 
            //container.RegisterType<IEmployeeService, EmployeeService>();
 
            container.LoadConfiguration();
            
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }

Modified Web.Config:

 <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <unity configSource="unity.config" />
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-DIWithUnityMVC-20160724093832.mdf;Initial Catalog=aspnet-DIWithUnityMVC-20160724093832;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

New Unity.Config:

Snippet
<?xml version="1.0" encoding="utf-8" ?>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <container>
    <register type="Services.IEmployeeService, Services" mapTo="Services.EmployeeService, Services" />
  </container>
</unity>

Display Templates in Asp.Net MVC -Part 1

Display and editor templates are way to automatically build UI based on a data model. Essentially, it allows us a way to return mark-up required to display the data for the specified model.

This is awesome because we can create templates for commonly used data models, allowing reuse and a clean razor view. The difference between display and editor templates are:

  • Display templates are used for read-only HTML elements.
  • Editor templates are used for editable HTML elements (e.g. input fields).

It was always painful to generate HTML for each property when we have a great feature in the MVC framework (@Html.EditorForModel() and @Html.DisplayForModel() and site.css (Default) where we can modify the user interface).


 

Let’s take Blog landing page as an example:

A common section called “categories” and “Tags” are important part of blog sites and may be these two sections shows many time on different pages.

so my view and it’s html and model classes would typically look something like this.

BlogPost.cs:

public class BlogPosts
    {
        public Categories CatObj;
        public Tags TagObj;
 
        public List<Categories> lstCat;
        public List<Tags> lstTag;
 
        public BlogPosts()
        {
            GetCategories();
            GetTags();
 
        }
 
        public void GetCategories()
        {
            lstCat = new List<Categories>();
            lstCat.Add(new Categories() { catId = 1, catName = "Asp.net" });
            lstCat.Add(new Categories() { catId = 2, catName = "C#" });
        }
 
        public void GetTags()
        { 
         lstTag = new List<Tags>();
         lstTag.Add(new Tags() { tagid = 1, tagName = "C++ Programming" ,Url="http://www.google.com"});
         lstTag.Add(new Tags() { tagid = 2, tagName = "SSIS", Url = "http://www.google.com" });
         lstTag.Add(new Tags() { tagid = 3, tagName = "SSRS", Url = "http://www.google.com" });
         lstTag.Add(new Tags() { tagid = 4, tagName = "SSAS", Url = "http://www.google.com" });
         lstTag.Add(new Tags() { tagid = 5, tagName = "Amazon Services", Url = "http://www.google.com" });
         lstTag.Add(new Tags() { tagid = 6, tagName = "Azure Services", Url = "http://www.google.com" });
        }
        
    }

Categories.cs

public class Categories
    {
        public int catId { get; set; }
        public string catName { get; set; }
    }

Tag.cs

public class Tags
   {
       public int tagid { get; set; }
       public string tagName { get; set; }
       public string Url { get; set; }
   }

HomeConroller.cs

public class HomeController : Controller
   {
       // GET: Home
       public ActionResult Index()
       {
           BlogPosts bp = new BlogPosts();
           return View("Index", bp);
 
       }
    }

cshtml:

@model MVCTemplate.Models.BlogPosts
 
<aside>
    @* Author:Rakesh Mahur *@
    @* This is traditional way to bind model with html by using foreach loop *@
   <h1>Common way to bind model with html</h1>
     <h2>Categories</h2>
    <ol>
        @foreach (var CatItem in Model.lstCat)
        {
            <li>
                <a href="#">@CatItem.catName</a>
            </li>
        }
    </ol>
        <h2>Tags</h2>
        <ol>
            @foreach (var tagItem in Model.lstTag)
            {
                <li>
                    <a href="@tagItem.Url">@tagItem.tagName</a>
                </li>
            }
        </ol>
     </aside>

 

 

output:

 Url: http://localhost:<port>/home/index

d1.jpg

Output is exactly same as the the desired but there are few things need to be noted that here  foreach loop is used to fetch all items from the collection and bind with html tags.So page performance directly depends on number of items in collection.

it seems ugly with lot of codes with foreach. so it’s better our views remain very simple and clean. With display templates we can make it cleaner.

How Come ?

To make code cleaner we can pass a model or a list of models into html.displayfor() and the framework will take of the rest.

before creating the display templates,folder structure is very import part of it.if you are going to create templates which will use any where in whole application as as reusable component then a folder structure looks like below and all display templates should be created under this folder.

Views->Shared->DisplayTemplates

d2.jpg

let’s create display templates for tag and categories.

Categories.cshtml

@model MVCTemplate.Models.Categories
 
        <li>
            <a href="#">@Model.catName</a>
        </li>

Tags.cshtml

@model MVCTemplate.Models.Tags
    <li>
        <a href=@Model.Url>@Model.tagName</a>
    </li>

Now add new cshtml page  with name “ViewWithTemplate” under view/home folder:

ViewWithTemplate.cshtml

@model MVCTemplate.Models.BlogPosts
 
<h1>Categories</h1>
<ol>
    
    @Html.DisplayFor(x=>x.lstCat)
</ol>
 
<h1>Tags</h1>
<ol>
    @Html.DisplayFor(x=>x.lstTag)
</ol>

Now Add new action method in homecontroller and now modified code look like this:

public class HomeController : Controller
{
    // GET: Home
    // Call this method to see view output with foreach loops
    public ActionResult Index()
    {
        BlogPosts bb = new BlogPosts();
        return View("Index", bb);
 
    }
// Call this method to see view output with Display templates.
    public ActionResult ViewWithTemplates()
       {
           BlogPosts bb = new BlogPosts();
           List<Categories> objcat = bb.lstCat;
           return View("ViewWithTemplate", bb);
 
       }

 

Output of modified code for Display templates:

 Url: http://localhost:<port>/home/ViewWithTemplates

d1

if you noticed and compare both outputs with display templates and with foreach loops as shown below,no differences found in both output but there are lot of differences at cshtml level and you can see cstmal with display templates are more manage and cleaner to traditional way.

d3.jpg

 

Another Example of Display Templates:

assume you have to show color thumbnail along with other details in tabular format as per below and you may download complete project:

colorTemplates

Sample Project for Color Thumbnail: DisplayNameForTemplate

Summary

Display templates are  a useful HTML helper built into the MVC framwork. Using them to replace foreach loops allow sus to write clean,readable code that can easily be used across the application.

Start removing your loops today !