PDA

View Full Version : Archived: TrueScript - scripts in .Net


Trueborn
01-19-2009, 05:48 AM
TrueScript is a pair of programs and a library for immediate execution or on-the-fly compilation of local or remote scripts written in a .Net language. All immediate execution scripts are sandboxed at the same level as your local computer's "internet untrusted zone."

/* PROJECT: TrueScript
* AUTHOR: J. V. Smith (Trueborn)
* CONTRIBUTOR(S): J. V. Smith (Trueborn)
* CREATED: 13 Oct 2008
* MODIFIED: 13 Oct 2008
* TITLE: TrueCode
* DESCRIPTION: This code provides the compile-and-execute
* functionality required for TrueScript scripts to run.
* It also includes error handling procedures.
* COMMENTS:
* LICENSE:
* This software is distributed under the following license:
*
* Microsoft Reciprocal License (Ms-RL)
* This license governs use of the accompanying software. If you use the
* software, you accept this license. If you do not accept the license, do
* not use the software.
*
* 1. Definitions
* The terms "reproduce," "reproduction," "derivative works," and
* "distribution" have the same meaning here as under U.S. copyright
* law.
* A "contribution" is the original software, or any additions or
* changes to the software.
* A "contributor" is any person that distributes its contribution
* under this license.
* "Licensed patents" are a contributor's patent claims that read
* directly on its contribution.
* 2. Grant of Rights
* (A) Copyright Grant- Subject to the terms of this license, including
* the license conditions and limitations in section 3, each
* contributor grants you a non-exclusive, worldwide, royalty-free
* copyright license to reproduce its contribution, prepare derivative
* works of its contribution, and distribute its contribution or any
* derivative works that you create.
* (B) Patent Grant- Subject to the terms of this license, including
* the license conditions and limitations in section 3, each
* contributor grants you a non-exclusive, worldwide, royalty-free
* license under its licensed patents to make, have made, use, sell,
* offer for sale, import, and/or otherwise dispose of its contribution
* in the software or derivative works of the contribution in the
* software.
* 3. Conditions and Limitations
* (A) Reciprocal Grants- For any file you distribute that contains
* code from the software (in source code or binary format), you must
* provide recipients the source code to that file along with a copy of
* this license, which license will govern that file. You may license
* other files that are entirely your own work and do not contain code
* from the software under any terms you choose.
* (B) No Trademark License- This license does not grant you rights to
* use any contributors' name, logo, or trademarks.
* (C) If you bring a patent claim against any contributor over patents
* that you claim are infringed by the software, your patent license
* from such contributor to the software ends automatically.
* (D) If you distribute any portion of the software, you must retain
* all copyright, patent, trademark, and attribution notices that are
* present in the software.
* (E) If you distribute any portion of the software in source code
* form, you may do so only under this license by including a complete
* copy of this license with your distribution. If you distribute any
* portion of the software in compiled or object code form, you may
* only do so under a license that complies with this license.
* (F) The software is licensed "as-is." You bear the risk of using it.
* The contributors give no express warranties, guarantees, or
* conditions. You may have additional consumer rights under your local
* laws which this license cannot change. To the extent permitted under
* your local laws, the contributors exclude the implied warranties of
* merchantability, fitness for a particular purpose and
* non-infringement.
*
* To view an original copy of this license:
* http://www.microsoft.com/opensource/licenses.mspx#Ms-RL
*
*/



using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security;
using System.Security.Policy;
using System.Xml;
using System.Xml.Serialization;

