Quantcast
Channel: ClearScript
Viewing all 2297 articles
Browse latest View live

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
Is this what you want? (it was truncated)

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
Yes, but unfortunately, as you can see, the native symbols are missing. Did you build ClearScript yourself? If so, you should be able to load the symbols (.PDBs) for the ClearScriptV8-32 and v8-ia32 assemblies into the debugger to get a stack with the relevant symbols. In the meantime we'll see if we can reproduce this with Eclipse.

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
I am using Nuget package manager for the Clearscript library.

If the pdb files for version 5.4.6 can be downloded, I would be glad if you could provide a download link.

Othwrwise I will download and compile the source code.

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
Hi again,

We don't distribute ClearScript binaries; please consider contacting the NuGet package owners or building ClearScript yourself. If you decide to do the latter, remember to copy all the ClearScript .DLLs and .PDBs to your application's binary folder.

We've now tested with Eclipse, and we couldn't reproduce the issue. The application remained responsive, writing "SizeChanged" to the console with both debuggers attached. Both script and managed/native breakpoints continued to work correctly.

Nevertheless, if you can collect a fully symbolized call stack, we'll be happy to check it out :)

Thanks!

Commented Unassigned: Cannot access a disposed object Error [114]

0
0
I get a weird "Cannot access a disposed object." error which I cant track down for its evil root.

Im stuck in not finding the cause and out of ideas.
its going to be difficult to explain, but basically I have 2 VBScript Engines instances running the same code in a sequential, non-parallel order. like:

```
var engine1 = new VBScriptEngine();
engine1.Execute(..);
engine1.Execute(..);
try {
engine1.Execute("engine1.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine1.Dispose();
engine1 = null;

var engine2 = new VBScriptEngine();
engine2.Execute(..);
engine2.Execute(..);
try {
engine2.Execute("engine2.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine2.Dispose();
engine2 = null;

```

If I dont call the Dispose() method after an engine finishes its job with a final Interrupt() call inside a loaded Script Document, everything is doing fine.

but on calling the Dispose() method on the 1st VBScript Engine after it finishes all tasks and stops with an Interrupt() call, the 2nd VBScript Engine still makes it to end of all its user script including the final Interrupt() call from within a Script document, but than somehow hits an "Cannot access a disposed object" Error after the engine successfully catches the Interrupt Exception.

I ve attached some screenshots where I think they might be better to further analyze the issue.

in addition some short descriptions to the attached images:

(se_all_intrptex.PNG)
1st script engine runs all script code, finishes and finally calls Interrupt() inside a script document, hitting the breakpoint in WindowsScriptEngine.Site.cs:231.

(se1_1oninvokeex.PNG)
hits InvokeMethod(...):177
and continues with Marshal.GetObjectForNativeVariant(...)

(se1_ondisposeex.PNG)
step-in next stops at CoTaskMemBlock.cs - Dispose():85
NOTICE the exception in the Locals Window writes: Exception HRESULT 0x80020101

(se1_errout.PNG + se1_errout_det.PNG)
last significant break seems to be here, where the exception catched before is being thrown.


when the 2nd script engine finishes all user script and receives the Interrupt() call, things go the same except that the Exception in the Locals Window (se2_2ondisposeex.PNG) now writes "Cannot access a disposed object..."

further it continues and throws a TargetInvocationException with the "Cannot access a disposed object" inside as inner exception.

the only difference I could catch here is that omitting the Dispose() call on the script engines produces all times a HRESULT 0x80020101 Exception as soon as CoTaskMemBlock.cs - Dispose():86 is hit.

but by having the Dispose() calls, all scripts engines created afterwards will produce a "Cannot access a disposed object".

one more to note: the object which is being noted as disposed is a: Microsoft.ClearScript.Windows.VBScriptEngine' object. the screenshots: se2_1oninvokeex.PNG, se2_2ondisposeex.PNG just suck in showing it.

