CQ, using c# for batch files
Modified : June 22 2009

Cq is a utility for running C# from the command prompt.

A user can author C# code directly into a .CQ file and run them just like batch files. The CQ runtime uses the extremely cool runtime compilation functionality of .NET to compile the code into a runnable block, and executes it. Writing and running C# directly with CQ is also a great way to try little chunks of code out without having to resort to building a new sandbox project each time.

Below is an example .CQ file that downloads the Google homepage, or a given URL passed as an argument. It also uses the CQ console, a simple pop-up text window that can be invoked when CQ scripts are running.

// open the cq console form
cqConsole cqC = new cqConsole();
cqC.Show();

// create a new web client
WebClient client = new WebClient();

// if we have an argument passed in, treat it as the
// web URL to download

String webTarget = "http://www.google.com";
if (args.Length >= 3)
{
webTarget = args[2];
}

// put up our user notice that downloading will now begin
cqC.addString("Downloading from : " + webTarget);

// Download the data to a file.
client.DownloadFile(webTarget, "cqweb.htm");

// we are done!
cqC.addString(" ... Done!\n", Color.Green);

The CQ compiler is configurable, so that custom assemblies or libraries can be loaded simply by adding to an XML file. This means you can either disable functionality to make .CQ files restricted in what they can do, or add 3rd party assemblies and have them used transparently. Namespaces and Assemblies can be added thus (to cq-compiler-config.xml):

<cqNamespace value="System.Reflection" />
<cqNamespace value="System.Reflection.Emit" />
<cqAssemblyLoad value="System.Windows.Forms.DLL" />
<cqAssemblyLoad value="System.Data.DLL" />

The compiler uses the CodeDom, Reflection and Microsoft.CSharp libraries, including the CSharpCodeProvider and ICodeCompiler classes to do its work. The runtime code compilation feature is without doubt one of my favorite things about .NET, it offers so much flexibility..!

Note that I havn't secured CQ with proper security permissions, although this wouldn't be too hard - without this, a .CQ file can probably do anything it likes, leaving a massive security hole if some naughty code was put into a file!

Download the installer for CQ, including sample scripts and shell integration here.

Download the source here. Built with .NET 1.1 and VS 2003.