namespace truecode
{
[Serializable(), XmlRoot(ElementName = "Script")]
public class Ctscript
{
[XmlElement(ElementName = "include", IsNullable = true)]
public string Includes = string.Empty;
[XmlElement(ElementName = "references", IsNullable = true)]
public string References = string.Empty;
[XmlElement(ElementName = "code", IsNullable = true)]
public CDATA Code = new CDATA(string.Empty);
[XmlAttribute()]
public string Language = "CSharp";
[XmlAttribute()]
public string StartupObject = string.Empty;
[XmlAttribute()]
public string OutputAssembly = string.Empty;
[XmlAttribute()]
public string Type = "exe";

private List<string> m_Errors = new List<string>();
private string m_szRoot = string.Empty;

public static Ctscript Load(string szFilename, ref string szLoadError)
{
Ctscript oScript = new Ctscript();
XmlSerializer oXml = new XmlSerializer(typeof(Ctscript));
try
{
oScript = (Ctscript)oXml.Deserialize(new XmlTextReader(szFilename));
return oScript;
}
catch (FileNotFoundException)
{
szLoadError = "File not found: " + szFilename;
return null;
}
catch (DirectoryNotFoundException)
{
szLoadError = "Directory not found: " + szFilename.Substring(0, szFilename.LastIndexOf("\\"));
return null;
}
catch (System.Net.WebException wex)
{
szLoadError = "Remote script file not found or an error occurred while retrieving the script." + Environment.NewLine + "Server returned: " + wex.Message;
return null;
}
catch (InvalidOperationException oex)
{
szLoadError = oex.Message;
return null;
}
catch (UriFormatException)
{
szLoadError = "Invalid URI: " + szFilename;
return null;
}
catch (Exception ex)
{
szLoadError = ex.Message;
return null;
}
}

public string[] Errors
{
get
{
if (m_Errors == null)
{
return new string[] {};
}
else
{
return m_Errors.ToArray();
}
}
}

public object Compile()
{
string[] temp = new string[] {};
return Run(ref temp, true);
}

public object Run(ref string[] szCmdArgs)
{
return Run(ref szCmdArgs, false);
}

protected string Run(ref string[] szCmdArgs, bool bCompileOnly)
{
string functionReturnValue = null;
functionReturnValue = string.Empty;
System.Reflection.Assembly hThisAsm = System.Reflection.Assembly.GetExecutingAssembly();
CodeDomProvider oProvider = CodeDomProvider.CreateProvider(Language);
List<string> szFinalCode = new List<string>();


// Create a sandboxed app domain
Evidence inetEvidence = new Evidence(new object[] { new Zone(System.Security.SecurityZone.Untrusted) }, new object[] {});
PermissionSet inetPerms = SecurityManager.ResolvePolicy(inetEvidence);
AppDomainSetup setup = new AppDomainSetup();
AppDomain sandbox = AppDomain.CreateDomain("TrueScript Domain", inetEvidence, setup, inetPerms, new StrongName[] {});

if (oProvider != null)
{
CompilerParameters cpParams = new CompilerParameters();
if (this.OutputAssembly.Length > 0)
{
cpParams.GenerateExecutable = true;
cpParams.GenerateInMemory = false;
cpParams.OutputAssembly = this.OutputAssembly;
cpParams.CompilerOptions = "/target:" + Type;
}
else
{
cpParams.GenerateExecutable = false;
cpParams.GenerateInMemory = true;
}
if (References.Length == 0)
{
foreach (System.Reflection.AssemblyName szAsm in hThisAsm.GetReferencedAssemblies())
{
cpParams.ReferencedAssemblies.Add(szAsm.Name + ".dll");
}
}
else
{
References = References.Replace(Environment.NewLine, " ");
References = System.Text.RegularExpressions.Regex.Replace(Refer ences, "\\s+", " ");
References = References.Trim();
foreach (string szAsm in References.Split(' '))
{
if (szAsm.Trim().Length > 0)
{
cpParams.ReferencedAssemblies.Add(szAsm.Trim());
}
}
}
if (Includes != null)
{
if (Includes.Length > 0)
{
foreach (string szSource in Includes.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries))
{
string szTempErrs = string.Empty;
Ctscript oTempScr = Ctscript.Load(szSource, ref szTempErrs);
if (oTempScr != null)
{
foreach (string szRef in oTempScr.References.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
if (!cpParams.ReferencedAssemblies.Contains(szRef.Tri m()))
cpParams.ReferencedAssemblies.Add(szRef.Trim());
}
szFinalCode.Add(oTempScr.Code.Value);
}
else
{
m_Errors.Add("Error including " + szSource + ": " + szTempErrs);
}
oTempScr = null;
}
}
}
szFinalCode.Add(Code.Value);
CompilerResults crResults = oProvider.CompileAssemblyFromSource(cpParams, szFinalCode.ToArray());
if (crResults.Errors.Count > 0)
{
foreach (CompilerError ceErr in crResults.Errors)
{
m_Errors.Add(ceErr.ToString());
}
}
else
{
System.Reflection.MethodInfo oMain = default(System.Reflection.MethodInfo);
Assembly oAsm = sandbox.Load(ReadFile(crResults.PathToAssembly));

if (!bCompileOnly)
{
if ((Type.ToLower().CompareTo("library") != 0))
{
if (crResults.CompiledAssembly.EntryPoint == null)
{
oMain = oAsm.CreateInstance(this.StartupObject).GetType(). GetMethod("Main");
}
else
{
oMain = oAsm.EntryPoint;
}
if (oMain.GetParameters().Length == 0)
{
try
{
oMain.Invoke(null, System.Reflection.BindingFlags.Static, null, null, null);
}
catch (Exception ex)
{
m_Errors.Add(ex.ToString());
}
}
else if (oMain.GetParameters().Length == 1)
{
try
{
oMain.Invoke(null, System.Reflection.BindingFlags.Static, null, new object[] { szCmdArgs }, null);
}
catch (Exception ex)
{
m_Errors.Add(ex.ToString());
}
}
else
{
m_Errors.Add("Number of parameters for Main must be zero or one.");
}
}
}
return crResults.PathToAssembly;
}
}
else
{
m_Errors.Add("Could not create code provider.");
return string.Empty;
}
return functionReturnValue;
}

private byte[] ReadFile(string szFilePath)
{
FileStream fs = new FileStream(szFilePath, FileMode.Open);
BinaryReader binReader = new BinaryReader(fs);
byte[] aRet = binReader.ReadBytes((int)fs.Length);
binReader.Close();
return aRet;
}
}