I tried to step trough into any line inside the clearscript implementation where the scriptengine.IsDisposed prop was set to true, but no luck. I could not find any context where the scriptengine was marked as IsDisposed=true before the exception "Cannot access a disposed object" was thrown.

anyways, my quick fix so far is a simple exception check similar to:
```
...
catch (Exception e) {
if !(myFlag.IsScriptFinished && e.InnerException != null && e.InnerException.Message.Contains("Cannot access a disposed object."))
throw e;
}
...
```

much appreciate any help. thanks





Comments: turns out the issue is occurring in recursive ManagedContext <> ScriptHostContext calls. and my code has a lot of it. but the evil doer was actually my helper function to suppress the, for me in most cases useless, ScriptInterruptedException. ``` public static void Stop(this WindowsScriptEngine engine) { try { engine.Interrupt(); } catch (Exception e) { if (!e.IsScriptInterruptedException()) throw; } } public static bool IsScriptInterruptedException(this Exception e) { do { if (e is ScriptInterruptedException) return true; e = e.InnerException; } while (e != null); return false; } ``` what seems to have happened in case of recursive calls was, that inner level calls in the ScriptContext couldnt catch up with the ScriptInterrupted exceptions thrown by child calls. so had other nestest exceptions(TargetInvocation in most cases) which the Engine tried to package into new exceptions. but then, if the engine was disposed already by a deeper occured invokation down the ladder, it tried to work on a dead engine instance. well, in short the fix for my problem would be either to check for a ScriptInterrupted Exception explicitly on each line of invocation whether in ManagedContext or ScriptContext or to go with this to have more simple project level code for cases where I don't care of a ScriptInterruptedException's: WindowsScriptEngine.cs:108 ``` private bool suppressInterruptedException = false; ``` WindowsScriptEngine.cs:384 ``` /// <summary> /// Interrupts script execution and causes the script engine to throw an exception. /// </summary> /// <remarks> /// This method can be called safely from any thread. /// </remarks> public override void Interrupt() { Interrupt(false); } /// <summary> /// Interrupts script execution and causes the script engine to throw an exception. /// </summary> /// <remarks> /// This method can be called safely from any thread. /// </remarks> /// <param name="suppressException">Suppresses the ScriptInterruptException</param> public void Interrupt(bool suppressException) { VerifyNotDisposed(); suppressInterruptedException = suppressException; var excepInfo = new EXCEPINFO { scode = RawCOMHelpers.HResult.E_ABORT }; activeScript.InterruptScriptThread(ScriptThreadID.Base, ref excepInfo, ScriptInterruptFlags.None); } ``` WindowsScriptEngine.cs:769 ``` internal override T ScriptInvoke<T>(Func<T> func) { VerifyAccess(); return base.ScriptInvoke(() => { try { return func(); } catch (Exception exception) { try { ThrowScriptError(exception); } catch (ScriptInterruptedException) { if (suppressInterruptedException) { suppressInterruptedException = false; return default(T); } throw; } throw; } }); } ``` Does this going to break something else? For now it does well in my project.

Commented Unassigned: Cannot access a disposed object Error [114]

0
0
I get a weird "Cannot access a disposed object." error which I cant track down for its evil root.

Im stuck in not finding the cause and out of ideas.
its going to be difficult to explain, but basically I have 2 VBScript Engines instances running the same code in a sequential, non-parallel order. like:

```
var engine1 = new VBScriptEngine();
engine1.Execute(..);
engine1.Execute(..);
try {
engine1.Execute("engine1.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine1.Dispose();
engine1 = null;

var engine2 = new VBScriptEngine();
engine2.Execute(..);
engine2.Execute(..);
try {
engine2.Execute("engine2.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine2.Dispose();
engine2 = null;

```

If I dont call the Dispose() method after an engine finishes its job with a final Interrupt() call inside a loaded Script Document, everything is doing fine.

