.Net, Azure, Cloud technology, Docker, HyperV

What is Docker and how to run an ASP.Net Core Web app on Docker (Bonus: Debugging also)

What is Docker and why is it so popular ?

Docker is a container platform which helps in deploying applications as clean and self sufficient containers that eliminates “works on my machine” problems when running of different machines. It helps creating lean containers which Enterprise customers use in delivery software’s faster and more securely to different platforms both Linux and Windows.

But what is a container?

Its a package in which all the dependencies required to run a software is packed, mind you its different from VM because it does not bundle a full operating system, but only the libraries and settings required to make the software work.

Lets see that with an example image from Docker website

containers-vs-vm
Image taken from here

So from the above example we can see that VM contains a full OS for an app whereas container contains only the App and its dependencies and running on top of the Docker engine. Which makes it very lean and very quick to spin off.

Terminologies

  • Container Image : Its a package with all the dependencies like framework, and the settings needed for the deployment and execution which is needed by the container runtime.
  • Container : An instance of an application which is created based on a container image. When you are scaling an application then you add more container by making an instance of the same image.
  • Tag : As the name suggest, its a tag or a name you give to the container image to identify itself.
  • Dockerfile : A text file giving instructions on how to build a container image.
  • Build : Its not usual what we programmers understand when said build meaning compiling the source code, here build means creating a container image with the files provided by following the instructions given in the Dockerfile. You do this with command docker build .
  • Docker Engine : The system which lets you create and run container on top of it.
  • Repository : Its a pool of related Container images. Same container image may have different variants, some with libraries only some with full SDK’s . Also different variants for different OS (linux or windows).
  • Registry : A place which hosts repositories which in turn has different container images. The most common one is Docker Hub . Companies can have their private registry also.
  • Docker Trusted Registry (DTR) : Its a registry service which can be installed on premises so that it remains private to the organization. It can be also attached to the Continuous Integration system. Its connect to the LDAP and AD of the organization. More to read here .
  • Cluster : A collection of Docker hosts. You can create this cluster using tools like Docker swarm , DC/OS, Kubernetes.
  • Orchestrator : A tool to manage Docker cluster and host. It provides command line and graphical interface. It helps in managing the containers and its networks, configurations and also load balancing so that load is distributed to different nodes. Same tool are used for this purpose (Docker swarm, DC/OS, Kubernetes)

Why Docker is so popular?

docker-interest
Google Trends

Docker has been becoming very popular for simple reasons,

  • Its the simplest way to test your application in different operating systems
  • If it works in a container then you can be sure it works in other system also, or it should work.
  • Its faster to spin off a container which make its excellent choice to scale a service.
  • Its very light weight which make it very efficient in terms of resource consumption.
  • More important if you are willing to manage by yourself , then there is a community edition which is free.

Ok now lets get started.

For this post I will work on Windows 10.

Prerequisites

  • Install Docker for windows from here
  • Install Visual Studio 2017 with .Net Core support (at the time of this post I was using .Net core 1.1)
  • Make sure you have Hyper V enabled. Docker needs that.