public class CDATA : IXmlSerializable
{

private string m_szText;

public CDATA()
{
}

public string Value
{
get { return m_szText; }
set { m_szText = value; }
}

public CDATA(string szText)
{
m_szText = szText;
}

public override string ToString()
{
return m_szText;
}

public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}

public void ReadXml(System.Xml.XmlReader reader)
{
m_szText = reader.ReadString();
reader.Read();
}

public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteCData(m_szText);
}
}
}


The console program:
/* PROJECT: TrueScript
* AUTHOR: J. V. Smith (Trueborn)
* CONTRIBUTOR(S): J. V. Smith (Trueborn)
* CREATED: 13 Oct 2008
* MODIFIED: 13 Oct 2008
* TITLE: modTrueScript
* DESCRIPTION: This code handles the loading for a TrueScript script
* that does not use GUI elements (System.Windows.Forms)
* COMMENTS:
* LICENSE:
* This software is distributed under the following license:
*
* Microsoft Reciprocal License (Ms-RL)
* This license governs use of the accompanying software. If you use the
* software, you accept this license. If you do not accept the license, do
* not use the software.
*
* 1. Definitions
* The terms "reproduce," "reproduction," "derivative works," and
* "distribution" have the same meaning here as under U.S. copyright
* law.
* A "contribution" is the original software, or any additions or
* changes to the software.
* A "contributor" is any person that distributes its contribution
* under this license.
* "Licensed patents" are a contributor's patent claims that read
* directly on its contribution.
* 2. Grant of Rights
* (A) Copyright Grant- Subject to the terms of this license, including
* the license conditions and limitations in section 3, each
* contributor grants you a non-exclusive, worldwide, royalty-free
* copyright license to reproduce its contribution, prepare derivative
* works of its contribution, and distribute its contribution or any
* derivative works that you create.
* (B) Patent Grant- Subject to the terms of this license, including
* the license conditions and limitations in section 3, each
* contributor grants you a non-exclusive, worldwide, royalty-free
* license under its licensed patents to make, have made, use, sell,
* offer for sale, import, and/or otherwise dispose of its contribution
* in the software or derivative works of the contribution in the
* software.
* 3. Conditions and Limitations
* (A) Reciprocal Grants- For any file you distribute that contains
* code from the software (in source code or binary format), you must
* provide recipients the source code to that file along with a copy of
* this license, which license will govern that file. You may license
* other files that are entirely your own work and do not contain code
* from the software under any terms you choose.
* (B) No Trademark License- This license does not grant you rights to
* use any contributors' name, logo, or trademarks.
* (C) If you bring a patent claim against any contributor over patents
* that you claim are infringed by the software, your patent license
* from such contributor to the software ends automatically.
* (D) If you distribute any portion of the software, you must retain
* all copyright, patent, trademark, and attribution notices that are
* present in the software.
* (E) If you distribute any portion of the software in source code
* form, you may do so only under this license by including a complete
* copy of this license with your distribution. If you distribute any
* portion of the software in compiled or object code form, you may
* only do so under a license that complies with this license.
* (F) The software is licensed "as-is." You bear the risk of using it.
* The contributors give no express warranties, guarantees, or
* conditions. You may have additional consumer rights under your local
* laws which this license cannot change. To the extent permitted under
* your local laws, the contributors exclude the implied warranties of
* merchantability, fitness for a particular purpose and
* non-infringement.
*
* To view an original copy of this license:
* http://www.microsoft.com/opensource/licenses.mspx#Ms-RL
*
*/

using System;
using System.Windows.Forms;
using truecode;

