DNX - Using Commands option

In DNX environment we are using dnx run command to run the program from the command line. I have already authored a post on this and you refer that from here

In this post I am going to cover the custom command option avaliable in .NET core using which we can do named execution of our program. We can define commands in the project.json file in your project folder and is recognized by editors like Visual Studio and Visual Studio Code. The commands defined in the project folder is available in that project only. If you want you can have commands defined at a global level, then it is available for everthing that runs under a user profile. 

Sample program 

using System;
using static System.Console;
using System.Collections.Generic;
namespace DnxCoreSample.Commands
{
    public class Program
    {
        public void Main(string[] args)
        {
            var items = new List<string>() { "Red", "Blue", "White", "Green" };
            foreach (var item in items)
            {
                WriteLine($"Color : {item}");
            }
        }

        
    }
}

Let's see how can we configure that in project.json file

{
  "frameworks": {
    "dnx451": { },
    "dnxcore50": {
      "dependencies": {
        "System.Console": "4.0.0-beta-23516",
        "System.Collections": "4.0.11-beta-23516"
      }
    }
  },
  "commands": {
    "RunSample" : "dnxcommands"

  }
}

A command contains two parts, the name for the commands is given on the left side and right contains the arguments needs to be passed to the command. In our configuration RunSample is the name of the command and we are passing the name of the folder which is "dnxcommands" to the command. When you pass the name of the folder, make sure that proper casing is maintained, because if there is mismatch in the casing it will return an error.

Now we can use the command dnx RunSample instead of dnx run to execute our program from the command line.

You can also give the name of the folder along with dnx command to execute your program too

Note: In this post I am making use of the two new features from C# 6.0, String interpolation and using static. You can refer the links given below to read about it further

String Interpolation in C# 6.0

Using static statement in C# 6.0


No Comments

Add a Comment