Lets see some commands to work with Docker

  • docker version docketversion'
  • docker images : this should list all the docker images you have it in your system. Initially it will be empty or one dummy image.
  • docker pull imageid:version : this will pull the docker image with which we work on. Lets use ubuntu 17.10 for this example. So the command  will be
    • docker pull ubuntu:17.10
  • docker run -it id : Check the below image dockerrunBasically, I first check for the images, then I use command docker run -it c6 , where -it means interactive that means I want the command prompt to get started for ubuntu else it will run and exit immediately, then c6 is the minimum characters from the IMAGE ID which makes it unique to other image ids. So this is now running ubuntu and you can try ‘cat /etc/*release‘ to check the version of ubuntu. To exit you can just type exit.

Lets build the Asp.Net core app.

  • Launch Visual Studio 2017 and create a Asp.Net Core web application and select Web App and un-check the option Enable Docker support. Also I have named the project as DockerExample.
  • Change the code of the Home controller a bit so that it looks like this controllerchange.PNG
  • Run the app on IIS server, you should see the following output when you click the About page.aboutpagewindows
  • Now lets publish this app to a folder which we can then publish it to Docker. But before that lets create a Dockerfile which will tell how to build the container image. To do that right click on the project and add a text file without file extension .txt, it should be just with name Dockerfile. Add the content of the Dockerfile like below dockerfile
  • In the file the 1st line means that take the container image microsoft/aspnetcore:1.1 , it contains the runtime to run , 3rd line says that copy all the  files from the current directory to the host directory, 4th line tell the entry point and which command to use to execute in our case its dotnet command.
  • One more important thing, is to set the properties of the Dockerfile to be Copy to output directory always. Right click on the Dockerfile from the visual studio and set the property Copy to Output Directory to be Copy always. So that when we publish, then Dockerfile also gets copied.
  • Now lets publish the app, to do that click on publish
  • On the publish window select the Folder option and browse to a folder location, in my case I have used the following location C:\Users\sherry.ummen\Desktop\DockerExample  and click publishpublishfolder.PNG
  • Now lets go to the command prompt and build the docker image. To do that first lets change the directory to be C:\Users\sherry.ummen\Desktop\DockerExample and type the following command. docker build -t sherry/dockerexample:1.0 .  . Where option -t is for tag.dockerbuild
  • If all is well at your end , then lets run the web app. Type the following command docker run -d -p 8000:80 sherry/dockerexample:1.0  where option -d is to run in background and -p is for port. dockerrunwebapp
  • Lets launch the app , open your favorite browser and navigate to 127.0.0.1:8000 and navigate to About page, you should see this aboutpagelinux
  • As you can see that app is running on linux container.
  • You can stop the service by typing the following commands dockerwebappstop

Now the Bonus part. Debugging Asp.Net Core web app running on docker.

  • First lets add the Docker support to our project, for that first you would have to delete the Dockerfile from the project, because a new one will be added automatically when we add docker support.
  • Now right click on the project and select Add -> Docker Support
  • Your solution should look like this
    dockersupport.PNG
  • You will notice that Docker file already created for us.
  • Now go to Home controller and add a break point at the beginning of About
  • Now click on the run button rundocker
  • Visual studio will do all the publish and launching the app for you, and if everything has gone well then you should hit the break point, when you navigate to About page. breakpoint

That’s all! . As you can see Asp.Net Core and Docker works so well and with Visual studio you get its great power of debugging. Can’t wait to explore more.

Thanks

.Net, Design Patterns

Abstract Factory Pattern in C#

Introduction

According to Wikipedia:

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.

According to Gang Of Four:

Provide an interface for creating families of related or dependent objects without
specifying their concrete classes.

Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime.

UML:

677px-Abstract_factory_UML.svg

When to use it?

  • When the system is independent on how the objects are created.
  • When the system should work with multiple families of product.
  • When an interface is required to create similar family products, not the implementation.

Why to use it?

  • Provides an interface for creating objects which are related or dependent objects without specifying concrete classes
  • Calling code works with abstract interface and classes and does not need to know the exact types of the objects created by the factory

The main players in the pattern are:

  • AbstractFactory – declares a interface for operations that create abstract products.
  • ConcreteFactory – implements operations to create concrete products.
  • AbstractProduct – declares an interface for a type of product objects.
  • Product – defines a product to be created by the corresponding ConcreteFactory; it implements the AbstractProduct interface.
  • Client – uses the interfaces declared by the AbstractFactory and AbstractProduct classes.

Example in C#

ComputerFactory.cs (Abstract Factory)


namespace DesignPatterns.AbstractPattern {
abstract class ComputerFactory {
public abstract Computer GetComputer();

}//ComputerFactory
}

ConcreteComputerFactory.cs (ConcreteFactory)


namespace DesignPatterns.AbstractPattern {
class ConcreteComputerFactory : ComputerFactory {

public override Computer GetComputer() {

return new ConcreteComputer();

}//GetComputer

}//ConcreteComputerFactory
}

Computer.cs (Abstract Product)


namespace DesignPatterns.AbstractPattern {
abstract class Computer {

public abstract int Mhz { get; }

}//Computer
}

ConcreteComputer.cs (Product)


namespace DesignPatterns.AbstractPattern {
class ConcreteComputer : Computer {

int _mhz = 500;

public override int Mhz{
get { return _mhz; }
}//Mhz

}//ConcreteComputer
}

Client Code


using System;

namespace DesignPatterns.AbstractPattern {
class AbstractFactoryPatternClient : IDesignPattern {
public void Run() {
Console.WriteLine("\n------------------Abstract Factory Pattern------------------");
ComputerFactory factory = new ConcreteComputerFactory();

new ComputerAssembler().AssembleComputer(factory);
}
}
}

ComputerAssembler.cs


using System;

namespace DesignPatterns.AbstractPattern {
class ComputerAssembler {
public void AssembleComputer(ComputerFactory factory) {

Computer computer = factory.GetComputer();
Console.WriteLine("Assembled a {0} running at {1} MHz",
computer.GetType().FullName, computer.Mhz);

}//AssembleComputer
}
}

Output:

Assembled a DesignPatterns.AbstractPattern.ConcreteComputer running at 500 MHz

So whats happening here?

If you see the client code its passing an Abstract factory to the ComputerAssembler class and this class has a public method AssembleComputer which takes the Abstract factory class and calls the exposed public method of that factory.

So good thing here is that the AssembleComputer does not care about any specific object but it can support any type of ComputerFatcory which in this example its the ConcreteComputerFacory which implements ComputerFactory; and then it calls the GetComputerMethod which returns a concrete computer which implements Computer abstract class, which again decouples it from any concrete class.

Basically idea is to decouple the implementation logic to any specific concrete class, in this way every concrete class will have an common interface to implement and the client can call any method of the Product without worrying the exact object type.

Code can be found at GitHub

Reference:

 

 

.Net, Design Patterns

Design Patterns using C#

My notes on various design patterns from the book of Gang of Four (Design Patterns – Elements of Reusable Object Oriented Software). Sharing so that others also could benefit from this.

Creational Patterns

  • Prototype Pattern: The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. Read the article
  • Abstract Factory Pattern: This pattern is used when creating families of related or dependent objects without specifying their concrete classes by using a common interface. Read the article
.Net

Sharing the code between multiple exceptions

Today I had a situation where I wanted to do same opertation in case of different exceptions. I came up with something simple

Here is the situation:

try{
  // Exception throwing code
}catch(MongoConnectionException ex){
  // Some code here
}catch(IOException ex){
  // Some code here
}catch(SocketException ex){
  // Some code here
}

Now this looks already quite ugly. Not for you? Ok then its ugly for me 🙂

So what I did some may consider it even more ugly but I can atleast share the code

I did it so that

try{
  // Exception throwing code
}catch(Exception ex){
  if(ex is MongoConnectionException || ex is IOException || ex is SocketConnection){
    // Do some specific logic or setting of state for these type of exceptions
}
  // Do some common logic here
}

If you find some problem in doing this please let me know so that I can fix my code as well 🙂 But this reduced my code.

Thanks

.Net

C# + REPL + Scripting -> Life is Good

cshell_logo

Alright this time I have again made my life a bit easy by finding a solution for problem where I want to test a library but I do not want to create .Net Solution using VS and then type class and all those. Since I want to just test the working of an API so I do not want to go soo long. Someone will say then use IronRuby and do it; but then we do not get Syntax Highlighting, Code completion, intellisense and etc. (productivity enhancing tools).

So I get this nice tool called CSHELL; its a REPL for C# script (isn’t that cool).

So let me show you how I have experimented this tool by solving one of my simple issue.

Problem Description:

          As you all know we in Platform team working on DB renewal stuff and we often need to check various different Databases and their functionality. This time I wanted to check Couchbase’s functionality on How to get the list of buckets in a default pool. Terminologies may be confusing for some who does not understand about Couchbase but in simple term Bucket is a collection of JSON documents.

Steps:

1) Run cshell -> Download it from here. It is just an .exe so you can just run it. (Tips: Better to pin it up with the Taskbar for easy access);

2) You will see this main window.

CShell Main Window

3) Now I want to have the reference to Couchbase .Net SDK.

CShell Referencing DLL

4) Select the required ones

CShell Referencing DLL

5) Now I have written the statement in the script to check the problem which I described earlier. So here is the snapshot of it:

CShell Intellisense

You see I get the intellisense. isn’t that nice? And if you see a bit above that I was using a class without the reference (that too two time (tongue)) and it gives me a colourful error . That’s neat.

CShell Linq Intellisense

Intellisense with LINQ as well. Nice!!

And finally I get the result which I want.

CShell Final Result

That’s it. It took me just 5 mins to do this. Time creating this blog post is not counted 

More info you can find in http://cshell.net/.

Please share if you find something useful as well or something which does not work. Its a good way to use C# as a scripting language. 

Thanks

Cloud technology

First ever Windows Azure Conference in India

WinAzure2

This post is all about my experience at India’s first ever Windows Azure conference. This event was on March 20th and 21st 2014 at Bangalore. This event was to showcase the power of mighty Windows Azure to Developers, IT Professionals, Business Decision Maker, and Service Providers.

Microsoft India has been excellent in conducting this event.

From the day I have heard about Windows Azure I have been soo fascinated with this technology, but I confess that I know only bits of it; this subject is huge by huge I mean really huge. It has soo many features and details hidden to it. BTW this small website of mine is also powered by Windows Azure.

Microsoft like to call Windows Azure as the Cloud OS. Well it is.

So my journey to this conference starts with the registration which I came accross on twitter, I did no long to get registered even I forgot to take permission about this to my boss. I was like I will attend this no matter what happens.

But I was lucky to have got the permission from my boss Jan Mattson to go for this event, even though I had a Sprint planning meeting on the same day.

wac_start

The event was divided into basically two main parts Develop and Deploy + Manage; I went for Develop module.
The event started with the key note by Mr. Bhaskar Pramanik, Chairman of Microsoft India. It was very very interesting to hear him. He showed soo very cool statisctics of Windows Azure. Here is the image of it:

azure_stats

Some interesting fact which mentioned were:
1. Over 1000 new customers sign up for Azure everyday.
2. 55% of the Fortune 500 use WIndows Azure.
3. Azure Revenue Growing 200% +

Wow that sounds very cool and promising.

Then there was the expected key not by the new CEO of Microsoft Mr. Satya Nadela.

satya_speech

He has been talking mostly about the future of Cloud and Mobile. So Microsoft is a cloud first company.

But after that comes the CIO of Fortis Hospital who speaks about their partnership with Azure. Yes Fortis uses Azure. Nice real case example of a big organization using Azure.

Then the events get started with Azure Website. They have shown some basic ways how website can be deployed to Azure quickly. Some of the ways they have been showing were:
1. FTP
2. Thru Visual Studio
3. Thru GIT
4. Thru DropBox
5. Thru TFS

In my coming posts I will try to cover these and show some examples on how to do it.

Now the next event was all about Mobile Services provided by Azure. This event was actually in my personal opinion was not planned very well. It had lots of glitches in between. But it was about the services like
1. Push notifications
2. Publishing app with diff platform support etc

To be frank I did not understand much with this event I would rather  read the documentation and learn by myself.

Next event was about Windows Azure Media services.

azure_media_services
They talked about the Live streaming of SOCHI Olympics which was hosted by Windows Azure.

They also talked about various media formats supported by Azure and how the streaming can be smooth by Smooth streaming technology.

Next we had lunch time; ok the food was good (it was free) but then they made us stand under hot sun which was still ok since its free hahaha..

Now the next event was about SQL Azure; well what to say I am not an SQL guy so this was a kind of bad choice of me sitting for this event. But what I liked in that event was how to take the backup of the database using SQL Server Management Studio. But the event was very theoritical and less hand on but still it was good nothing to share about lets move on.

This was the last event Windows Azure Websites Deep Dive.. aah very nice and informative event. They showed some cool stuffs like
1. Kudu Console
2. Remote debugging of Azure website
3. Visual Studio Online
4. Web Jobs
5. Zapier.com (very cool website)

Overall very very informative I liked this session the most.

Above topics are huge and lots of details in themselves. I will talk about these as seperate posts soon 🙂

That’s the end of the first day. Soo much I have learnt from it. Saw so many bright minds on this event got inspired by them to great extent. Very happy to be part of this event

Second day I could not join since taking two days leave from office work was not feasible.

What I get from this? Lots of knowledge which you will see in the coming posts of mine and this very cool Windows Azure Pendrive

azure_pendrive