JScript for the .NET Framework


Microsoft.JScript.Vsa.VsaEngine


I have a simple function:
public static string EvalJScript(string JScript){ return Microsoft.JScript.Eval.JScriptEvaluate(JScript, Microsoft.JScript.Vsa.VsaEngine.CreateEngine()).ToString();}
that is used all over my .NET 1.1 application and am currently porting over to .NET 2.0. What is the working replacement for this code? I found the following code on the net:
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")][PermissionSet(SecurityAction.Demand, Name="FullTrust")][PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")] public static string EvalJScript(string JScript){
string result = string.Empty;
string JScriptSource =#"package Evaluator{class Evaluator{public function Eval(expr : String) : String{return eval(expr);}}}";
Type evaluatorType = null;object evaluator;CodeDomProvider compiler = CodeDomProvider.CreateProvider("JScript");CompilerParameters parameters = new CompilerParameters();parameters.CompilerOptions = "/t:library";parameters.GenerateInMemory = true;System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromSource(parameters, JScriptSource);System.Reflection.Assembly assembly = results.CompiledAssembly;evaluatorType = assembly.GetType("Evaluator.Evaluator");evaluator = Activator.CreateInstance(evaluatorType);Type t = evaluator.GetType();result = evaluatorType.InvokeMember("Eval", System.Reflection.BindingFlags.InvokeMethod, null, evaluator, new object[] { JScript }).ToString();return result;}
But it continuously throws a security exception. Any help would be greatly appreciated.
InnerException = {"Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."}
I just got my issue fixed.  The problem is with the JScriptSource:
 
string JScriptSource =#"package Evaluator{class Evaluator{public function Eval(expr : String) : String{return eval(expr);}}}";
 
 
if you change it to the following:
string JScriptSource =
#"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr, ""unsafe"");
}
}
}";
 
it should work fine.  This code got rid of my {"Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."} error.  I tested my code and it works fine.  I can finally get rid of the last piece of depricated code!!  I hope this works for everyone and thanks for your help.
 
Full function:
 
public static string EvalJScript(string JScript){ 
string result = string.Empty;
string JScriptSource =#"package Evaluator{class Evaluator{public function Eval(expr : String) : String{return eval(expr, ""unsafe"");}}}";
Type evaluatorType = null;object evaluator;CodeDomProvider compiler = CodeDomProvider.CreateProvider("JScript");CompilerParameters parameters = new CompilerParameters();parameters.CompilerOptions = "/t:library";parameters.GenerateInMemory = true;System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromSource(parameters, JScriptSource);System.Reflection.Assembly assembly = results.CompiledAssembly;evaluatorType = assembly.GetType("Evaluator.Evaluator");evaluator = Activator.CreateInstance(evaluatorType);Type t = evaluator.GetType();result = evaluatorType.InvokeMember("Eval", System.Reflection.BindingFlags.InvokeMethod, null, evaluator, new object[] { JScript }).ToString();return result;}
Hi
rpansini,have you had a reply on this? I am interested in the solution. Thanks.
I wish someone would respond to this.  This is still an open issue.
I also have this issue.  Has anyone solved this yet?
Hi,It worked on mine (on my dev machine). I have something similar exception my CodeProvider code is as follow: JScriptCodeProvider jsCodeProvider = new JScriptCodeProvider(); CompilerParameters compilerParam = new CompilerParameters(); compilerParam.ReferencedAssemblies.Add("System.dll"); compilerParam.ReferencedAssemblies.Add("System.Data.dll"); compilerParam.ReferencedAssemblies.Add("System.Xml.dll"); compilerParam.CompilerOptions = "/t:library"; compilerParam.GenerateInMemory = true; CompilerResults compilerResult = jsCodeProvider.CompileAssemblyFromSource(compilerParam, _jscriptSource); if (compilerResult.Errors.Count > 0) { string errMsg = String.Format("Compiling JSScript code failed and threw the exception: {0}", compilerResult.Errors[0].ErrorText); Trace.Fail(errMsg); throw new ApplicationException(errMsg); } Assembly assembly = compilerResult.CompiledAssembly; _evaluatorType = assembly.GetType("Evaluator.JsEvaluator"); _evaluator = Activator.CreateInstance(_evaluatorType); I've tested this in NUnit and in a Console App under Framework 2.0 without getting an exception. If it doesn't work for you, perhaps you may want to look at your .Net permissions.
I tried adding your referenced assemblies, but I still get the error:
 