but on calling the Dispose() method on the 1st VBScript Engine after it finishes all tasks and stops with an Interrupt() call, the 2nd VBScript Engine still makes it to end of all its user script including the final Interrupt() call from within a Script document, but than somehow hits an "Cannot access a disposed object" Error after the engine successfully catches the Interrupt Exception.

I ve attached some screenshots where I think they might be better to further analyze the issue.

in addition some short descriptions to the attached images:

(se_all_intrptex.PNG)
1st script engine runs all script code, finishes and finally calls Interrupt() inside a script document, hitting the breakpoint in WindowsScriptEngine.Site.cs:231.

(se1_1oninvokeex.PNG)
hits InvokeMethod(...):177
and continues with Marshal.GetObjectForNativeVariant(...)

(se1_ondisposeex.PNG)
step-in next stops at CoTaskMemBlock.cs - Dispose():85
NOTICE the exception in the Locals Window writes: Exception HRESULT 0x80020101

(se1_errout.PNG + se1_errout_det.PNG)
last significant break seems to be here, where the exception catched before is being thrown.


when the 2nd script engine finishes all user script and receives the Interrupt() call, things go the same except that the Exception in the Locals Window (se2_2ondisposeex.PNG) now writes "Cannot access a disposed object..."

further it continues and throws a TargetInvocationException with the "Cannot access a disposed object" inside as inner exception.

the only difference I could catch here is that omitting the Dispose() call on the script engines produces all times a HRESULT 0x80020101 Exception as soon as CoTaskMemBlock.cs - Dispose():86 is hit.

but by having the Dispose() calls, all scripts engines created afterwards will produce a "Cannot access a disposed object".

one more to note: the object which is being noted as disposed is a: Microsoft.ClearScript.Windows.VBScriptEngine' object. the screenshots: se2_1oninvokeex.PNG, se2_2ondisposeex.PNG just suck in showing it.

I tried to step trough into any line inside the clearscript implementation where the scriptengine.IsDisposed prop was set to true, but no luck. I could not find any context where the scriptengine was marked as IsDisposed=true before the exception "Cannot access a disposed object" was thrown.

anyways, my quick fix so far is a simple exception check similar to:
```
...
catch (Exception e) {
if !(myFlag.IsScriptFinished && e.InnerException != null && e.InnerException.Message.Contains("Cannot access a disposed object."))
throw e;
}
...
```

much appreciate any help. thanks





Comments: Hi eichti, It's great to hear that you found a solution, but as you said, since you can catch `ScriptInterruptedException` at any level of recursion, we don't believe that an API change is warranted. Also, it seems like your change could break callers that don't expect `default(T)` return values, or might misinterpret such values as valid results of script execution. Any objection to us closing this issue as "By Design"? Thanks!

Commented Unassigned: Cannot access a disposed object Error [114]

0
0
I get a weird "Cannot access a disposed object." error which I cant track down for its evil root.

Im stuck in not finding the cause and out of ideas.
its going to be difficult to explain, but basically I have 2 VBScript Engines instances running the same code in a sequential, non-parallel order. like:

```
var engine1 = new VBScriptEngine();
engine1.Execute(..);
engine1.Execute(..);
try {
engine1.Execute("engine1.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine1.Dispose();
engine1 = null;

var engine2 = new VBScriptEngine();
engine2.Execute(..);
engine2.Execute(..);
try {
engine2.Execute("engine2.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine2.Dispose();
engine2 = null;

```

If I dont call the Dispose() method after an engine finishes its job with a final Interrupt() call inside a loaded Script Document, everything is doing fine.

but on calling the Dispose() method on the 1st VBScript Engine after it finishes all tasks and stops with an Interrupt() call, the 2nd VBScript Engine still makes it to end of all its user script including the final Interrupt() call from within a Script document, but than somehow hits an "Cannot access a disposed object" Error after the engine successfully catches the Interrupt Exception.

I ve attached some screenshots where I think they might be better to further analyze the issue.

