Friday, April 26, 2013

Project-less scripted C# with ScriptCS and Roslyn

Project-less scripted C# with ScriptCS and Roslyn:
ScriptCS inside of SublimeText2 with the ScriptCS package giving SyntaxHighlighting
Glenn Block is working on something interesting that combines C#, NuGet, Roslyn (the new "compiler as a service") and his love of text editors and scripts. Now, with help from Justin Rusbatch (@jrusbatch) and Filip Wojcieszyn (@filip_woj) they are having all kinds of fun...using C# as a scripting language.
Every few years someone tries to turn C# into a competent scripting world, myself included. Often this has included batch files and MacGyver magic, file associations and hacks. Clearly the .NET community wants something like this, but we are collectively still trying to figure out what it should look like. PowerShell aficionados - and I count myself amongst them - might look at such efforts as a threat or a pale reinvention of PowerShell, but the fact remains that C# at the command line, be it as a script or a REPL, is an attractive concept.
Simply put by example, ScriptCS lets me do this:
C:\temp>copy con hello.csx

Console.WriteLine("Pants");

^Z

        1 file(s) copied.



C:\temp>scriptcs hello.csx

Pants
That's Hello World. There's no namespace, no class, just some C# in a .csx file. Roslyn takes care of the compilation and the resulting code and .exe never hits the disk.

Self-hosting Web APIs

So that's interesting, but what about bootstrapping a web server using NancyFX to host a Web API?
Go and clone this repo:
git clone https://github.com/scriptcs/scriptcs-samples.git
Look in the Nancy folder. There's a packages.config. Just like a node.js application has a packages.json file with the dependencies in has, a .NET app usually has a packages.config with the name. In node, you type npm install to restore those packages from the main repository. Here I'll type scriptcs -install...
C:\temp\scriptcs-samples\nancy>scriptcs -install

Installing packages...

Installed: Nancy.Hosting.Self 0.16.1.0

Installed: Nancy.Bootstrappers.Autofac 0.16.1.0

Installed: Autofac 2.6.3.862

Installation successful.
Now, running start.csx fires up an instance of Nancy listening on localhost:1234. There's no IIS, no ASP.NET.
C:\temp\scriptcs-samples\nancy>scriptcs start.csx

Found assembly reference: Autofac.Configuration.dll

Found assembly reference: Autofac.dll

Found assembly reference: Nancy.Bootstrappers.Autofac.dll

Found assembly reference: Nancy.dll

Found assembly reference: Nancy.Hosting.Self.dll

Nancy is running at http://localhost:1234/

Press any key to end
There is also the notion of a "ScriptPack" such that you can Require<T> a library and hide a lot of the bootstrapping and complexity. For example, I could start up WebAPI after installing a Web API package that includes some starter code. Note this is all from the command line. I'm using "copy con file" to get started.
C:\temp\foo>scriptcs -install ScriptCs.WebApi

Installing packages...

Installed: ScriptCs.WebApi

Installation completed successfully.

...snip...

Added ScriptCs.WebApi, Version 0.1.0, .NET 4.5

Packages.config successfully created!



C:\temp\foo>copy con start.csx

public class TestController : ApiController {

  public string Get() {

    return "Hello world!";

  }

}



var webApi = Require<WebApi>();

var server = webApi.CreateServer("http://localhost:8080");

server.OpenAsync().Wait();



Console.WriteLine("Listening...");

Console.ReadKey();

server.CloseAsync().Wait();

^Z

        1 file(s) copied.



C:\temp\foo>scriptcs start.csx

Found assembly reference: Newtonsoft.Json.dll

...snip...

Listening...
Pretty slick. Add in a little Live Reload-style action and we could have a very node-ish experience, all from the command line and from within your text editor of choice, except using C#.
Note that this is all using the same CLR and .NET that you've already got, running at full speed. Only the compilation is handled differently to give this script-like feel.

Installing ScriptCS

The easiest way to install and use ScriptCS is to use Chocolatey (a system-wide NuGet-based application/component installer. "Chocolatey NuGet," get it?) And yes, it's Chocolatey spelled incorrectly with an "-ey."
You can use Chocolatey to do things like "cinst 7zip" or "cinst git" but we'll be using it just to get ScriptCS set up. It's also easily removed if it freaks you out and it installs no services and won't change anything major up save your PATH.
First paste this into a cmd.exe prompt:
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('http://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
This will PowerShell, run http://chocolatey.org/install.ps1 and add Chocolatey to your path.
Then, run
cinst ScriptCS
Which will put ScriptCS in a path like C:\Chocolatey\lib\ScriptCs.0.0.0 while Chocolatey makes it available in your PATH.

Sublime Text or Visual Studio

You can get syntax highlighting for your CSX files inside of Sublime Text 2 with the "ScriptCS" package you can install from package control. If you're using Visual Studio you can get the Roslyn CTP to turn on CSX syntax highlighting.
You can use PackageControl in SublimeText2 and install the ScriptCS package
You can even debug your running ScriptCS projects by opening the ScriptCS.exe as a project. (Did you know you can open an EXE as a project?) Add the .csx script to the command line via Project Properties, drag in the scripts you're working on and debug away.
Debugging requires the Roslyn SDK, although personally, I've been doing just fine with scripts at the command line which requires nothing more than the basic install and a text editor.
It's not clear where ScriptCS is going, but it'll be interesting to see! Go get involved at scriptcs.net. This kind of stuff gets me excited about the prospect of a compiler as a service, and also cements my appreciation of C# as my enabling language of choice. Between C# and JavaScript, you can really get a lot done, pretty much anywhere.
I'll have a video walkthrough on how this works as I explain it to Rob Conery up on TekPub soon! (Here's a referral coupon for 20% off of Tekpub!)
What do you think?


© 2013 Scott Hanselman. All rights reserved.


DIGITAL JUICE

No comments:

Post a Comment

Thank's!