Saturday, September 24, 2016

Building a simple command-line application using .NET Core and Visual Studio Code

I am planning to write a series of blogs posts to introduce application and web developers to the all new .NET Core framework. This article is intended as an introductory lesson on the very basics of .NET Core. Unlike previous version of the .NET framework, .NET Core is open source, cross platform, cross device, small, and fast.

Our first task is to build a simple command-line application with .NET Core version 1.0.0. We will use the light weight Visual Studio Code for our text editor.

1) Create a working folder named “Institution”

2) Change directory into the “Institution” node and type in
dotnet new
This creates a .NET Core “Hello World” project containing two files: Program.cs and project.json.

3) Start Visual Studio Code and open this project folder. There are two others ways, I know of, that can achieve the same result:
a. In the command-line, change directory to the “Institution” folder and type “code .”. This will open up your project folder contents in Visual Studio Code in the current directory (.).
b. Alternatively, navigate to the “Institution” folder using File Explorer (in Windows). Right-click on the folder and select “Open with Code”.
4) Once in Visual Studio Code, you can view the contents of this file. The Program.cs file looks like this:
using System;
namespace ConsoleApplication {
  public class Program {
    public static void Main(string[] args) {
      Console.WriteLine("Hello World!");
    }
  }
}
The project.json file looks like this:
{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}
The project.json file has NuGet dependencies necessary to build our console app. You may also notice the presence of another file named project.lock.json. This file is auto-generated and expands on project.json with more detailed dependencies required by your application. There is no need to commit file project.lock.json to source control.

5) Change the namespace from ConsoleApplication to Institution. Also, change the statement Console.WriteLine("Hello World!"); to
Console.WriteLine("Welcome to our institution!");
6) Save and back in the command prompt, type in:

dotnet restore

This instruction causes dependencies to be brought in from the NuGet repository

7) To execute the application, you can simple run the following command from the command-line:

dotnet run

“dotnet run” calls “dotnet build” to ensure that the app has been built, and then calls “dotnet institution.dll” to run the application. You can find the resulting institution.dll file in the bin\Debug\netcoreapp1.0 directory. Notice that the build process does not produce a institution.exe file. This is because we just created a portable app. Instead of creating a portable app, let us produce a self-contained .exe app.

Note that the name of the .dll file is dictated by the name of the primary project folder, and not by the name of your primary class file (Program.cs).

Compiling a self-contained .exe app

We will need to make some changes to the project.json file.

1) Delete the "type": "platform" element from all dependencies.

2) Next, add a new runtimes node as follows:
"runtimes": {
  "win10-x64": {},
  "osx.10.11-x64": {}
}

This causes the build system to generate native executables for the current environment. In Windows, you will build a Windows executable. On the Mac, you will build the OS X executable.
Save the project.json file, then run the following commands from the command-line:
dotnet restore
dotnet build

The self-contained .exe file can be found at bin\Debug\netcoreapp1.0\win10-x64\Institution.exe.
You can execute the institution.exe file by typing the following on the command line while in the Institution folder:
      bin\Debug\netcoreapp1.0\win10-x64\hello.exe
or simply:
      dotnet run
Let us add a Student class to the project. It is good practice to organize our files in folders. This is especially beneficial when you are dealing with large projects. Therefore, create a folder named Model and add to it a Student.cs class file with the following code:

using System;
using System.Collections.Generic;
namespace Institution.Models {
  public class Student {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Major { get; set; }
    public DateTime DateOfBirth { get; set; }

    public static List<Student> GetSampleStudents()   {
      List<Student> students = new List<Student>() {
        new Student {
          Id = 1,
          FirstName = "Ann",
          LastName = "Lee",
          Major = "Medicine",
          DateOfBirth = Convert.ToDateTime("2004/09/09")
        },
        new Student
        {
          Id = 2,
          FirstName = "Bob",
          LastName = "Doe",
          Major = "Engineering",
          DateOfBirth = Convert.ToDateTime("2005/09/09")
        },
        new Student {
          Id = 3,
          FirstName = "Sue",
          LastName = "Douglas",
          Major = "Pharmacy",
          DateOfBirth = Convert.ToDateTime("2006/01/01")
        },
        new Student {
          Id = 4,
          FirstName = "Tom",
          LastName = "Brown",
          Major = "Business",
          DateOfBirth = Convert.ToDateTime("2000/09/09")
        },
        new Student {
          Id = 5,
          FirstName = "Joe",
          LastName = "Mason",
          Major = "Health",
          DateOfBirth = Convert.ToDateTime("2001/01/01")
        }
      };
      return students;
    }
  }
}



























The above code describes a Student class with properties: Id, FirstName, LastName, Major, and DateOfBirth. It also generates some dummy data that can be accessed through the GetSampleStudents() static method.
Back in Program.cs, replace the Main() method with the following:
public static void Main(string[] args) {
  List<Student> students = Student.GetSampleStudents();
  foreach(var i in students) {
    Console.WriteLine("{0}\t{1}\t{2}", i.Id, i.FirstName, i.LastName);
  }
}
Do not forget to resolve the Student and List classes by using the following namespaces:

using System.Collections.Generic;
using Institution.Models;
If you run the application by executing “dotnet run” from the command-line, you should see the following output:

1 Ann Lee
2 Bob Doe
3 Sue Douglas
4 Tom Brown
5 Joe Mason
In future posts, I am hoping to explore more complicated data driven apps developed using .NET Core. Meantime, I hope you benefited from this article.

No comments:

Post a Comment