Friday, May 19, 2017

Running and Exploring a Docker Linux Container

Sometimes the best way to troubleshoot and understand how a Docker Container works, is by exploring the Container. While I believe there are couple of ways to explore, one of the ways I really found useful is docker exec. Basically docker exec let’s you run commands inside a Container, and for a Linux Container we can use docker exec to bash in and run shell commands.

But to bash in of course, you need to have the Container in running state. Here in this post, I have explained how you can setup your own Container, specifically a Linux Container with ASP.NET Core MVC Application running inside.

So let’s proceed.

Currently I have no Containers running.
image
docker ps -a
And I have following set of Images.
image
docker images
Here the dockerwebapp is the Image that I am planning of creating and running a Container from. I can run the Container by issuing  docker run.
# Runs in the foreground
# Even if pressed Ctrl+C, Container is still running
PS C:\WINDOWS\system32> docker run dockerwebapp
 
# Runs in the background/detached
PS C:\WINDOWS\system32> docker run -d dockerwebapp
 
# Runs in the foreground
# If pressed Ctrl+C, Container will stop running
# Container will be displayed in docker ps -a
PS C:\WINDOWS\system32> docker run -it dockerwebapp
 
# Runs in the foreground
# If pressed Ctrl+C, Container will stop running and will get deleted
PS C:\WINDOWS\system32> docker run -it –-rm dockerwebapp
In this case, I am going to run docker run –d dockerwebapp as I want the Container to be running in the background, so for next docker commands, I don’t want to open up another PowerShell window.
image
docker run -d dockerwebapp
Now I can see that my container is running, it’s time to explore the image.
PS C:\WINDOWS\system32> docker exec -i -t blissful_roentgen /bin/bash
 
# -i -t can be use together like follows
PS C:\WINDOWS\system32> docker exec -it blissful_roentgen /bin/bash
image
docker exec
You can see that I am now in a Linux shell and I can use shell commands to explore the image. For instance to see the file system.
image
ls
Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, May 18, 2017

Running ASP.NET Core MVC Application inside a Docker Linux Container from Windows

I have been having some quality time with Docker recently and wanted to get an ASP.NET Core application running in a Docker Linux Container which will run inside my Windows machine. Was having some hard time getting it to work initially, but with some great help and guidance from a fellow MVP, Alex Thissen (@alexthissen), managed to get it up and running.

Here in this post, I assume you have some basic knowledge on Docker, Docker Images/Containers. And for some of the commands, I might not be explaining what each arguments of the command does, hoping you will do --help on those.

So let’s start.

So on my machine, I have Docker for Windows installed, and there under settings, I have my local C:\ drive shared with Containers.
image
Shared Drives
Now let’s create a folder (I am creating on my Desktop, make sure the drive you are creating the folder in, is shared like above) and I am naming it as a DockerWebApp.

Open up a PowerShell window and change the directory to DockerWebApp folder.
PS C:\Users\Jaliya\Desktop\DockerWebApp> dotnet new mvc
PS C:\Users\Jaliya\Desktop\DockerWebApp> dotnet restore
PS C:\Users\Jaliya\Desktop\DockerWebApp> code .
Now the project will get opened in Visual Studio Code. I have Docker extension for VS Code installed. If you haven’t installed, I suggest you do so, so we can create Docker related files pretty easily. So using the extension, I am creating a Dockerfile as follows.
Dockerfile
Docker for VS Code - Adding Dockerfile
So my Dockerfile looks like this.
FROM microsoft/aspnetcore:1.0.1
LABEL Name=dockerwebapp Version=0.0.1
ARG source=.
WORKDIR /app
EXPOSE 30000
COPY $source .
ENTRYPOINT dotnet dockerwebapp.dll
For now, I am not going to do any changes here, but I am going to delete the other Docker files which got created inside the project which are docker-compose.debug.yml and docker-compose.yml to make things not confusing.

Now let’s publish our application.
PS C:\Users\Jaliya\Desktop\DockerWebApp> dotnet publish -c Release
And since I haven’t specify any specific output path, application will get published to bin\Release\netcoreapp1.1\publish folder.
image
Publish folder
Now let’s move to back to our Dockerfile and do following changes.
FROM microsoft/aspnetcore:1.0.1
LABEL Name=dockerwebapp Version=0.0.1
ARG source
WORKDIR /app
EXPOSE 30000
COPY ${source:-bin/Release/netcoreapp1.1/publish} .
ENTRYPOINT dotnet DockerWebApp.dll
Here first what I have done is, I don’t want to copy the whole project folder to my Image, I am just copying the publish folder. Then I have renamed the dll name in the ENTRYPOINT as in the file name in the publish folder (well I have spent quite sometime figuring out an issue because of this name mismatch).

Now let’s build the Docker Image, so I can create a Container out of it.

For that I am running the following command.
PS C:\Users\Jaliya\Desktop\DockerWebApp> docker build -t dockerwebapp .
I am seeing the following output.
image
docker build -t dockerwebapp .
All seem to be good, there is a warning at the end, we can basically ignore that for now for the sake of this demo. Now let’s run the following command to confirm whether our image is created.
PS C:\Users\Jaliya\Desktop\DockerWebApp> docker images
SNAGHTML82e020a
docker images
Yes, it is created, now let’s try to run it.
PS C:\Users\Jaliya\Desktop\DockerWebApp> docker run dockerwebapp
Now I am getting an error “The specified framework 'Microsoft.NETCore.App', version '1.1.2' was not found.”.
image
docker run dockerwebapp
Of course, I have been using an older aspnetcore image, I am changing the Dockerfile as follows.
FROM microsoft/aspnetcore:1.1.2
LABEL Name=dockerwebapp Version=0.0.1
ARG source
WORKDIR /app
EXPOSE 30000
COPY ${source:-bin/Release/netcoreapp1.1/publish} .
ENTRYPOINT dotnet DockerWebApp.dll
Here is the link where you can find the list ASP.NET Core Docker image information.
https://hub.docker.com/r/microsoft/aspnetcore/

Now let’s run a docker build again.
PS C:\Users\Jaliya\Desktop\DockerWebApp> docker build -t dockerwebapp .
image
docker build -t dockerwebapp .
Now let’s run the image again.
image
docker run dockerwebapp
Yes, it seem to be working. Let’s run the following command in a new PowerShell Window to see the status of all the running Containers.
PS C:\Users\Jaliya> docker ps
Here note that I am running the command from another directory. You can run docker ps from sitting inside any directory.
image
docker ps -a
Now from let’s try to access to site http://localhost:30000 from a browser.
image
Site can't be reached
That’s because I haven’t mapped Container ports and host machines ports. I can easily to fix it by running docker run specifying port mappings.
PS C:\Users\Jaliya\Desktop\DockerWebApp> docker run -p 30000:80 dockerwebapp
image
docker run -p 30000:80 dockerwebapp
And now if I check for running Containers, I can see the ports are mapped.
image
docker ps
Now let’s browse to http://localhost:30000 back again. And this time, it works!
image
Site is running
In this post, I have used following commands in the background.
# List running containers
docker ps
 
# List all containers
docker ps -a
 
# List all images
docker images
 
# Stop given container
docker stop {container_name}
 
# Delete given container
docker rm {container_name}
 
# Delete given image
docker rmi {image_id}
 
# Delete all containers
docker rm $(docker ps -a -q)
 
# Delete all images
docker rmi $(docker images -q)
Hope you find this post helpful.

Again huge thanks goes out to Alex Thissen (@alexthissen) for all his help.

More reads,
Running and Exploring a Docker Linux Container

Happy Coding.

Regards,
Jaliya

Wednesday, May 17, 2017

Visual C# Technical Guru - April 2017

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
https://blogs.technet.microsoft.com/wikininjas/2017/05/16/april-2017-technet-guru-winners/
image
Visual C# Technical Guru - April 2017
Happy Coding.

Regards,
Jaliya

Tuesday, May 9, 2017

Windows Subsystem for Linux

With Windows 10 Creators Update one of the features that got released publicly is Windows Subsystem for Linux (WSL). But it was available for Windows 10 Insiders for almost like a year now and was initially announced at Build 2016. WSL basically let’s you run Linux on Windows. If you are thinking about a VM, No, it’s not a Virtual Machine.

Configuring WSL on Windows shouldn’t take more than 10 minutes, by following these steps you can configure WSL pretty easily. Once you have configured WSL, you should be able use Bash on Ubuntu, just by opening up the Command Prompt/PowerShell and running bash command.
image
WSL
Or you can Search for Bash in Windows, and there should be a desktop app named Bash on Ubuntu on Windows.
image
Bash On Ubuntu On Windows
Currently under WSL only Ubuntu is supported, may be in the future Microsoft might support different flavors of Linux.