in addition some short descriptions to the attached images:

(se_all_intrptex.PNG)
1st script engine runs all script code, finishes and finally calls Interrupt() inside a script document, hitting the breakpoint in WindowsScriptEngine.Site.cs:231.

(se1_1oninvokeex.PNG)
hits InvokeMethod(...):177
and continues with Marshal.GetObjectForNativeVariant(...)

(se1_ondisposeex.PNG)
step-in next stops at CoTaskMemBlock.cs - Dispose():85
NOTICE the exception in the Locals Window writes: Exception HRESULT 0x80020101

(se1_errout.PNG + se1_errout_det.PNG)
last significant break seems to be here, where the exception catched before is being thrown.


when the 2nd script engine finishes all user script and receives the Interrupt() call, things go the same except that the Exception in the Locals Window (se2_2ondisposeex.PNG) now writes "Cannot access a disposed object..."

further it continues and throws a TargetInvocationException with the "Cannot access a disposed object" inside as inner exception.

the only difference I could catch here is that omitting the Dispose() call on the script engines produces all times a HRESULT 0x80020101 Exception as soon as CoTaskMemBlock.cs - Dispose():86 is hit.

but by having the Dispose() calls, all scripts engines created afterwards will produce a "Cannot access a disposed object".

one more to note: the object which is being noted as disposed is a: Microsoft.ClearScript.Windows.VBScriptEngine' object. the screenshots: se2_1oninvokeex.PNG, se2_2ondisposeex.PNG just suck in showing it.

I tried to step trough into any line inside the clearscript implementation where the scriptengine.IsDisposed prop was set to true, but no luck. I could not find any context where the scriptengine was marked as IsDisposed=true before the exception "Cannot access a disposed object" was thrown.

anyways, my quick fix so far is a simple exception check similar to:
```
...
catch (Exception e) {
if !(myFlag.IsScriptFinished && e.InnerException != null && e.InnerException.Message.Contains("Cannot access a disposed object."))
throw e;
}
...
```

much appreciate any help. thanks





Comments: yes that default(T) will much probably move the problem just somewhere else to be discovered yet. no, thanks. I may post again if I find anything significant to this issue. cheers

Commented Unassigned: Exception when creating Dates in V8ScriptEngine [113]

0
0
Hello,

I'm trying to create/parse date from a JS evaluate and return them as strings back into c# code as such:

```
using (var engine = new V8ScriptEngine())
{
resultEval = engine.Evaluate(expression);
}
```

where my `expression` is

`new Date()`

and it return an "Microsoft.ClearScript.V8.V8ScriptItem" object with an "UnderlyingSystemType" saying:

'((Microsoft.ClearScript.ScriptItem)resultEval).UnderlyingSystemType' threw an exception of type 'System.NotImplementedException'

Now, I feel like this *should* work, but it's not. Any ideas? I don't think anything went wrong during the build/reference process. Other JS libraries such as Math work flawlessly.

Also, this is only an issue when trying to create a `new` date. Calling `Date()` works, but it only displays today's date.
Comments: Hello, Thanks a lot for the help. > Now, when a Date or any other script object is returned to the host, ClearScript wraps it in a dynamic proxy that provides full access to the script object. This was the missing piece. Now, my code works: ``` dynamic scriptVal = engine.Evaluate(expression); //Cannot directly check for V8ScriptItem type because it is protected. if (scriptVal.GetType().FullName == "Microsoft.ClearScript.V8.V8ScriptItem") { DateTime tempDate; if(DateTime.TryParse(scriptVal.toISOString(), out tempDate)) { resultEval = tempDate; } else { resultEval = ""; } } ``` But I still have two questions: 1) I can't seem to use V8ScriptItem for type-checking because it is protected. Is this intended? I found the workaround of using the GetType().FullName to accomplish what I want 2) As you can see, right now I'm checking to see if it's a V8ScriptItem in order to try to parse and extract the date. To explain my intent. I want the user to be able to return `strings`, `dates` and `numeric` datatypes without having to specify a specific variable (such as jsNow in your example) note: This is why I think `Evaluate` seems more appropriate than `Execute` based on my tests. e.g. their expression (js) could be: ``` if (true){ Math.floor(2.345); } else{ Math.floor(3.456); } ``` result: 2 ``` new Date("March 21, 2016") ``` result: 2016-03-21T00:00:00Z ``` "hello" ``` result: "hello" I guess my question is, with that intent in mind, are there other scenarios where the ScriptEngine returns a V8ScriptItem that isn't a js Date, that I should take in consideration?

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
Hi,

Did you try putting a breakpoint to the "Console.WriteLine" line?
debugger;
var connect1 = main.SizeChanged.connect(function (sender, e) {
    Console.WriteLine("SizeChanged");
});
If you have only a "debugger;" statement at the first line and continue execution after stopping there, it works fine.

But if you put a breakpoint at that line and resize the form, the application hangs as soon as it hits the breakpoint.

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
Yes, we did set a breakpoint on that line, and yes, the application stops when it hits it, but that's expected, right? The breakpoint pauses execution and gives control to the debugger. Or are you saying that the application can't resume execution after it hits the breakpoint?

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
I've finally found the cause of the problem.

I host a chromium embedded browser (CefSharp) inside my application to integrate the debugger inside the application.

When a UI event which is bound to a script function is triggered and if there is a breakpoint in that function, the UI of the application freezes until the execution is resumed in the debugger.

Since the debugger interface is IN MY APPLICATON, I do not have the chance to resume the script because my UI is frozen and this gives me a frozen application.

When I run the debugger interface in an external Chrome instance, the Winforms application is frozen again when the breakpoint is hit but since I can click the resume button in the external interface I can unfreeze the app.

Can you imagine of a coding trick to overcome this problem?

As I wrote before I have the following "calling a delegate function in a new thread" option but this makes the code complicated and hard to maintain.
        public delegate void FormEvent(string eventName, object sender, EventArgs e);
        private FormEvent callbacks;

        public void RegisterToFormEvents(FormEvent eventHandler)
        {
            callbacks += eventHandler;
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
                new Thread(() =>
                {
                    if (callbacks != null)
                        callbacks("Resize", sender, e);
                }).Start();           
        }

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
Hi again,

That sounds like a very interesting application!

Have you considered running your debugger in a separate UI thread? Windows Forms applications can have any number of UI threads. Lots of relevant information is available on MSDN and StackOverflow.

Good luck!

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
Thanks for your quick response and this great library.

Commented Unassigned: Exception when creating Dates in V8ScriptEngine [113]

0
0
Hello,

I'm trying to create/parse date from a JS evaluate and return them as strings back into c# code as such:

```
using (var engine = new V8ScriptEngine())
{
resultEval = engine.Evaluate(expression);
}
```

where my `expression` is

`new Date()`

and it return an "Microsoft.ClearScript.V8.V8ScriptItem" object with an "UnderlyingSystemType" saying:

'((Microsoft.ClearScript.ScriptItem)resultEval).UnderlyingSystemType' threw an exception of type 'System.NotImplementedException'

Now, I feel like this *should* work, but it's not. Any ideas? I don't think anything went wrong during the build/reference process. Other JS libraries such as Math work flawlessly.

