Run C# scripts from the .NET CLI.
What do I need to install?
Nothing - everything is self contained from the project.json level. Just make sure you have .NET Core installed and dotnet available in your PATH.
1> Create a project.json file with your dependencies and reference Dotnet.Script as a tool:
{
"dependencies": {
"Automapper": "5.1.1",
"Newtonsoft.Json": "9.0.1"
},
"frameworks": {
"netcoreapp1.0": {
}
},
"tools": {
"Dotnet.Script": {
"version": "0.1.1-beta",
"imports": [
"portable-net45+win8",
"dnxcore50"
]
}
}
}
In the above case we will pull in Automapper and Newtonsoft.Json from nuget into our script.
2> Run dotnet restore
3> Now, create a C# script beside the project.json. You can use any types from the packages you listed in your dependencies. You can also use anything that is part of Microsoft.NETCore.App. Your script will essentially be a netcoreapp1.0 app.
For example:
using Newtonsoft.Json;
using AutoMapper;
Console.WriteLine("hello!");
var test = new { hi = "i'm json!" };
Console.WriteLine(JsonConvert.SerializeObject(test));
Console.WriteLine(typeof(MapperConfiguration));4> You can now execute your script using dotnet script foo.csx.
CSX script could also be located elsewhere and referenced by absolute path - what's important is that the
project.jsonwith its dependencies is located next to the script file, and that restore was run beforehand.
This should produce the following output:
λ dotnet script foo.csx
hello!
{"hi":"i'm json!"}
AutoMapper.MapperConfigurationYou can also reference a script from a script - this is achieved via the #load directive.
Imagine having the following 2 CSX files side by side - bar.csx and foo.csx:
Console.WriteLine("Hello from bar.csx");#load "bar.csx"
Console.WriteLine("Hello from foo.csx");Running dotnet script foo.csx will produce:
Hello from bar.csx
Hello from foo.csxEven better, Dotnet.Script supports loading CSX references over HTTP too. You could now modify the foo.csx accordingly:
#load "https://gist.githubusercontent.com/filipw/9a79bb00e4905dfb1f48757a3ff12314/raw/adbfe5fade49c1b35e871c49491e17e6675dd43c/foo.csx"
#load "bar.csx"
Console.WriteLine("Hello from foo.csx");In this case, the first dependency is loaded as string and parsed from an HTTP source - in this case a gist I set up beforehand.
Running dotnet script foo.csx now, will produce:
Hello from a gist
Hello from bar.csx
Hello from foo.csxYou can pass arguments to the script the following way:
dotnet script foo.csx -a arg1 -a arg2 -a arg3
Then you can access the arguments in the script context using a global ScriptArgs collection:
foreach (var arg in ScriptArgs)
{
Console.WriteLine(arg);
}