static class modTruescript
{
[STAThread]
public static void Main(string[] args)
{
Ctscript oScript = new Ctscript();

string szLoadErr = string.Empty;


#if (!DEBUG)
AppDomain.CurrentDomain.UnhandledException += UnhandledException;
#endif

if (args.Length == 0)
{
Console.Error.WriteLine("Usage: truescript <scriptfile>");
System.Environment.Exit(0);
}
oScript = Ctscript.Load(args[0], ref szLoadErr);
if ((oScript != null))
{
oScript.Run(ref args);
if (oScript.Errors.Length > 0)
{
MessageBox.Show(String.Join(Environment.NewLine, oScript.Errors), "Output Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Environment.Exit(0);
}
else
{
System.Environment.Exit(0);
}
}
else
{
MessageBox.Show("Error loading script: " + szLoadErr, "TrueScript", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
System.Environment.Exit(0);
}

}

public static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.Error.WriteLine("Unhandled exception - " + Environment.NewLine + e.ExceptionObject.ToString());
}

}


The GUI program:
/* PROJECT: TrueScript
* AUTHOR: J. V. Smith (Trueborn)
* CONTRIBUTOR(S): J. V. Smith (Trueborn)
* CREATED: 13 Oct 2008
* MODIFIED: 13 Oct 2008
* TITLE: modTrueScript
* DESCRIPTION: This code handles the loading for a TrueScript script
* that uses GUI elements (System.Windows.Forms)
* COMMENTS:
* LICENSE:
* This software is distributed under the following license:
*
* Microsoft Reciprocal License (Ms-RL)
* This license governs use of the accompanying software. If you use the
* software, you accept this license. If you do not accept the license, do
* not use the software.
*
* 1. Definitions
* The terms "reproduce," "reproduction," "derivative works," and
* "distribution" have the same meaning here as under U.S. copyright
* law.
* A "contribution" is the original software, or any additions or
* changes to the software.
* A "contributor" is any person that distributes its contribution
* under this license.
* "Licensed patents" are a contributor's patent claims that read
* directly on its contribution.
* 2. Grant of Rights
* (A) Copyright Grant- Subject to the terms of this license, including
* the license conditions and limitations in section 3, each
* contributor grants you a non-exclusive, worldwide, royalty-free
* copyright license to reproduce its contribution, prepare derivative
* works of its contribution, and distribute its contribution or any
* derivative works that you create.
* (B) Patent Grant- Subject to the terms of this license, including
* the license conditions and limitations in section 3, each
* contributor grants you a non-exclusive, worldwide, royalty-free
* license under its licensed patents to make, have made, use, sell,
* offer for sale, import, and/or otherwise dispose of its contribution
* in the software or derivative works of the contribution in the
* software.
* 3. Conditions and Limitations
* (A) Reciprocal Grants- For any file you distribute that contains
* code from the software (in source code or binary format), you must
* provide recipients the source code to that file along with a copy of
* this license, which license will govern that file. You may license
* other files that are entirely your own work and do not contain code
* from the software under any terms you choose.
* (B) No Trademark License- This license does not grant you rights to
* use any contributors' name, logo, or trademarks.
* (C) If you bring a patent claim against any contributor over patents
* that you claim are infringed by the software, your patent license
* from such contributor to the software ends automatically.
* (D) If you distribute any portion of the software, you must retain
* all copyright, patent, trademark, and attribution notices that are
* present in the software.
* (E) If you distribute any portion of the software in source code
* form, you may do so only under this license by including a complete
* copy of this license with your distribution. If you distribute any
* portion of the software in compiled or object code form, you may
* only do so under a license that complies with this license.
* (F) The software is licensed "as-is." You bear the risk of using it.
* The contributors give no express warranties, guarantees, or
* conditions. You may have additional consumer rights under your local
* laws which this license cannot change. To the extent permitted under
* your local laws, the contributors exclude the implied warranties of
* merchantability, fitness for a particular purpose and
* non-infringement.
*
* To view an original copy of this license:
* http://www.microsoft.com/opensource/licenses.mspx#Ms-RL
*
*/

using System;
using System.Windows.Forms;
using truecode;

static class modTruescript
{
[STAThread]
public static void Main(string[] args)
{
Ctscript oScript = new Ctscript();

string szLoadErr = string.Empty;


#if (!DEBUG)
AppDomain.CurrentDomain.UnhandledException += UnhandledException;
#endif

if (args.Length == 0) {
Console.Error.WriteLine("Usage: truescript <scriptfile>");
System.Environment.Exit(0);
}
oScript = Ctscript.Load(args[0], ref szLoadErr);
if ((oScript != null)) {
oScript.Run(ref args);
if (oScript.Errors.Length > 0) {
MessageBox.Show(String.Join(Environment.NewLine, oScript.Errors), "Output Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Environment.Exit(0);
}
else {
System.Environment.Exit(0);
}
}
else {
MessageBox.Show("Error loading script: " + szLoadErr, "TrueScript", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
System.Environment.Exit(0);
}

}

public static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Console.Error.WriteLine("Unhandled exception - " + Environment.NewLine + e.ExceptionObject.ToString());
}

}