Also, this is only an issue when trying to create a `new` date. Calling `Date()` works, but it only displays today's date.
Comments: Hi again, ​​ >I can't seem to use V8ScriptItem for type-checking because it is protected. Is this intended? I found the workaround of using the GetType().FullName to accomplish what I want ​ Right; ClearScript should provide a better way to determine whether something is a script object. Your technique works but is unsupported. You could type-check against [`DynamicObject`](https://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject(v=vs.110).aspx), but host objects can be derived from that class as well. Unfortunately we don't have a better answer at this time. ​ >I guess my question is, with that intent in mind, are there other scenarios where the ScriptEngine returns a V8ScriptItem that isn't a js Date, that I should take in consideration? ​ Yes; a JavaScript function or expression can return any object it can access or construct. ClearScript converts simple values to their .NET equivalents (strings, bools, numbers, `null`, `undefined`, `void`), but all other JavaScript objects (dates, functions, arrays, object literals, etc.) are returned to the host as dynamic objects. Script code can also return any .NET objects you've exposed or passed to the script engine. .NET provides various means of determining an object's type. You can use reflection, try casting to a special type such as `DynamicObject` or [`IConvertible`](https://msdn.microsoft.com/en-us/library/system.iconvertible(v=vs.110).aspx), use [`Type.GetTypeCode`](https://msdn.microsoft.com/en-us/library/system.type.gettypecode(v=vs.110).aspx), etc. And if you know you're dealing with a JavaScript object, you can use language-specific techniques such as `obj.constructor.name`. Good luck!

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
I wrote two magical functions to handle my problem. I want to share it so that other users can benefit, too.

I added a host object referring to my Form object to the engine.
            engine.AddHostObject("main", this);
I added two public functions to the Form class:
        public EventHandler AddEventHandler(object obj, string eventName, object callback) {
            var eventInfo = obj.GetType().GetEvent(eventName);
            if (eventInfo != null)
            {
                Assembly asm = typeof(V8ScriptEngine).Assembly;
                Type asmType = asm.GetType("Microsoft.ClearScript.DelegateFactory");
                MethodInfo mi = asmType.GetMethod("CreateDelegate", new[] { typeof(ScriptEngine), typeof(object), typeof(Type) }); 
                object[] parameters = { engine, callback, eventInfo.EventHandlerType };
                Delegate scriptHandler = (Delegate)mi.Invoke(null, parameters);

                EventHandler handler = delegate (object sender, EventArgs e) {
                    Console.WriteLine("Event triggered: " + eventInfo.Name);
                    new Thread(() =>
                    {
                        object[] args = new object[] { sender, e };
                        scriptHandler.DynamicInvoke(args);
                    }).Start();
                };

                eventInfo.AddEventHandler(obj, handler);
                return handler;
            }
            return null;
        }

        public bool RemoveEventHandler(object obj, string eventName, EventHandler handler)
        {
            var eventInfo = obj.GetType().GetEvent(eventName);
            if (eventInfo != null)
            {
                eventInfo.RemoveEventHandler(obj, handler);
                return true;
            }
            return false;
        }
What solves my problem is calling the callback script in a new Thread.

This avoids the application from hanging when it hits a breakpoint in the callback. (Remember that my debugger is hosted in a web browser inside my application)

And this is how I register to the "Resize" event of the form in the script:
var handler = main.AddEventHandler(main, "Resize", function (sender, e) {
    Console.WriteLine("Resize triggered inside script");
    main.RemoveEventHandler(main, "Resize", handler); //unregister
});
The only restriction in this solution is that I can only register events whose method parameters match with the EventHandler delegate.

I would be happy to your feedbacks!

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
Hi ahmetuzun,