I can actually run a simple javasrcript such as:
// this runs fine.
var a = 2;var b = 3;b*a;
 
but if i try the following, I get the security error:
// I get security error on this.
function timestwo(c){  return c * 2;}
timestwo(4);
Can you post your entire source?Here is mine, you will just need to change a few things for it to run:using System;using System.CodeDom.Compiler;using System.Diagnostics;using System.Reflection;using Microsoft.JScript;using System.Text;namespace Dotnet.Commons.Lang.ExpressionEval{    /// <summary>    /// This class provides the ability to execute JScript code dynamically and return the result as    /// an int, double, string or an object.    /// </summary>    public class JsEvalProvider : BaseEvaluator    {        private object _evaluator = null;        private Type _evaluatorType = null;        private static JsEvalProvider _instance = null;        private static object _synObject = new object();        // JScript Source string which will evaluate the expression        private static readonly string _jscriptSource =            #"            import System;            import System.Collections;            import System.IO;            import System.Text;            import System.Xml;            package Evaluator {                public class JsEvaluator                {                    public function Eval(expr : String) : Object                     {                         var result = eval(expr);                         if (result != null)                             return result;                        else                            return null;                    }                }              }";        /// <summary>        /// private Constructor        /// </summary>        private JsEvalProvider()        {            // Initialise static variables            initialise();        }        /// <summary>        ///         /// </summary>        /// <returns></returns>        public static JsEvalProvider GetInstance()        {            if (_instance == null)            {                lock (_synObject)                {                    if (_instance == null)                    {                        _instance = new JsEvalProvider();                    }                }            }            return _instance;        }        private void initialise()        {            //ICodeCompiler compiler = new JScriptCodeProvider().CreateCompiler();            JScriptCodeProvider jsCodeProvider = new JScriptCodeProvider();            CompilerParameters compilerParam = new CompilerParameters();            compilerParam.ReferencedAssemblies.Add("System.dll");            compilerParam.ReferencedAssemblies.Add("System.Data.dll");            compilerParam.ReferencedAssemblies.Add("System.Xml.dll");            compilerParam.ReferencedAssemblies.Add("Dotnet.Commons.Lang.dll");            compilerParam.CompilerOptions = "/t:library";            compilerParam.GenerateInMemory = true;            CompilerResults compilerResult = jsCodeProvider.CompileAssemblyFromSource(compilerParam, _jscriptSource);            if (compilerResult.Errors.Count > 0)            {                string errMsg = String.Format("Compiling JSScript code failed and threw the exception: {0}", compilerResult.Errors[0].ErrorText);                Trace.Fail(errMsg);                throw new ApplicationException(errMsg);            }            Assembly assembly = compilerResult.CompiledAssembly;            _evaluatorType = assembly.GetType("Evaluator.JsEvaluator");            _evaluator = Activator.CreateInstance(_evaluatorType);                }        /// <summary>        /// Evaluate teh expression and return a <see cref="System.Boolean" /> result.        /// </summary>        /// <param name="expression">C# expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.Boolean" />.</returns>        public override bool? EvalToBoolean(string expression)        {            string result = EvalToString(expression);            if (result == null || result.Equals(string.Empty))                return null;            return Boolean.Parse(result);        }        /// <summary>        /// Evaluate the expression and return an <see cref="System.Int32" /> result.        /// </summary>        /// <param name="expression">JScript expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.Int32" />.</returns>        public override int? EvalToInteger(string expression)        {            string result = EvalToString(expression);            if (result == null || result.Equals(string.Empty))                return null;                        return int.Parse(result.ToString());        }        /// <summary>        /// Evaluate teh expression and return a <see cref="System.Double" /> result.        /// </summary>        /// <param name="expression">JScript expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.Double" />.</returns>        public override double? EvalToDouble(string expression)        {            string result = EvalToString(expression);            if (result == null || result.Equals(string.Empty))                return null;            return double.Parse(result);        }        /// <summary>        /// Evaluate the express and return a <see cref="System.String" /> result.        /// </summary>        /// <param name="expression">JScript expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.String" />.</returns>        public override string EvalToString(string expression)        {            object o = EvalToObject(expression);            if (o == null)                return string.Empty;            return o.ToString();        }        /// <summary>        /// Execute the evaluation express and return an <see cref="System.Object" /> result.        /// </summary>        /// <param name="expression">JScript expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.Object" />.</returns>        public override object EvalToObject(string expression)        {            // object evaluator = Activator.CreateInstance(m_evaluatorType);            // Execute the Eval method with the results.            object result = null;                        // Check to see that the static variable have been initialised            if(_evaluatorType == null || _evaluator == null)            {                Debug.WriteLine ("Static Variables Initialised from EvalToObject");                initialise();            }            if (expression == null || expression.Length == 0)            {                Trace.TraceWarning(String.Format("Expression to evaluate '{0}' is null or empty", expression));            }            try             {                result = _evaluatorType.InvokeMember("Eval", BindingFlags.InvokeMethod, null, _evaluator, new object[] { expression } );            }             catch(Exception ex) {                 Trace.Fail(String.Format("ExpressionEvaluator.EvalToObject('{0}') threw the exception: {1}", expression, ex.StackTrace));            }            return result;        }    }}---------BaseEvaluator class:using System;using System.Collections.Generic;using System.Text;namespace Dotnet.Commons.Lang.ExpressionEval{    /// <summary>    ///     /// </summary>    public abstract class BaseEvaluator    {        /// <summary>        /// Evaluate the expression and return an <see cref="System.Int32" /> result.        /// </summary>        /// <param name="expression">expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.Int32" />.</returns>        public abstract int? EvalToInteger(string expression);        /// <summary>        /// Evaluate the expression and return a <see cref="System.Double" /> result.        /// </summary>        /// <param name="expression">expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.Double" />.</returns>        public abstract double? EvalToDouble(string expression);        /// <summary>        /// Evaluate the express and return a <see cref="System.String" /> result.        /// </summary>        /// <param name="expression">expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.String" />.</returns>        public abstract string EvalToString(string expression);        /// <summary>        /// Execute the evaluation express and return an <see cref="System.Object" /> result.        /// </summary>        /// <param name="expression">expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.Object" />.</returns>        public abstract object EvalToObject(string expression);        /// <summary>        /// Execute the evaluation express and return an <see cref="System.Boolean" /> result.        /// </summary>        /// <param name="expression">expression to be executed.</param>        /// <returns>Evaluated result as an <see cref="System.Boolean" />.</returns>        public abstract bool? EvalToBoolean(string expression);        /// <summary>        /// Tag used for inserting the expression into the code for compiling on the fly.        /// </summary>        protected const string  EXPRESSION_TAG = "${expression}";    }}
Hi,
 
I used the code posted by Joe Black. It  compiles with miniscule changes and I even get the JsEvalProvider  object.
However, when I try to eval anything beyond trivial expressions, I get the dreaded exception reported in the original post:
 
{"Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."}
 
I also tried another approach - compiling a dll from a .js file, with a single object that evaluates a javascript string and returns the result. (see the comment by Joe in http://west-wind.com/WebLog/posts/10688.aspx for details).
This solution suffers from the same problem. I took the resulting dll, gave it a strong name, ran caspol -af on it, added it to the GAC - nada. I still get the same exception when I try to evaluate any javascript code with a function in it.
 
This is done under .Net 3.0. Any help will be greatly appreciated.
 
I just got my issue fixed.  The problem is with the JScriptSource:
 
string JScriptSource =#"package Evaluator{class Evaluator{public function Eval(expr : String) : String{return eval(expr);}}}";
 
 
if you change it to the following:
string JScriptSource =
#"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr, ""unsafe"");
}
}
}";
 
