The dnx run Command

As we have seen in the earlier post, we can use the dnx run command to compile and immediately execute the program. To recap, when you execute the below command in the command prompt, it will execute the program which has an entry point defined in the current folder. 

dnx run

I have created a sample program  which outputs a message to the console.

using System;
using static System.Console;
namespace DnxCoreSample.Commands
{
 public class Program
    {
        public  void Main(string[] args)
        {
            WriteLine("Getting started with dnx commands");
			
        }
    }
}	

So if we try to execute the dnx run command, will get an error as shown below.

That's because we haven't created the configuration file yet, which is used by the DNX environment for managing the dependencies and other project settings. So let's create one with the needed dependencies and run the dnu restore command to download the packages. 

So after downloading, run the program using dnx run in the command prompt and will get the result as shown below.

Let's modify the example which iterates through the list and prints the item in the console.

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

If you run the dnx run command now, will get the following error

So let's add the missing depenedency by modifing the project.json file and also don't forget to run the dnu restore command to download the newly added projects and execute the program again.

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

Suppose if we want to execute a program in some other folder using dnx run command, use -p switch to specify the path to project.json file where the C# code resides


No Comments

Add a Comment