taritsyn / msiejavascriptengine Goto Github PK
View Code? Open in Web Editor NEW.NET wrapper for working with the JavaScript engines of Internet Explorer and Edge Legacy.
License: Apache License 2.0
.NET wrapper for working with the JavaScript engines of Internet Explorer and Edge Legacy.
License: Apache License 2.0
Is there any reason why you have nuget.exe in .nuget and Nuget folders?
What's the purpose of using MsieJavaScriptEngine?
When would someone use it, use case?
I have executed the following script:
var obj = { n: 123, s: 'str' }
GetVariableValue("obj") has returned COM Object.
How can I get data from JS to C# as ExpandoObject or Dictionary<string, object>?
var jsEngine = new MsieJsEngine(new JsEngineSettings {
EngineMode = JsEngineMode.Auto,
UseEcmaScript5Polyfill = false,
UseJson2Library = false
});
DateTime? n = DateTime.Now;
jsEngine.EmbedHostObject("n", n);
jsEngine.Execute(@"n.Value.ToString(""yyyy-MM-dd"")");
MsieJavaScriptEngine.JsRuntimeException:“TypeError: Unable to get property 'ToString' of undefined or null reference
at Global code (Script Document:1:1)”
It doesn't look like you can embed anonymous objects with EmbedHostObject at present.
Is the best way to do this to serialize the object to json and include in the js being executed?
Thanks.
Is there any documentation in place for this?
After doing an analysis of one of our Memory dumps, Microsoft stated this.
_However for your specific instance your finalizer thread is blocked by a ChakraEdgeJsRtJsEngine object. When looking at the amount of exceptions it seems as if there are thousands and thousands of exceptions all rooted to System.Net.Connection which are all stuck waiting to be finalized. They can't execute their finalize method because of the blocked finalizer thread below.
It's stuck on a Wait call which is part of the Dispose() method. I would recommend disposing ALL instances of the Chakra engine in your code as this will explicitly avoid the finalizer from being called. What the ChakraEngine looks like it's doing here is when this object is finalized it called a native method to reduce a ref counter to an object, this is either taking too long or never returns (I can't tell).
Assuming you're using this library here (https://github.com/Taritsyn/MsieJavaScriptEngine), I would take a look at this code to ensure you know what it's doing when, as there are a lot of finalizers due to the PInvokes into the JavaScript engine. I think it's also pretty clear that this isn't a Microsoft library so I don't know how far Michael or I can help debug this._
mscorlib_ni!System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle, Int64, Boolean, Boolean)+1b
mscorlib_ni!System.Threading.WaitHandle.WaitOne(Int32, Boolean)+2e
MsieJavaScriptEngine.ScriptDispatcher.InnnerInvoke(System.Func`1)+80
MsieJavaScriptEngine.JsRt.Edge.ChakraEdgeJsRtJsEngine.Dispose(Boolean)+58
MsieJavaScriptEngine.JsRt.Edge.ChakraEdgeJsRtJsEngine.Finalize()+d
[[DebuggerU2MCatchHandlerFrame]]
[[ContextTransitionFrame]]
[[GCFrame]]
[[DebuggerU2MCatchHandlerFrame]]
Do you know if this is fixed in your latest release?
Are there any intentions to add support for JS functions which return await
able Promises to the caller and similarly, support for having JS code await
on .NET awaitables?
If not, would it be a welcome addition?
I see that ChakraCore supports promises to some degree, with a little documentation here: https://github.com/Microsoft/ChakraCore/wiki/JavaScript-Runtime-%28JSRT%29-Overview#promises
I would welcome direction on how to best implement this :)
Hi Taritsyn,
Some users are reporting VS crashes while running T4 templates after installing Windows 10 anniversary update. I'm using MsieJavascriptEngine inside .tt files to parse TypeScript code.
It seems like something has changed with Edge / Chakra in this update.
Here is a crash log from one of users:
https://gist.github.com/VictorTomaili/58165b8962232a7d16589adc8d3e79b8
I asked this user to select JsEngineMode.ChakraIeJsRt, instead of Auto, and this fixed the crash.
In my machine i don't have anniversary update yet, but i used JsEngineMode.ChakraActiveScript and also had a similar crash. Wİth Auto/ChakraIeJsRt it works fine.
I have been trying to run the latest JSLint under Chakra using this tool. It would solve a bunch of issues for JSLint.NET.
Unfortunately the latest edition of jslint.js doesn't get past the parser - it falls over on a property named "continue" (legal in ES5). When I debug, I can see that it's using the ChakraJsEngine, but that doesn't seem to change how it's parsed.
I don't know much about how ActiveScript works, but is there some way to change the parser to use whatever IE9+ is using?
Hi Taritsyn,
I am getting below exception, intermittently on Windows Server 2008R2.
not able to reproduce this exception on my local windows 7.
can you please provide some more info on the reason for this issue.
System.Web.HttpException: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'.
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
at System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func
1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func
1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func
1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList
1 filters, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.b__22(IAsyncResult asyncResult)
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.Mvc.ViewPage.ProcessRequest(HttpContext context)
at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.<>c__DisplayClass4.b__3()
at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func1 func) at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Reflection.Assembly.CreateInstance(String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at JavaScriptEngineSwitcher.Core.Utilities.Utils.CreateInstanceByFullTypeName[T](String fullTypeName) at JavaScriptEngineSwitcher.Core.JsEngineSwitcher.CreateJsEngineInstance(String name) at BundleTransformer.Less.Compilers.LessCompiler..ctor(Func
1 createJsEngineInstance, CompilationOptions defaultOptions)
at BundleTransformer.Less.Translators.LessTranslator.Translate(IList1 assets) at BundleTransformer.Core.Transformers.TransformerBase.Translate(IList
1 assets, Boolean isDebugMode)
at BundleTransformer.Core.Transformers.CssTransformer.Transform(IList1 assets, BundleResponse bundleResponse, VirtualPathProvider virtualPathProvider, HttpContextBase httpContext, Boolean isDebugMode) at BundleTransformer.Core.Transformers.TransformerBase.Process(BundleContext context, BundleResponse response, Boolean isDebugMode) at System.Web.Optimization.Bundle.ApplyTransforms(BundleContext context, String bundleContent, IEnumerable
1 bundleFiles)
at System.Web.Optimization.Bundle.GetBundleResponse(BundleContext context)
at System.Web.Optimization.BundleResolver.GetBundleContents(String virtualPath)
at System.Web.Optimization.AssetManager.EliminateDuplicatesAndResolveUrls(IEnumerable1 refs) at System.Web.Optimization.AssetManager.DeterminePathsToRender(IEnumerable
1 assets)
at System.Web.Optimization.AssetManager.RenderExplicit(String tagFormat, String[] paths)
at ASP._Page_XXXXXXX_YYYYYY_ZZZZZ__Head_cshtml.Execute() in c:*************_Head.cshtml:line 13
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at AW.Web.Mvc.BaseView`1.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper htmlHelper, String partialViewName)
at ASP.xxxxx_yyyyy_zzzzz_aaaaa_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer)
at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
JavaScriptEngineSwitcher.Core.JsEngineLoadException: During loading of MSIE JavaScript engine error has occurred.
See more details:
The requested lookup key was was not found in any active activation context.
at JavaScriptEngineSwitcher.Msie.MsieJsEngine..ctor(MsieConfiguration msieConfig)
System.ComponentModel.Win32Exception: The requested lookup key was was not found in any active activation context.
at MS.Win32.HwndWrapper..ctor(Int32 classStyle, Int32 style, Int32 exStyle, Int32 x, Int32 y, Int32 width, Int32 height, String name, IntPtr parent, HwndWrapperHook[] hooks)
at System.Windows.Threading.Dispatcher..ctor()
at MsieJavaScriptEngine.ActiveScript.ActiveScriptJsEngineBase..ctor(String clsid, String engineModeName, String lowerIeVersion, Boolean useEcmaScript5Polyfill, Boolean useJson2Library)
at MsieJavaScriptEngine.MsieJsEngine..ctor(JsEngineMode engineMode, Boolean useEcmaScript5Polyfill, Boolean useJson2Library)
at JavaScriptEngineSwitcher.Msie.MsieJsEngine..ctor(MsieConfiguration msieConfig)
Any ideas on this one?
var engine = new MsieJsEngine(JsEngineMode.Auto);
//this works
engine.Execute("var foo = 'ddd';");
//this doesnt
var thread = new Thread(() => engine.Execute("var foobar = 'ddd';"));
thread .Start();
Thread.Sleep(10000);
I have an asp.net site that uses JavaScriptEngineSwitcher.MSIE and MsieJavaScriptEngine. Versions 2.0.0 worked fine but after upgrade to JavaScriptEngineSwitcher.MSIE 2.4.11 and MsieJavaScriptEngine 2.2.5, it crashes IIS express on starting the site. VS 2015 reports:
System.AccessViolationException was unhandled
Message: An unhandled exception of type 'System.AccessViolationException' occurred in MsieJavaScriptEngine.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I also tried 3.0.0 beta 3, same error. In Windows 10 it seems to work. I realize it's not much info to debug this - if I can do something to get more info, let me know.
I have seen several related issues on different repos but I have not seen this specific one, sorry if this is a duplicate. All the related issues seem to have been solved by updating packages, but I am running the latest I know of.
I am not seeing this issue consistently so I don't know how to reproduce reliably.
I am using:
Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at MsieJavaScriptEngine.JsRt.Ie.IeNativeMethods.JsSetCurrentContext(IeJsContext context)
at MsieJavaScriptEngine.JsRt.Ie.ChakraIeJsRtJsEngine.<>c__DisplayClass30_0`1.<InvokeScript>b__0()
at MsieJavaScriptEngine.ScriptDispatcher.<>c__DisplayClass10_0`1.<Invoke>b__0()
at MsieJavaScriptEngine.ScriptDispatcher.StartThread()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
I want to pass a JavaScript object reference in as an argument in CallFunction
. Do you think this might be possible to do? I currently get this exception when using this code (from ctaggart/TsAst#5):
module Taser.Chakra
open MsieJavaScriptEngine
let main() =
use jse =
new MsieJsEngine(
JsEngineSettings(
EngineMode = JsEngineMode.ChakraEdgeJsRt,
UseEcmaScript5Polyfill = false,
UseJson2Library = false))
jse.Execute
"""
function add(num1, num2) {
return (num1 + num2);
}
"""
let a = jse.Evaluate "add(7, 9);"
printfn "a: %A" a // a: 16.0
let b = jse.Evaluate<int> "add(7, 9);"
printfn "b: %A" b // b: 16
let i = jse.CallFunction<int>("add", 7, 9)
printfn "i: %A" i // i: 16
jse.ExecuteFile @"C:\ts\TsAst\node_modules\typescript\lib\typescriptServices.js"
let node = jse.Evaluate @"ts.createNode(1);"
printfn "node: %A" node // node: System.__ComObject
jse.Execute "function getKind(node){ return node.kind; }"
let kind = jse.CallFunction("getKind", node);
// Exception: One of the function parameters 'getKind' has a type `System.__ComObject`, which is not supported.
printfn "kind: %A" kind
Do you know what would cause this exception? I see it sporadically and occasionally get reports of people encountering it in ReactJS.NET
An unhandled exception of type 'System.AccessViolationException' occurred in MsieJavaScriptEngine.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at MsieJavaScriptEngine.JsRt.Edge.EdgeNativeMethods.JsCallFunction(EdgeJsValue function, EdgeJsValue[] arguments, UInt16 argumentCount, EdgeJsValue& result)
at MsieJavaScriptEngine.JsRt.Edge.EdgeJsValue.CallFunction(EdgeJsValue[] arguments)
at MsieJavaScriptEngine.JsRt.Edge.ChakraEdgeJsRtJsEngine.<>c__DisplayClassc.<CallFunction>b__b()
at MsieJavaScriptEngine.JsRt.Edge.ChakraEdgeJsRtJsEngine.InvokeScript[T](Func`1 func)
at MsieJavaScriptEngine.JsRt.Edge.ChakraEdgeJsRtJsEngine.CallFunction(String functionName, Object[] args)
at MsieJavaScriptEngine.MsieJsEngine.CallFunction(String functionName, Object[] args)
at JavaScriptEngineSwitcher.Msie.MsieJsEngine.InnerCallFunction(String functionName, Object[] args)
at JavaScriptEngineSwitcher.Msie.MsieJsEngine.InnerCallFunction[T](String functionName, Object[] args)
at JavaScriptEngineSwitcher.Core.JsEngineBase.CallFunction[T](String functionName, Object[] args)
at React.JavaScriptEngineUtils.CallFunctionReturningJson[T](IJsEngine engine, String function, Object[] args) in C:\src\ReactJS.NET\src\React.Core\JavaScriptEngineUtils.cs:line 89
at React.ReactEnvironment.ExecuteWithBabel[T](String function, Object[] args) in C:\src\ReactJS.NET\src\React.Core\ReactEnvironment.cs:line 323
at React.Babel.TransformWithSourceMap(String input, String filename) in C:\src\ReactJS.NET\src\React.Core\Babel.cs:line 287
at React.Babel.TransformWithHeader(String filename, String contents, String hash) in C:\src\ReactJS.NET\src\React.Core\Babel.cs:line 225
at React.Babel.TransformFileWithSourceMap(String filename, Boolean forceGenerateSourceMap) in C:\src\ReactJS.NET\src\React.Core\Babel.cs:line 126
at React.Babel.TransformFile(String filename) in C:\src\ReactJS.NET\src\React.Core\Babel.cs:line 89
at React.ReactEnvironment.EnsureUserScriptsLoaded() in C:\src\ReactJS.NET\src\React.Core\ReactEnvironment.cs:line 165
at React.ReactEnvironment.CreateComponent[T](String componentName, T props, String containerId, Boolean clientOnly) in C:\src\ReactJS.NET\src\React.Core\ReactEnvironment.cs:line 265
at React.AspNet.HtmlHelperExtensions.React[T](IHtmlHelper htmlHelper, String componentName, T props, String htmlTag, String containerId, Boolean clientOnly, Boolean serverOnly, String containerClass) in C:\src\ReactJS.NET\src\React.AspNet\HtmlHelperExtensions.cs:line 86
at Asp._Views_Home_Index_cshtml.<ExecuteAsync>d__25.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Asp._Views_Home_Index_cshtml.ExecuteAsync()
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.