.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

Debug, Tools

Debugging Rust on Windows using Visual Studio Code

Rust is the next super cool language I have seen after C# . Flame war… 😀 just kidding. But seriously the whole idea of Rust has just blown my mind and I just wanted to learn it.

But coming from C# + Visual Studio background. I am so spoil on using these massive super cool tool and excellent debugging experience. So selecting any language I also tend to see what tools are available.

Rust community is still not  as big as .Net, mainly because its so new language. So I did not find ONE great tool which will serve purpose. But I am sure things will change. There are things coming up, you can read more here

Ok so back to the original purpose of this post. Rust with Visual Studio Code.

The tools we will use :

  1. Visual Studio code here
  2. Rust Nightly (1.13) GNU 64bit here (Why we need this I’ll explain it a bit later )
  3. Rust Source here (I have used 7 zip to extract)
  4. GDB for Windows here
  5. Python here

Visual studio extensions:

  1. Rusty Code here
  2. Native Debug here

 

Now the steps to install or get things working.

  1. Install Rust Nightly 1.13
  2. Create a folder C:/rust/utils
  3. Open command prompt and CD to C:/rust/utils.
  4. Type cargo install racer
  5. Type cargo install rustfmt
  6. Type cargo install rustsym
  7. Put C:/rust/utils/bin in your environment variable PATH
  8. Install GDB for example in location C:/rust/debug
  9. Put this path C:/rust/debug/gdb64/bin in your environment variable PATH.
  10. Install Python
  11. Extract rust src for example in location c:/rust/src
  12. Create an environment variable RUST_SRC_PATH and assign value C:/rust/src/src to it. Its pointing to the actual source folder.
  13. Install Visual Studio Code
  14. Open Visual Studio Code. Press Ctrl + Shift + X which will open extensions pane. Type Rusty Code (install + restart). Then same way install Native Debug extension as well.

Thats all to setup the environment.

Now lets do some debugging.

  1. Code I will use is straight from Rust website.
    fn main() {
    // A simple integer calculator:
    // `+` or `-` means add or subtract by 1
    // `*` or `/` means multiply or divide by 2
    
    let program = "+ + * - /";
    let mut accumulator = 0;
    
    for token in program.chars() {
    match token {
    '+' => accumulator += 1,
    '-' => accumulator -= 1,
    '*' => accumulator *= 2,
    '/' => accumulator /= 2,
    _ => { /* ignore everything else */ }
    }
    }
    
    println!("The program \"{}\" calculates the value {}",
    program, accumulator);
    }
    
  2. Lets use folder c:/rust/learning
  3. One thing Rusty Code does not support at the time of writing this blog is creating a new rust project so you have to do it manually by using cargo.
  4. Open command prompt and CD to C:/rust/learning.
  5. Type cargo new vscodetest –bin
  6. Open the new created folder C:/rust/learning/vscodetest from Visual Studio Code
  7. Press Ctrl + Shift  + P
  8. Type Cargo and select Cargo: Build Debug
  9. Press Ctrl + Shift + D
  10. Press the start button beside the Configurations drop down. Like thisdebug_config
  11. Select GDB
  12. It will create launch.json. Change it to look like this
       {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Debug",
                "type": "gdb",
                "request": "launch",
                "target": "target/debug/vscodetest",
                "cwd": "${workspaceRoot}"
            }
        ]
    }
  13. Now put a line break at line number 6
  14. Press F5. The breakpoint should hit. Like this debugging_without_pretty.png
  15. If you see in the above screenshot. I am trying to inspect the value of variable program but it seems to show some extra info. We can get rid of it with a small python script.
  16. Go to C:/rust/debug/gdb64/bin and open file gdbinit in VS code. And add this at the end of the file
    python
    print "---- Loading Rust pretty-printers ----"
    
    sys.path.insert(0, "C:/rust/src/src/etc")
    import gdb_rust_pretty_printing
    gdb_rust_pretty_printing.register_printers(gdb)
    
    end 
  17. Save it and go back to VS Code and again press F5. You should see cleaner inspect output like this debugging_with_pretty