Thanks for posting your solution! Here's an alternative that uses only public APIs and supports all events that follow the standard pattern:
publicstaticclass EventSourceExtensions {
    publicstatic EventConnection<T> connectAsync<T>(this EventSource<T> source, object callback) {
        return source.connect(new EventHandler((sender, args) => {
            ThreadPool.QueueUserWorkItem(_ => ((dynamic)callback)(sender, args));
        }));
    }
}
And then:
engine.AddHostType(typeof(Console));
engine.AddHostType(typeof(EventSourceExtensions));
engine.Execute(@"
    var connect1 = main.SizeChanged.connectAsync(function (sender, e) {
        Console.WriteLine('SizeChanged');
    });
    var connect2 = main.MouseClick.connectAsync(function (sender, e) {
        Console.WriteLine('MouseClick({0}, {1})', e.X, e.Y);
    });
");
Cheers!

New Post: Debugging hangs if an event handler for a UI element is set and event handler gets executed (V8)

0
0
That's a perfect solution.

Thank you very much for your help.

Closed Unassigned: Cannot access a disposed object Error [114]

0
0
I get a weird "Cannot access a disposed object." error which I cant track down for its evil root.

Im stuck in not finding the cause and out of ideas.
its going to be difficult to explain, but basically I have 2 VBScript Engines instances running the same code in a sequential, non-parallel order. like:

```
var engine1 = new VBScriptEngine();
engine1.Execute(..);
engine1.Execute(..);
try {
engine1.Execute("engine1.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine1.Dispose();
engine1 = null;

var engine2 = new VBScriptEngine();
engine2.Execute(..);
engine2.Execute(..);
try {
engine2.Execute("engine2.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine2.Dispose();
engine2 = null;

```

If I dont call the Dispose() method after an engine finishes its job with a final Interrupt() call inside a loaded Script Document, everything is doing fine.

but on calling the Dispose() method on the 1st VBScript Engine after it finishes all tasks and stops with an Interrupt() call, the 2nd VBScript Engine still makes it to end of all its user script including the final Interrupt() call from within a Script document, but than somehow hits an "Cannot access a disposed object" Error after the engine successfully catches the Interrupt Exception.

I ve attached some screenshots where I think they might be better to further analyze the issue.

in addition some short descriptions to the attached images:

(se_all_intrptex.PNG)
1st script engine runs all script code, finishes and finally calls Interrupt() inside a script document, hitting the breakpoint in WindowsScriptEngine.Site.cs:231.

(se1_1oninvokeex.PNG)
hits InvokeMethod(...):177
and continues with Marshal.GetObjectForNativeVariant(...)

(se1_ondisposeex.PNG)
step-in next stops at CoTaskMemBlock.cs - Dispose():85
NOTICE the exception in the Locals Window writes: Exception HRESULT 0x80020101

(se1_errout.PNG + se1_errout_det.PNG)
last significant break seems to be here, where the exception catched before is being thrown.


when the 2nd script engine finishes all user script and receives the Interrupt() call, things go the same except that the Exception in the Locals Window (se2_2ondisposeex.PNG) now writes "Cannot access a disposed object..."

further it continues and throws a TargetInvocationException with the "Cannot access a disposed object" inside as inner exception.

the only difference I could catch here is that omitting the Dispose() call on the script engines produces all times a HRESULT 0x80020101 Exception as soon as CoTaskMemBlock.cs - Dispose():86 is hit.

but by having the Dispose() calls, all scripts engines created afterwards will produce a "Cannot access a disposed object".

one more to note: the object which is being noted as disposed is a: Microsoft.ClearScript.Windows.VBScriptEngine' object. the screenshots: se2_1oninvokeex.PNG, se2_2ondisposeex.PNG just suck in showing it.

I tried to step trough into any line inside the clearscript implementation where the scriptengine.IsDisposed prop was set to true, but no luck. I could not find any context where the scriptengine was marked as IsDisposed=true before the exception "Cannot access a disposed object" was thrown.

anyways, my quick fix so far is a simple exception check similar to:
```
...
catch (Exception e) {
if !(myFlag.IsScriptFinished && e.InnerException != null && e.InnerException.Message.Contains("Cannot access a disposed object."))
throw e;
}
...
```

much appreciate any help. thanks





Edited Issue: Cannot access a disposed object Error [114]

0
0
I get a weird "Cannot access a disposed object." error which I cant track down for its evil root.

Im stuck in not finding the cause and out of ideas.
its going to be difficult to explain, but basically I have 2 VBScript Engines instances running the same code in a sequential, non-parallel order. like:

```
var engine1 = new VBScriptEngine();
engine1.Execute(..);
engine1.Execute(..);
try {
engine1.Execute("engine1.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine1.Dispose();
engine1 = null;

var engine2 = new VBScriptEngine();
engine2.Execute(..);
engine2.Execute(..);
try {
engine2.Execute("engine2.Interrupt()");
} catch (Exception e) {
if (!(e is ScriptInterruptedException || e?.InnerException is ScriptInterruptedException))
throw e;
}
engine2.Dispose();
engine2 = null;

```

If I dont call the Dispose() method after an engine finishes its job with a final Interrupt() call inside a loaded Script Document, everything is doing fine.

but on calling the Dispose() method on the 1st VBScript Engine after it finishes all tasks and stops with an Interrupt() call, the 2nd VBScript Engine still makes it to end of all its user script including the final Interrupt() call from within a Script document, but than somehow hits an "Cannot access a disposed object" Error after the engine successfully catches the Interrupt Exception.

I ve attached some screenshots where I think they might be better to further analyze the issue.

in addition some short descriptions to the attached images:

(se_all_intrptex.PNG)
1st script engine runs all script code, finishes and finally calls Interrupt() inside a script document, hitting the breakpoint in WindowsScriptEngine.Site.cs:231.

(se1_1oninvokeex.PNG)
hits InvokeMethod(...):177
and continues with Marshal.GetObjectForNativeVariant(...)

(se1_ondisposeex.PNG)
step-in next stops at CoTaskMemBlock.cs - Dispose():85
NOTICE the exception in the Locals Window writes: Exception HRESULT 0x80020101

(se1_errout.PNG + se1_errout_det.PNG)
last significant break seems to be here, where the exception catched before is being thrown.


when the 2nd script engine finishes all user script and receives the Interrupt() call, things go the same except that the Exception in the Locals Window (se2_2ondisposeex.PNG) now writes "Cannot access a disposed object..."

further it continues and throws a TargetInvocationException with the "Cannot access a disposed object" inside as inner exception.

the only difference I could catch here is that omitting the Dispose() call on the script engines produces all times a HRESULT 0x80020101 Exception as soon as CoTaskMemBlock.cs - Dispose():86 is hit.

but by having the Dispose() calls, all scripts engines created afterwards will produce a "Cannot access a disposed object".

one more to note: the object which is being noted as disposed is a: Microsoft.ClearScript.Windows.VBScriptEngine' object. the screenshots: se2_1oninvokeex.PNG, se2_2ondisposeex.PNG just suck in showing it.

I tried to step trough into any line inside the clearscript implementation where the scriptengine.IsDisposed prop was set to true, but no luck. I could not find any context where the scriptengine was marked as IsDisposed=true before the exception "Cannot access a disposed object" was thrown.

anyways, my quick fix so far is a simple exception check similar to:
```
...
catch (Exception e) {
if !(myFlag.IsScriptFinished && e.InnerException != null && e.InnerException.Message.Contains("Cannot access a disposed object."))
throw e;
}
...
```

much appreciate any help. thanks





Commented Unassigned: Exception when creating Dates in V8ScriptEngine [113]

0
0
Hello,

I'm trying to create/parse date from a JS evaluate and return them as strings back into c# code as such:

```
using (var engine = new V8ScriptEngine())
{
resultEval = engine.Evaluate(expression);
}
```

where my `expression` is

`new Date()`

and it return an "Microsoft.ClearScript.V8.V8ScriptItem" object with an "UnderlyingSystemType" saying:

'((Microsoft.ClearScript.ScriptItem)resultEval).UnderlyingSystemType' threw an exception of type 'System.NotImplementedException'

Now, I feel like this *should* work, but it's not. Any ideas? I don't think anything went wrong during the build/reference process. Other JS libraries such as Math work flawlessly.

Also, this is only an issue when trying to create a `new` date. Calling `Date()` works, but it only displays today's date.
Comments: The next ClearScript release will provide a simple way to determine whether something is a script object.
Viewing all 2297 articles
Browse latest View live


Latest Images