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

Thursday, January 26, 2017

Visual C# Technical Guru - December 2016

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 - December 2016
Happy Coding.

Regards,
Jaliya

Thursday, January 5, 2017

Doing a Self-Contained Deployment (SCD) of a .NET Core Application on Ubuntu

Before moving on I am assuming that you have the basic knowledge on .NET Core and application development targeting .NET Core.

In this post let’s see how we can do a Self-Contained Deployment (SCD) on a Ubuntu machine where there is no .NET Core SDK is installed.

So basically that’s the most important aspect of doing a SCD, we are no longer dependent on a machine wide framework. Framework is bundled with the our application (and third party dependencies if any) and it will get run on top of that. Where as in FDD (Framework-Dependent Deployment), we are deploying only the application (and third party dependencies if any). The application will get run on top of the framework which is installed on the machine.

(Some important thing to note here, in .NET Core Application Deployment documentation under SCD it says, "Creating an SCD does not, however, include the native dependencies of .NET Core itself on various platforms (for example, OpenSSL on macOS) so these need to be installed before running the application.". So there is a list of dependencies for Ubuntu and I have not installed any of those. I was confused about that. Thanks to fellow MVP @WilliamIvanski, I got some explanation from him. His explanation is as follows,

"-dev packages contain headers that allows one to recompile software that depend on these libraries. If you need to only run such software, the package without -dev may be installed. For example, libicu/libicu{somenumber} may be already installed. That's why your application runs fine. You'll need *-dev packages if you want to compile dotnet itself. ". Well that answered my question. When I checked for those packages, they were already installed upon OS installation.)

Here let’s start by creating a Console Application targeting .NET Core. I am using Visual Studio 2015 Update 3.

(You need to note that for this demo, I am using the latest stable versions of tools and frameworks as of today. There is a possibility that some of this will get changed in the future. For instance, I will be using project.json and it will get removed in Visual Studio 2017. But all we really need to do is understanding the concept.)
image
Console Application (.NET Core)
Having said that, I have created the project. This is what my default project.json looks like (this may be different from yours and it is based on the version of .NET Core tools that you have installed).
{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },
 
  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.1"
    }
  },
 
  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }
}
Here I am going to remove imports section and instead of targeting .NET Core 1.0, I am going to target .NET Core 1.1 as it’s the latest.
{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },
 
  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.1.0"
    }
  },
 
  "frameworks": {
    "netcoreapp1.1": {
      
    }
  }
}
Now let’s do the changes which is required to make this application to be deployed as SCD.
{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },
 
  "runtimes": {
    "ubuntu.16.04-x64": {}
  },
 
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.1.0"
    }
  },
 
  "frameworks": {
    "netcoreapp1.1": {
      
    }
  }
}
Here, first thing I did was removing the type=”platform” element. That is what specifies whether this is going to be a SCD or FDD. Here I have also specified the Ubuntu runtime (my Ubuntu installation is 16.04.1) as it’s mandatory when doing a SCD. You can find the list of .NET Core Runtime IDentifiers (RID) here).

Now I have modified program.cs to print "Hello World" to the console. Nothing fancy over there.
public class Program
{
    public static void Main(string[] args)
    {
        System.Console.WriteLine("Hello World");
    }
}
Now let’s move into dotnet CLI, and do the build and release. I am not going to run dotnet restore, as I was using Visual Studio and it was doing the package restoration upon project.json changes for me. If you are on VS Code or other editor run dotnet restore to restore the packages.

To build the application against my targeted runtime, I am running the following command.
dotnet build -r ubuntu.16.04-x64
image
Result: Build
Now to create the release package, I am running the following command.
dotnet publish -c Release -r ubuntu.16.04-x64
image
Result: Release
You can see that a folder named publish has been created under {project}\bin\Release\netcoreapp1.1\ubuntu.16.04-x64.

Now you just need to copy/move the publish folder into a Ubuntu machine. I have done that and here it is.
image
Published folder on Ubuntu
Now open up a terminal. You can see that I have not installed .NET Core over there.
image
dotnet
Now let’s try to run the application.
image
Running the application
Here I am thrown with an error “Failed to initialize CoreCLR, HRESULT: 0x8007001F”. And found out this was caused by a permission issue.

Let’s try giving all the permission to the executable and try back again.
image
Running the application
Everything is working great!

Happy Coding.

Regards,
Jaliya