That’s all. Not a very easy process but still good enough to start learning rust.

Now why I choose the nightly build mainly because with the version at the time of the post was 1.11 which had a small problem in debugging rust macros. To read about it more you can check my question in Rust user group here

Please let me know if this does not work or you find some problem so that I can help you if I could and also update the blog post. Also I have read various blog post and stack overflow post to get understanding about all this so thanks to all of them, its difficult to post all the link here as most of them I forgot 🙂

.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, Software Architecture

Prototype Pattern using C#

Introduction

According to Wikipedia:

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.

According to Gang Of Four:

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

UML:

600px-Prototype_UML.svg

When to use it?

  1. To avoid the inherent cost of creating a new object in the standard way (e.g., using the ‘new’ keyword) when it is prohibitively expensive for a given application.
  2. Hide concrete classes from the client.
  3. Add and remove new classes (via prototypes) at runtime.
  4. Keep the number of classes in the system to a minimum.
  5. Adapt to changing structures of data at runtime.

The main players in the pattern are:

IPrototype
Defines the interface that says prototypes must be cloneable

Prototype
A class with cloning capabilities

PrototypeManager
Maintains a list of clone types and their keys

Client
Adds prototypes to the list and requests clones

Example in C#

PrototypeBase.cs

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace DesignPatterns.PrototypePattern {
[Serializable]
public abstract class PrototypeBase<T> {

// Shallow clone
public T Clone() {
return (T)this.MemberwiseClone();
}

//Deep Clone
public T DeepClone() {
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
T copy = (T)formatter.Deserialize(stream);
stream.Close();
return copy;
}
}
}

Prototype.cs

using System;

namespace DesignPatterns.PrototypePattern {
[Serializable]
public class Prototype : PrototypeBase<Prototype> {
// Content members
public string Country { get; set; }
public string Capital { get; set; }
public DeeperData Language { get; set; }

public Prototype(string country, string capital, string language) {
Country = country;
Capital = capital;
Language = new DeeperData(language);
}

public override string ToString() {
return Country + "\t\t" + Capital + "\t\t->" + Language;
}
}
}

DeeperData.cs

using System;

namespace DesignPatterns.PrototypePattern {
[Serializable]
public class DeeperData {
public string Data { get; set; }
public DeeperData(string s) {
Data = s;
}
public override string ToString() {
return Data;
}
}
}

PrototypeManager.cs

using System.Collections.Generic;

namespace DesignPatterns.PrototypePattern {
public class PrototypeManager {
public Dictionary<string, Prototype> prototypes
= new Dictionary<string, Prototype> {
{"Germany",
new Prototype("Germany", "Berlin", "German")},
{"Italy",
new Prototype("Italy", "Rome", "Italian")},
{"Australia",
new Prototype("Australia", "Canberra", "English")}
};
}
}

PrototypeClient.cs

using System;

namespace DesignPatterns.PrototypePattern {
public class PrototypeClient : IDesignPattern {

private void Report(string s, Prototype a, Prototype b) {
Console.WriteLine("\n" + s);
Console.WriteLine("Prototype " + a + "\nClone      " + b);
}

public void Run() {
Console.WriteLine("\n------------------Prototype Pattern------------------");
PrototypeManager manager = new PrototypeManager();
Prototype c2, c3;

// Make a copy of Australia's data
c2 = manager.prototypes["Australia"].Clone();
Report("Shallow cloning Australia\n===============",
manager.prototypes["Australia"], c2);

// Change the capital of Australia to Sydney
c2.Capital = "Sydney";
Report("Altered Clone's shallow state, prototype unaffected",
manager.prototypes["Australia"], c2);

// Change the language of Australia (deep data)
c2.Language.Data = "Chinese";
Report("Altering Clone deep state: prototype affected *****",
manager.prototypes["Australia"], c2);

// Make a copy of Germany's data
c3 = manager.prototypes["Germany"].DeepClone();
Report("Deep cloning Germany\n============",
manager.prototypes["Germany"], c3);

// Change the capital of Germany
c3.Capital = "Munich";
Report("Altering Clone shallow state, prototype unaffected",
manager.prototypes["Germany"], c3);

// Change the language of Germany (deep data)
c3.Language.Data = "Turkish";
Report("Altering Clone deep state, prototype unaffected",
manager.prototypes["Germany"], c3);
}
}
}

