Introduction
Nscript is a tool similar to wscript failed t that it allows scripts to be written in. NET languages ages such as C #, VB. net and JScript. net. nscript automatically compiles the code into an assembly in memory and executes the assembly. the nscript setup application associates nscript ". NCS "(for C # scripts ),". NVB "(for VB. net scripts) and ". NJS "(for JScript. net scripts) file extensions. this enables any code written in these files to be executed directly by double clicking on these files in Windows Explorer. I wrote this tool when I needed to write a script for automating builds. A simple batch file was not sufficient for the task and I preferred to write code in C # as opposed to VBSCRIPT or JScript. this tool came in handy as I cocould modify the scripts easily and execute them by double clicking on the files in Windows Explorer.
Using nscript
- Download and unzip the setup
- Run the setup fileNscript. MSI. You need to have Windows Installer as well as the. NET Framework installed on the machine before running the. MSI file
- The setup automatically associates the file extensions ". NCS", ". NVB" and ". NJS" with nscript.
- Write some code in C # Like
<span class="cs-keyword">using</span> System.Windows.Forms; <span class="cs-keyword">class</span> Test{ <span class="cs-keyword">static</span> <span class="cs-keyword">void</span> Main(<span class="cs-keyword">string</span>[] args) { MessageBox.Show(<span class="cpp-string">"Hello World!"</span>, <span class="cpp-string">"NScript"</span>); }}; |
- Save the file and give it an extension
.ncs
You can execute the code in the file in any of the following ways :-
- Double click on the file in Windows Explorer in that case the script is launched using nscriptw
- At the command prompt type
NScript MessageBox.ncs
- At the command prompt type
NScriptw MessageBox.ncs
- You can execute code written in VB. net or JScript. net too. you need to save VB. net files with the extension ". NVB "and JScript. net files with extension ". NJS"
- To cancel the execution when running in Console mode press Ctrl + C or Ctrl + break. when running under Windows mode (I. e. nscriptw) an animating icon is shown in system tray. double clicking on the icon cancels the execution.
The requirements for the code to be executed by nscript are :-
- The Code shoshould have a class defined.
- The class shoshould have the main method which takes single argument of type array of strings.
- You can refer to any assemblies listed in a file named nscript. NRF if it exists in the same directory as the nscript. EXE. Here is a sample content of nscript. NRF File
System.Web.dllSystem.Web.RegularExpressions.dllSystem.Web.Services.dllSystem.Windows.Forms.DllSystem.XML.dll |
It just has list of Assembly names on each line.
How it works?
The nscript solution has three projects :-
- Nscript-a c # console application
- Nscriptw-a c # Windows Application
- Nscriptlib-a c # class library
Nscript and nscriptw are very much similar to each other; the former can be used to run scripts that can output to console. nscript shows error messages in Console where as nscriptw shows error messages using message boxes. it is nscriptw which is associated with file extensions. since there is lot of code that is shared by the two executables the common code is compiled in nscriptlib and both the executables refer to this class library.
The code behind nscript is pretty simple :-
- Nscript creates an asynchronous delegate that does the compilation and execution asynchronously.
CompileAndExecuteRoutine asyncDelegate = <span class="cs-keyword">new</span> CompileAndExecuteRoutine(<span class="cs-keyword">this</span>.CompileAndExecute); IAsyncResult result = asyncDelegate.BeginInvoke(fileName, newargs, <span class="cs-keyword">this</span>, <span class="cs-keyword">null</span>, <span class="cs-keyword">null</span>); <span class="cs-comment">//For a windows app a message loop and for a </span><span class="cs-comment">// console app a simple wait</span>ExecutionLoop(result); asyncDelegate.EndInvoke(result); |
- The compilation and execution routine creates a separate
AppDomain
Where it does the main compilation and execution. This is done because the user may require to cancel the execution of He script, in that caseAppDomain
Can simply be unloaded.
<span class="cs-comment">//Create an AppDomain to compile and execute the code</span><span class="cs-comment">//This enables us to cancel the execution if needed</span>executionDomain = AppDomain.CreateDomain(<span class="cpp-string">"ExecutionDomain"</span>); IScriptManager manager = (IScriptManager) executionDomain.CreateInstanceFromAndUnwrap( <span class="cs-keyword">typeof</span>(BaseApp).Assembly.Location, <span class="cs-keyword">typeof</span>(ScriptManager).FullName); manager.CompileAndExecuteFile(file, args, <span class="cs-keyword">this</span>); |
IScriptManager
Interface is implemented by the TypeScriptManager
. Since any object has to be passed aled in order for it to be referenced from a separateAppDomain
, We need the interfaceIScriptManager
(As opposed to directly usingScriptManager
Object).ScriptManager
Type extendsMarshalByRefObject
As it is already aled by reference.
public class ScriptManager : MarshalByRefObject, IScriptManager
- The main compilation and execution is carried out by
ScriptManager
Object'sCompileAndExecute
Method. It used codedom to carry out the compilation. It first figures outCodeDomProvider
To use based on the extension of the input script file
<span class="cs-comment">//Currently only csharp scripting is supported</span>CodeDomProvider provider; <span class="cs-keyword">string</span> extension = Path.GetExtension(file); <span class="cs-keyword">switch</span>(extension){<span class="cs-keyword">case</span> <span class="cpp-string">".cs"</span>:<span class="cs-keyword">case</span> <span class="cpp-string">".ncs"</span>: provider = <span class="cs-keyword">new</span> Microsoft.CSharp.CSharpCodeProvider(); <span class="cs-keyword">break</span>;<span class="cs-keyword">case</span> <span class="cpp-string">".vb"</span>:<span class="cs-keyword">case</span> <span class="cpp-string">".nvb"</span>: provider = <span class="cs-keyword">new</span> Microsoft.VisualBasic.VBCodeProvider(); <span class="cs-keyword">break</span>;<span class="cs-keyword">case</span> <span class="cpp-string">".njs"</span>:<span class="cs-keyword">case</span> <span class="cpp-string">".js"</span>: provider = (CodeDomProvider)Activator.CreateInstance( <span class="cpp-string">"Microsoft.JScript"</span>, <span class="cpp-string">"Microsoft.JScript.JScriptCodeProvider"</span>).Unwrap(); <span class="cs-keyword">break</span>;<span class="cs-keyword">default</span>: <span class="cs-keyword">throw</span> <span class="cs-keyword">new</span> UnsupportedLanguageExecption(extension);} |
- Once we have
CodeDomProvider
We can compile the file into a temporary assembly usingICodeCompiler
InterfaceSystem.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler();System.CodeDom.Compiler.CompilerParameters compilerparams = new System.CodeDom.Compiler.CompilerParameters();compilerparams.GenerateInMemory = true;compilerparams.GenerateExecutable = true;System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromFile(compilerparams, file);
- And finally the entry point method of the just compiled assembly is invoked.
results.CompiledAssembly.EntryPoint.Invoke( null, BindingFlags.Static, null, new object[]{args}, null);
Conclusion
This is a very simple tool and I must confess that this is in no way an original idea. don box wrote a similar tool long time back but I cocould not locate it. as a result I decided to write my own. in future I hope to enhance it by allowing to compile and execute XML files similar ". wsh "files. as usual any suggestions are welcome.