On WSL, one of the things that fascinates me more is the File System that is already mounted for you.
image
File System
And through the bash I can just run mkdir and the folder will be appearing inside Windows Explorer the same time.

And most importantly I can run .NET Core Apps on WSL. I have installed .NET Core on my WSL, (again it’s pretty easy, just follow the relevant steps described here) and created an ASP.NET Core HelloWorld application.
image
.NET Core on WSL
And I can just browse the site from a Web Browser in my Windows OS. Isn’t that just great?

Happy Coding.

Regards,
Jaliya

Friday, April 21, 2017

Visual C# Technical Guru - March 2017

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - March 2017
Happy Coding.

Regards,
Jaliya

Thursday, April 20, 2017

Proper Use of ArgumentException and ArgumentNullException

I am sure most of you are already aware of this, but thought of clarifying the things, if someone is looking for it.

Basically ArgumentException is deriving from SystemException where as ArgumentNullException is deriving from ArgumentException. So while ArgumentException is more generic, ArgumentNullException is more specific.

Let's consider the following scenario. I have an Employee class and it has three properties.
public class Employee
{
    public string FirstName { get; }
    public string LastName { get; }
    public string JobRole { getset; }
 
    public Employee(string firstName, string lastName)
    {
        FirstName = firstName ?? throw new ArgumentNullException(nameof(firstName));
        LastName = lastName ?? throw new ArgumentNullException(nameof(lastName));
    }
}
Employee should have FirstName, LastName, but JobRole is optional when you are creating an employee.

In here as you can see, in the constructor we must be using ArgumentNullException instead of ArgumentException, because we are checking argument itself is null.