it should work fine.  This code got rid of my {"Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."} error.  I tested my code and it works fine.  I can finally get rid of the last piece of depricated code!!  I hope this works for everyone and thanks for your help.
 
Full function:
 
public static string EvalJScript(string JScript){ 
string result = string.Empty;
string JScriptSource =#"package Evaluator{class Evaluator{public function Eval(expr : String) : String{return eval(expr, ""unsafe"");}}}";
Type evaluatorType = null;object evaluator;CodeDomProvider compiler = CodeDomProvider.CreateProvider("JScript");CompilerParameters parameters = new CompilerParameters();parameters.CompilerOptions = "/t:library";parameters.GenerateInMemory = true;System.CodeDom.Compiler.CompilerResults results = compiler.CompileAssemblyFromSource(parameters, JScriptSource);System.Reflection.Assembly assembly = results.CompiledAssembly;evaluatorType = assembly.GetType("Evaluator.Evaluator");evaluator = Activator.CreateInstance(evaluatorType);Type t = evaluator.GetType();result = evaluatorType.InvokeMember("Eval", System.Reflection.BindingFlags.InvokeMethod, null, evaluator, new object[] { JScript }).ToString();return result;}
thank you so much, it works perfectly.This tiny change has a huge significance for my software. 
Just to warn you all about this approach. Everytime this method is executed, a new assembly is loaded into the current AppDomain and can only be unloaded when the AppDomain unloads (which usually happens when the application exits). If this is a problem to you, consider creating a new AppDomain and load the newly created assembly there. Regards