Output:

Shallow cloning Australia
===============
Prototype Australia             Canberra                ->English
Clone      Australia            Canberra                ->English

Altered Clone’s shallow state, prototype unaffected
Prototype Australia             Canberra                ->English
Clone      Australia            Sydney          ->English

Altering Clone deep state: prototype affected *****
Prototype Australia             Canberra                ->Chinese
Clone      Australia            Sydney          ->Chinese

Deep cloning Germany
============
Prototype Germany               Berlin          ->German
Clone      Germany              Berlin          ->German

Altering Clone shallow state, prototype unaffected
Prototype Germany               Berlin          ->German
Clone      Germany              Munich          ->German

Altering Clone deep state, prototype unaffected
Prototype Germany               Berlin          ->German
Clone      Germany              Munich          ->Turkish

So whats happening here?

Firstly we are using two ways to clone the object

  1. Shallow Clone: In .Net we have a method called MemberwiseClone, its a method that is available on all objects. It copies the values of all fields and any references, and returns a reference to this copy. However, it does not copy what the references in the object point to.Many objects are simple, without references to other objects, and therefore shallow copies are adequate.To preserve the complete value of the object, including all its subobjects use a deep copy.
  2. Deep Clone: An alternative is a deep copy, meaning that fields are dereferenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B. The result is different from the result a shallow copy gives in that the objects referenced by the copy B are distinct from those referenced by A, and independent. Deep copies are more expensive, due to needing to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph. In the .NET Framework they are encapsulated in a process called serialization, which can be defined by using attribute [Serializable] on the class to be serialized. Objects are copied to a given destination and can be brought back again at will. The options for serialization destinations are several, including disks and the Internet, but the easiest one for serializing smallish objects is memory itself. Thus a deep copy consists of serializing and deserializing in one method.

Then we are also using a PrototypeManager, which I mentioned earlier that its used to maintains a list of clone types and their keys so that we can retrieve an already cloned object quickly.

The main program consists of a series of experiments demonstrating the effects of cloning and deep copying.

In the first group, Australia is shallow copied. After changing of Australia’s clone, the capital is Canberra in the prototype and Sydney in the clone. The statement responsible is   c2.Capital = “Sydney”;

however, changing the language to Chinese (  c2.Language.Data = “Chinese”;) also changes the prototype’s language to Chinese. That is not what we wanted. We got the error because we did a shallow copy and the language in the prototype and in the clone reference the same DeeperData object.

In the next experiment, we clone Germany using a deep copy ( c3 = manager.prototypes[“Germany”].DeepClone();).

Now changing the capital ( c3.Capital = “Munich”;) does not affect the prototype but the deep clone is affected. Similarily  altering the deep state-its language to Turkish ( c3.Language.Data = “Turkish”;), shows the prototype after the changes; it is unaffected.

That’s all about Prototype Pattern.

Code can be found at GitHub

Reference:

 

HyperV

XDE Exit Code: HypervisorNotRunning when running Visual studio android emulator

Tonight i got stuck with this small issue for which I spent about 2 hours to figure out the fix.

Problem:

When I try to start VS 2015 Emulator for Android it failed to start with the following error

 

“XDE Exit Code: HypervisorNotRunning”

Make sure that your system supports virtualization and you have Virtualization technology “ON” in your BIOS

Start cmd.exe with Admin rights and type

 

“bcdedit /set hypervisorlaunchtype auto”

 

Restart the system and now try starting the emulator and it should start.

 

Hope it helps!! 🙂