Consider the below method. It’s accepting an employee and let’s say we are going to do something with the employee’s JobRole, and to do that employee's JobRole should have set first.
public void SomeMethod(Employee employee)
{
    if (employee == nullthrow new ArgumentNullException(nameof(employee));
    if (employee.JobRole == nullthrow new ArgumentException($"{nameof(employee)}.{nameof(JobRole)} cannot be null");
    // TODO: Implementation
}
So here, first  we have checked whether the employee is null, if yes, we are throwing an ArgumentNullException. Then we need to check whether the employee’s JobRole is set or not. So if the JobRole of employee is null, we are throwing ArgumentException, but not an ArgumentNullException. The reason is even though the property is null, it has made the employee argument itself to invalid.

Well, hope you understood the difference. Even though these are simple things, these things matters when it comes to writing quality code.

Happy Coding.

Regards,
Jaliya

Thursday, March 30, 2017

Why I love Visual Studio Code

I just love Visual Studio Code and believe most of you must be feeling the same. On my code editor preferences, VS Code only seconds to Visual Studio.

In this post, thought of sharing some little tiny things that altogether makes VS Code a great editor. Let’s just start by creating a folder.

Quick Open

First I can just right click on the folder and open with VS Code. (I know it’s an old feature, but it’s super useful.)
SNAGHTML1ed23e5
Open with Code
This is one of my most favorite features. Once the VS Code is opened, I can open up a Integrated Terminal. That’s either by Menu Bar -> View -> Integrated Terminal or just by Ctrl+`.
image
Integrated Terminal
In Windows environment, you can use either PowerShell or cmd. (On the above image, I have customized the Integrated Terminal to use cmd, but PowerShell is the default. Will show you how easy it is to customize the VS Code to match your preference later in the post.)
image
Integrated Terminal
If you are worried about the command I typed here, I just created a React-Redux project using dotnet. Basically you can type any command which you do on cmd.

image
IntelliSense
You have fully IntelliSense support for most of the languages, here I am writing TypeScript code.

Keyboard Shortcuts

If you are so much addicted to the keyboard and hate using the mouse, there are plenty of shortcuts to do most of VS Code tasks without leaving the keyboard. Not to forget, all the keyboard shortcuts can be customized.

Here is a list of keyboard shortcuts available in VS Code.
Key Bindings for Visual Studio Code

But in default VS Code you might find some keyboard shortcuts are different when compared to Visual Studio. But don’t worry, there is an extension called Visual Studio Keymap to port all your Visual Studio shortcuts to VS Code.

There are hundreds of extensions available providing variety of features, here is a list of some extensions that I have installed.
image
Installed Extensions
VS Code lets you customize variety of options to suit your preference.
image
Customize
If you open up the Settings, you will see something like this.
image
Settings
Here on the left side you can see all the different settings that you can change. On the right side, it will either display User Settings or Workspace Settings. While User Settings are maintained in “C:\Users\{UserName}\AppData\Roaming\Code\User\settings.json”, Workspace Settings are maintained in “{CurrentExplorerFolder}\.vscode\settings.json”. Whatever the settings declared in those files will get applied in following order. Default Settings will get overridden by User Settings, and both Default and User Settings will get overridden by Workspace Settings.

Here is how I have customized my VS Code. The highlighted properties are for customizing the Integrated Terminal which I mentioned earlier in the post.
image
Customized Settings
Same way we can customize the keyboard shortcuts. User specific shortcuts will get stored in “C:\Users\{UserName}\AppData\Roaming\Code\User\keybindings.json”.

Well, these are some of the features that I love. If I started to write them all, I won’t be able to stop.

Happy Coding.

Regards,
Jaliya

Tuesday, March 28, 2017

Wrote a TNWiki Article Spotlight at Official Blog of TechNet Wiki

Wrote a post in Wiki Ninjas - Official Blog of TechNet Wiki. The title of the post is TNWiki Article Spotlight – Secure your .NET Core web applications using IdentityServer4.
image
TNWiki Article Spotlight – Secure your .NET Core web applications using IdentityServer4

Read the rest on,
TNWiki Article Spotlight – Secure your .NET Core web applications using IdentityServer4.

Happy Coding.

Regards,
Jaliya

Saturday, March 25, 2017

Visual C# Technical Guru - February 2017

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - February 2017
Happy Coding.

Regards,
Jaliya

Saturday, February 25, 2017

Visual C# Technical Guru - January 2017

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - January 2017
Happy Coding.

Regards,
Jaliya

Wednesday, February 15, 2017

Creating a MVC ASP.NET Core Application Powered by React

Recently I have started to explore React and this morning, I saw this blog post Building Single Page Applications on ASP.NET Core with JavaScriptServices published on .NET Web Development and Tools Blog. And when I started to read this post, I got quite surprised and amazed.

Basically the summary is with the latest version of .NET Core SDK, you can use following templates to create a project using dotnet new.
image
dotnet new --list
While there are a lot of information about all of this in above mentioned post, in this post, I am going to explore the React project template. (Not React with Redux, at least not on this post). Of course, to start exploring , first you need to create it.

I have the latest .NET Core SDK and Node installed.
image
dotnet  and Node version
And I have installed Single Page Application (SPA) templates as per the original blog post.
Now let’s start some React time.
image
dotnet new react
Once the project is created, let’s see what dotnet exactly has created for us.
image
Project Structure
You can see that basically the structure is more or less the same to web application projects created using Visual Studio.

In addition you have webpack, babel and TypeScript configuration files (if you haven’t worked with webpack, and babel before, may be you can read this previous post of mine: Getting Started with React, Babel and Webpack). And of course there is a Dockerfile as well.

Your familiar files which bootstraps ASP.NET Core and MVC (Program.cs, Startup.cs, Controllers and Views folders etc.) are there. React components are placed inside ClientApp folder.

While all the client side dependencies are listed in package.json, server side dependencies are listed in the .csproj it self (you can find more information about the project.json to .csproj migration in this previous post of mine: Where is project.json in Default .NET Core Application Templates in Visual Studio 2017). On the server side dependencies, one of the important thing to note is, reference to “Microsoft.AspNetCore.SpaServices”.

image
Server Side Dependencies
If you open up Startup.cs, inside Configure method which configures the HTTP request pipeline, while the environment is Development, we are using the Webpack Dev Server along with it’s HMR (Hot Module Replacement) feature.
image
Use of Webpack Dev Server
This is made all possible by using “Microsoft.AspNetCore.SpaServices” package.  And that is a very handy thing when it comes to development, you don’t have to refresh the page after making client side code changes.

So now let’s run the application and see what happens. Open up a command prompt inside the project folder and run the following commands to restore/install server side and client side packages.
dotnet restore
npm install
Finally it’s the command of joy.
dotnet run
image
dotnet run
Let’s navigate to http://localhost:5000 from the browser.
image
MVC ASP.NET Core with React
Isn’t it marvelous!

Happy Coding.

Regards,
Jaliya

Wednesday, February 1, 2017

Getting Started with React, Babel and Webpack

React is getting popular everyday and I believe you can find many articles to know what React is. In this post let’s see how we can setup a HelloWorld React application using some set of nice tools.

To build this sample, I am going to use following set of tools and libraries.
This is the editor that I am going to use, and of course, you can use any editor you prefer. But I suggest you try out Visual Studio Code as it offers great features for JavaScript developers. All these features are made possible by the new JavaScript Language Service (Code name : “Salsa”)  which is also getting shipped with Visual Studio 2017.
I am going to use npm as the JavaScript package manager.
Babel is the transpiler here. We can use all the great features in ECMAScript 6, also known as ECMAScript 2015 (ES6/ES2015) and Babel will make sure they will get transpiled to ES5 which will work on all browser versions.
Webpack is the module bundler that I am using, it will be responsible for effectively bundling the files based on the configuration I provide.
I will be using webpack-dev-server to test and host my application. It provides nice features such as hot reloading. We just need to modify the code and changes will get reflected. We don’t need to refresh the browser.

Now it’s time to write some code. I will start by installing the global dependencies that I need. I am going to install webpack-dev-server as a global npm package.
npm install webpack-dev-server -g
Now I am creating a folder for the application “HelloWorldReact” and inside there creating another folder named “app” and that’s where I am going to have all my code files.

From the “HelloWorldReact” folder, I am opening up a command prompt and running the npm init command to create the package.json file. On the prompts, I am just keeping the default values as it is.

Now let’s install the packages using npm.

dependencies
npm install react react-dom --save
devDependencies
npm install webpack babel-core babel-loader file-loader react-hot-loader babel-preset-es2015 babel-preset-react --save-dev
As you already know upon the installation, package.json will get updated. I am further modifying the package.json as follows adding a script.
{
  "name": "helloworldreact",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "start-webpack-server": "webpack-dev-server --hot --inline --colors --progress"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2"
  },
  "devDependencies": {
    "babel-core": "^6.22.1",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.22.0",
    "babel-preset-react": "^6.22.0",
    "file-loader": "^0.9.0",
    "react-hot-loader": "^1.3.1",
    "webpack": "^1.14.0"
  }
}
Here, the packages listed under dependencies are only needed when running the application in production. The packages listed under both dependencies and devDependencies are need when developing the application. Under devDependencies, I have installed,
  • Core Babel package
  • Babel loader for Webpack
  • Two presets to make sure ES6/ES2015 and react transpilation
  • File loader for Webpack
  • Webpack & react-hot-loader to enable webpack dev servers hot loading for React (webpack-dev-server should be running with --hot flag).
The script is for running webpack-dev-server with some set of flags. To know about what these flags are visit webpack-dev-server CLI.

Now let’s create a js file to configure webpack. I am naming it as webpack.config.js.

webpack.config.js
var path = require('path');
var webpack = require('webpack');
 
module.exports = {
  context: path.join(__dirname, 'app'),
  entry: {
    javascript: './app.js',
    html: './index.html'
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  devServer: {
    inline: true,
    port: 9999
  },
  module: {
    loaders: [
      {
        test: /.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      },
      {
        test: /\.html$/,
        loader: "file?name=[name].[ext]",
      }
    ]
  }
};
Here I have specified the entry files, bundle output directory, devServer information and loaders. And for js files, I have set the loader as Babel. So what happens in the js loader here is when you come across a path that resolves to a '.js' inside of a require()/import statement, use the babel-loader to transform it before you add it to the bundle. For more information about webpack loaders, go to https://webpack.github.io/docs/loaders.html.

Now let’s create the entry files. Navigate to the “app” folder, and let’s create a app.js and index.html files.

app.js
import React from 'react';
import ReactDOM from 'react-dom';
 
class App extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello World</h1>
      </div>
    )
  }
}
 
ReactDOM.render(<App />, document.getElementById('main'))
index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Hello World</title>
</head>
<body>
  <div id="main">
  </div>
 
  <script src="/bundle.js"></script>
</body>

</html>
Now I am almost good. From the command prompt run the following command.
npm run start-webpack-server 
Now you should be able to see that bundling is happening and webpack dev server is starting. Once completed, navigate to http://localhost:9999 and if all is good you should see something like below.

image
Output
Now try changing the text inside our React component and just save the file, you should be able to see the changes in the browser without refreshing the browser.

Still the bundled files are not outputted to the destination (HelloWorldReact/dist). When you are ready for the deployment, from the command prompt, you can run webpack -d command to output files.

I have made the code available on GitHub. Feel free to fork.
https://github.com/jaliyaudagedara/Blog-Post-Samples/tree/master/HelloWorldReact

Happy Coding.

Regards,
Jaliya