Related Links

Microsoft jScript runtime error
how to make a screen Like this?
Not Understand javascript code compatible with IE
how to find a texbox control inside a datagrid using javascript
ajax controls similar to office on web application
Create new HTML Helper for Search button
IE7 showmodaldialog displays unnecessary scroll bar with content
Javascript client server download speed help
Help i am getting this error 'Runtime error: unable to load dll jscript." can anybody help?
scrollbar in asp ListBox control
De-serialize Json in WPF
column resizing with repeater control
take snapshot of google map on javascript button click
Change ImageURL with JScript
document.getElementById().innerHTML fails with 'Unknown Error' in IE
using visual studio 2005 and getting error "Microsoft JScript runtime error : Object expected" in clicking any of webpage

Categories

MSDN
Game Development
SharePoint
Data Platform Development
Internet Explorer Deve...
Windows Hardware Devel...
Lync Server
Archived Forums E-H
Archived Forums V
Archived Forums Visual...
Windows Phone Preview ...
Kinect for Windows SDKs
Archived Forums
Microsoft R
Cortana
Announcements for all ...
Suggestions and Feedba...
Visual F#
Visual Studio General ...
Visual Studio Integrate
Visual Studio Tools fo...
Visual Studio LightSwi...
Visual Studio Unit Tes...
Submitting and Publish...
DirectShow Development
Windows Desktop Develo...
Windows Desktop Search...
Hardware Development B...
SharePoint 2013 - Usin...
SharePoint Legacy Vers...
Azure Management Portal
Service Bus
Azure BizTalk Services
Azure Networking (DNS,...
Azure HDInsight
Azure Marketplace
StorSimple
Azure Security Center
Azure Database for MySQL
Azure Time Series Insi...
Claims based access pl...
Commerce Server 2007
HealthVault Developer
Microsoft Live Labs Volta
Microsoft Translator H...
Small Basic
SyncFx - SyncToy-File ...
Microsoft Robotics - C...
SQL Server Integration...
.NET Framework inside ...
SQL Server High Availa...
Getting started with S...
SQL Server Data Wareho...
SQL Server Samples and...
SQL Server Data Qualit...
Windows Embedded 8 Sta...
Standard 2009: Compone...
Standard 7: Embedded E...
Standard 7: Servicing ...
SQL Server 2012 PowerP...
SQL Server 2012 SQL To...
Windows Live Messenger...
Speech Service for Dev...
WebsitePanel - Discuss...
WebsitePanel - Enterpr...
Bing Maps General
Game Development with ...
Search Server: Install...
Retired InfoPath Forms...
ADO.NET Entity Framewo...
Building Windows Store...
Charts & Reports in th...
Dynamic Languages on .NET
Expression Community S...
Game Technologies: Dir...
Git, Mercurial and Dro...
Microsoft adCenter: De...
Microsoft Unified Comm...
Monitor, Alert and Aut...
Office Live Small Busi...
Parallel Computing Pla...
Pex and Moles PowerTool
Popfly Bugs and Sugges...
Regular Expressions
Search Server: Feature...
Search Server: Federation
Sharepoint Development...
Silverlight (formerly ...
Security for Azure
Service Bus EAI & EDI ...
Surface Application De...
SQL Server 2014 Integr...
Team Foundation Server...
Team Foundation Server...
Tools for Windows Stor...
Visual Basic Express E...
Visual C# Express 2008...
Visual C# Language
Visual Studio Tools fo...
Web Sandbox - Exploits
Windows Live Controls ...
Windows Live Search: D...
Working with Data in W...
Building Windows Store...
XML in Visual Studio a...
Reporting
Microsoft R Server
Open source Developmen...

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile