Nscript-A Script Host for C #/VB. NET/JScript. net

Source: Internet
Author: User
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
  1. Download and unzip the setup
  2. 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
  3. The setup automatically associates the file extensions ". NCS", ". NVB" and ". NJS" with nscript.
  4. 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>);    }};
  5. Save the file and give it an extension.ncs

    You can execute the code in the file in any of the following ways :-

    1. Double click on the file in Windows Explorer in that case the script is launched using nscriptw
    2. At the command prompt typeNScript MessageBox.ncs
    3. At the command prompt typeNScriptw MessageBox.ncs
    4. 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"
  6. 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 :-

  1. The Code shoshould have a class defined.
  2. The class shoshould have the main method which takes single argument of type array of strings.
  3. 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 :-

  1. Nscript-a c # console application
  2. Nscriptw-a c # Windows Application
  3. 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 :-

  1. 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);
  2. The compilation and execution routine creates a separateAppDomainWhere it does the main compilation and execution. This is done because the user may require to cancel the execution of He script, in that caseAppDomainCan 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>);

    IScriptManagerInterface 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 usingScriptManagerObject).ScriptManagerType extendsMarshalByRefObjectAs it is already aled by reference.

    public class ScriptManager : MarshalByRefObject, IScriptManager
  3. The main compilation and execution is carried out byScriptManagerObject'sCompileAndExecuteMethod. It used codedom to carry out the compilation. It first figures outCodeDomProviderTo 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);}
  4. Once we haveCodeDomProviderWe can compile the file into a temporary assembly usingICodeCompilerInterface
    System.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);
  5. 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.