public JavaScriptValue RunScript(string script, string sourceURL = "")
        {
            JavaScriptValue result;

            try
            {
                JavaScriptErrorCode errorCode = Native.JsRunScript(script, currentSourceContext++, sourceURL, out result);

                if (errorCode != JavaScriptErrorCode.NoError)
                {
                    string errorMessage = string.Format("Failed to run script with error [{0}]", errorCode);

                    System.Diagnostics.Debug.WriteLine(errorMessage);

                    throw new Exception(errorMessage);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("An exception occurred while executing script with error [{0}]", ex.Message);

                throw;
            }

            return(result);
        }
        private JavaScriptRuntime CreateRuntime(JavaScriptRuntimeAttributes attributes)
        {
            JavaScriptRuntime runtime;

            try
            {
                // Create a runtime.
                JavaScriptErrorCode errorCode = Native.JsCreateRuntime(attributes, null, out runtime);

                if (errorCode != JavaScriptErrorCode.NoError)
                {
                    string errorMessage = string.Format("Failed to create javascript runtime with error [{0}]", errorCode);

                    System.Diagnostics.Debug.WriteLine(errorMessage);

                    throw new Exception(errorMessage);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("An exception occurred when creating the javascript runtime with error [{0}]", ex.Message);

                throw;
            }

            return(runtime);
        }
        private void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                try
                {
                    // Reset JavaScriptContext
                    JavaScriptErrorCode errorCode = Native.JsSetCurrentContext(JavaScriptContext.Invalid);

                    if (errorCode != JavaScriptErrorCode.NoError)
                    {
                        System.Diagnostics.Debug.WriteLine("Failed to reset JavaScriptContext with error [{0}]", errorCode);
                    }

                    // Dispose runtime
                    errorCode = Native.JsDisposeRuntime(runtime);

                    if (errorCode != JavaScriptErrorCode.NoError)
                    {
                        System.Diagnostics.Debug.WriteLine("Failed to dispose javascript runtime with error [{0}]", errorCode);
                    }

                    disposed = true;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("An exception occurred when disposing the JavaScriptEngine with error [{0}]", ex.Message);
                }
            }
        }
Example #4
0
        /// <summary>
        ///     Parse the source for an ES module
        /// </summary>
        /// <remarks>
        ///     This is basically ParseModule operation in ES6 spec. It is slightly different in that:
        ///     a) The ModuleRecord was initialized earlier, and passed in as an argument.
        ///     b) This includes a check to see if the module being Parsed is the last module in the
        /// dependency tree. If it is it automatically triggers Module Instantiation.
        /// </remarks>
        /// <param name="script">The source script to be parsed, but not executed in this code.</param>
        /// <param name="sourceContext">A cookie identifying the script that can be used by debuggable script contexts.</param>
        /// <returns>
        ///     The code <c>JsNoError</c> if the operation succeeded, a failure code otherwise.
        /// </returns>
        public void ParseSource(
            string script,
            JavaScriptSourceContext sourceContext
            )
        {
            byte[]              scriptBuffer = Encoding.UTF8.GetBytes(script);
            uint                scriptLength = (uint)scriptBuffer.Length;
            JavaScriptValue     exceptionValue;
            JavaScriptErrorCode errorCode = Native.JsParseModuleSource(
                this,
                sourceContext,
                scriptBuffer,
                scriptLength,
                JavaScriptParseModuleSourceFlags.JsParseModuleSourceFlags_DataIsUTF8,
                out exceptionValue
                );

            if (errorCode != JavaScriptErrorCode.NoError)
            {
                if (exceptionValue.IsValid)
                {
                    JavaScriptContext.SetException(exceptionValue);
                }
                Native.ThrowIfError(errorCode);
            }
        }
Example #5
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptException" /> class.
 /// </summary>
 /// <param name="info">The serialization info.</param>
 /// <param name="context">The streaming context.</param>
 protected JavaScriptException(string message, Exception innerException) :
     base(message, innerException)
 {
     if (message != null)
     {
         code = (JavaScriptErrorCode) HResult;
     }
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptException"/> class. 
 /// </summary>
 /// <param name="info">The serialization info.</param>
 /// <param name="context">The streaming context.</param>
 protected JavaScriptException(SerializationInfo info, StreamingContext context) :
     base(info, context)
 {
     if (info != null)
     {
         code = (JavaScriptErrorCode) info.GetUInt32("code");
     }
 }
Example #7
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptException"/> class.
 /// </summary>
 /// <param name="info">The serialization info.</param>
 /// <param name="context">The streaming context.</param>
 protected JavaScriptException(string message, Exception innerException) :
     base(message, innerException)
 {
     if (message != null)
     {
         code = (JavaScriptErrorCode)base.HResult;
     }
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptException"/> class.
 /// </summary>
 /// <param name="info">The serialization info.</param>
 /// <param name="context">The streaming context.</param>
 protected JavaScriptException(SerializationInfo info, StreamingContext context) :
     base(info, context)
 {
     if (info != null)
     {
         code = (JavaScriptErrorCode)info.GetUInt32("code");
     }
 }
Example #9
0
 internal static void ThrowIfError(this JavaScriptErrorCode code)
 {
     if (JavaScriptErrorCode.NoError != code)
     {
         var args = new ChakraExceptionArgs(code);
         throw new Exception <ChakraExceptionArgs>(args);
     }
 }
        public string ConvertValueToString(JavaScriptValue value)
        {
            string result = null;

            try
            {
                // Convert your script result to String in JavaScript; redundant if your script returns a String
                JavaScriptValue resultJSString;

                JavaScriptErrorCode errorCode = Native.JsConvertValueToString(value, out resultJSString);

                if (errorCode != JavaScriptErrorCode.NoError)
                {
                    string errorMessage = string.Format("Failed to convert value to JsString with error [{0}]", errorCode);

                    System.Diagnostics.Debug.WriteLine(errorMessage);

                    throw new Exception(errorMessage);
                }

                // Project script result in JS back to C#.
                IntPtr  resultPtr;
                UIntPtr stringLength;

                errorCode = Native.JsStringToPointer(resultJSString, out resultPtr, out stringLength);

                if (errorCode != JavaScriptErrorCode.NoError)
                {
                    string errorMessage = string.Format("Failed to convert JsString to Pointer with error [{0}]", errorCode);

                    System.Diagnostics.Debug.WriteLine(errorMessage);

                    throw new Exception(errorMessage);
                }

                result = Marshal.PtrToStringUni(resultPtr);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("An exception occurred while converting JavaScriptValue with error [{0}]", ex.Message);

                throw;
            }

            return(result);
        }
        private JavaScriptContext CreateContext(JavaScriptRuntime runtime)
        {
            JavaScriptContext context;

            try
            {
                // Create an execution context.
                JavaScriptErrorCode errorCode = Native.JsCreateContext(runtime, out context);

                if (errorCode != JavaScriptErrorCode.NoError)
                {
                    string errorMessage = string.Format("Failed to create JavaScriptContext with error [{0}]", errorCode);

                    System.Diagnostics.Debug.WriteLine(errorMessage);

                    throw new Exception(errorMessage);
                }

                // Now set the execution context as being the current one on this thread.
                errorCode = Native.JsSetCurrentContext(context);

                if (errorCode != JavaScriptErrorCode.NoError)
                {
                    string errorMessage = string.Format("Failed to set current JavaScriptContext with error [{0}]", errorCode);

                    System.Diagnostics.Debug.WriteLine(errorMessage);

                    throw new Exception(errorMessage);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("An exception occurred when creating the javascript context with error [{0}]", ex.Message);

                throw;
            }

            return(context);
        }
        /// <summary>
        /// Throws if a native method returns an error code.
        /// </summary>
        /// <param name="error">The error.</param>
        internal static void ThrowIfError(JavaScriptErrorCode error)
        {
            if (error != JavaScriptErrorCode.NoError)
            {
                switch (error)
                {
                    case JavaScriptErrorCode.InvalidArgument:
                        throw new JavaScriptUsageException(error, "Invalid argument.");

                    case JavaScriptErrorCode.NullArgument:
                        throw new JavaScriptUsageException(error, "Null argument.");

                    case JavaScriptErrorCode.NoCurrentContext:
                        throw new JavaScriptUsageException(error, "No current context.");

                    case JavaScriptErrorCode.InExceptionState:
                        throw new JavaScriptUsageException(error, "Runtime is in exception state.");

                    case JavaScriptErrorCode.NotImplemented:
                        throw new JavaScriptUsageException(error, "Method is not implemented.");

                    case JavaScriptErrorCode.WrongThread:
                        throw new JavaScriptUsageException(error, "Runtime is active on another thread.");

                    case JavaScriptErrorCode.RuntimeInUse:
                        throw new JavaScriptUsageException(error, "Runtime is in use.");

                    case JavaScriptErrorCode.BadSerializedScript:
                        throw new JavaScriptUsageException(error, "Bad serialized script.");

                    case JavaScriptErrorCode.InDisabledState:
                        throw new JavaScriptUsageException(error, "Runtime is disabled.");

                    case JavaScriptErrorCode.CannotDisableExecution:
                        throw new JavaScriptUsageException(error, "Cannot disable execution.");

                    case JavaScriptErrorCode.AlreadyDebuggingContext:
                        throw new JavaScriptUsageException(error, "Context is already in debug mode.");

                    case JavaScriptErrorCode.HeapEnumInProgress:
                        throw new JavaScriptUsageException(error, "Heap enumeration is in progress.");

                    case JavaScriptErrorCode.ArgumentNotObject:
                        throw new JavaScriptUsageException(error, "Argument is not an object.");

                    case JavaScriptErrorCode.InProfileCallback:
                        throw new JavaScriptUsageException(error, "In a profile callback.");

                    case JavaScriptErrorCode.InThreadServiceCallback:
                        throw new JavaScriptUsageException(error, "In a thread service callback.");

                    case JavaScriptErrorCode.CannotSerializeDebugScript:
                        throw new JavaScriptUsageException(error, "Cannot serialize a debug script.");

                    case JavaScriptErrorCode.AlreadyProfilingContext:
                        throw new JavaScriptUsageException(error, "Already profiling this context.");

                    case JavaScriptErrorCode.IdleNotEnabled:
                        throw new JavaScriptUsageException(error, "Idle is not enabled.");

                    case JavaScriptErrorCode.OutOfMemory:
                        throw new JavaScriptEngineException(error, "Out of memory.");

                    case JavaScriptErrorCode.ScriptException:
                        {
                            JavaScriptValue errorObject;
                            JavaScriptErrorCode innerError = JsGetAndClearException(out errorObject);

                            if (innerError != JavaScriptErrorCode.NoError)
                            {
                                throw new JavaScriptFatalException(innerError);
                            }

                            throw new JavaScriptScriptException(error, errorObject, "Script threw an exception.");
                        }

                    case JavaScriptErrorCode.ScriptCompile:
                        {
                            JavaScriptValue errorObject;
                            JavaScriptErrorCode innerError = JsGetAndClearException(out errorObject);

                            if (innerError != JavaScriptErrorCode.NoError)
                            {
                                throw new JavaScriptFatalException(innerError);
                            }

                            throw new JavaScriptScriptException(error, errorObject, "Compile error.");
                        }

                    case JavaScriptErrorCode.ScriptTerminated:
                        throw new JavaScriptScriptException(error, JavaScriptValue.Invalid, "Script was terminated.");

                    case JavaScriptErrorCode.ScriptEvalDisabled:
                        throw new JavaScriptScriptException(error, JavaScriptValue.Invalid, "Eval of strings is disabled in this runtime.");

                    case JavaScriptErrorCode.Fatal:
                        throw new JavaScriptFatalException(error);

                    default:
                        throw new JavaScriptFatalException(error);
                }
            }
        }
Example #13
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptException"/> class.
 /// </summary>
 /// <param name="code">The error code returned.</param>
 /// <param name="message">The error message.</param>
 public JavaScriptException(JavaScriptErrorCode code, string message) :
     base(message)
 {
     this.code = code;
 }
Example #14
0
        /// <summary>
        /// Throws if a native method returns an error code.
        /// </summary>
        /// <param name="error">The error.</param>
        internal static void ThrowIfError(JavaScriptErrorCode error)
        {
            if (error != JavaScriptErrorCode.NoError)
            {
                switch (error)
                {
                case JavaScriptErrorCode.InvalidArgument:
                    throw new JavaScriptUsageException(error, "Invalid argument.");

                case JavaScriptErrorCode.NullArgument:
                    throw new JavaScriptUsageException(error, "Null argument.");

                case JavaScriptErrorCode.NoCurrentContext:
                    throw new JavaScriptUsageException(error, "No current context.");

                case JavaScriptErrorCode.InExceptionState:
                    throw new JavaScriptUsageException(error, "Runtime is in exception state.");

                case JavaScriptErrorCode.NotImplemented:
                    throw new JavaScriptUsageException(error, "Method is not implemented.");

                case JavaScriptErrorCode.WrongThread:
                    throw new JavaScriptUsageException(error, "Runtime is active on another thread.");

                case JavaScriptErrorCode.RuntimeInUse:
                    throw new JavaScriptUsageException(error, "Runtime is in use.");

                case JavaScriptErrorCode.BadSerializedScript:
                    throw new JavaScriptUsageException(error, "Bad serialized script.");

                case JavaScriptErrorCode.InDisabledState:
                    throw new JavaScriptUsageException(error, "Runtime is disabled.");

                case JavaScriptErrorCode.CannotDisableExecution:
                    throw new JavaScriptUsageException(error, "Cannot disable execution.");

                case JavaScriptErrorCode.AlreadyDebuggingContext:
                    throw new JavaScriptUsageException(error, "Context is already in debug mode.");

                case JavaScriptErrorCode.HeapEnumInProgress:
                    throw new JavaScriptUsageException(error, "Heap enumeration is in progress.");

                case JavaScriptErrorCode.ArgumentNotObject:
                    throw new JavaScriptUsageException(error, "Argument is not an object.");

                case JavaScriptErrorCode.InProfileCallback:
                    throw new JavaScriptUsageException(error, "In a profile callback.");

                case JavaScriptErrorCode.InThreadServiceCallback:
                    throw new JavaScriptUsageException(error, "In a thread service callback.");

                case JavaScriptErrorCode.CannotSerializeDebugScript:
                    throw new JavaScriptUsageException(error, "Cannot serialize a debug script.");

                case JavaScriptErrorCode.AlreadyProfilingContext:
                    throw new JavaScriptUsageException(error, "Already profiling this context.");

                case JavaScriptErrorCode.IdleNotEnabled:
                    throw new JavaScriptUsageException(error, "Idle is not enabled.");

                case JavaScriptErrorCode.OutOfMemory:
                    throw new JavaScriptEngineException(error, "Out of memory.");

                case JavaScriptErrorCode.ScriptException:
                {
                    JavaScriptValue     errorObject;
                    JavaScriptErrorCode innerError = JsGetAndClearException(out errorObject);

                    if (innerError != JavaScriptErrorCode.NoError)
                    {
                        throw new JavaScriptFatalException(innerError);
                    }

                    throw new JavaScriptScriptException(error, errorObject, "Script threw an exception.");
                }

                case JavaScriptErrorCode.ScriptCompile:
                {
                    JavaScriptValue     errorObject;
                    JavaScriptErrorCode innerError = JsGetAndClearException(out errorObject);

                    if (innerError != JavaScriptErrorCode.NoError)
                    {
                        throw new JavaScriptFatalException(innerError);
                    }

                    throw new JavaScriptScriptException(error, errorObject, "Compile error.");
                }

                case JavaScriptErrorCode.ScriptTerminated:
                    throw new JavaScriptScriptException(error, JavaScriptValue.Invalid, "Script was terminated.");

                case JavaScriptErrorCode.ScriptEvalDisabled:
                    throw new JavaScriptScriptException(error, JavaScriptValue.Invalid, "Eval of strings is disabled in this runtime.");

                case JavaScriptErrorCode.Fatal:
                    throw new JavaScriptFatalException(error);

                default:
                    throw new JavaScriptFatalException(error);
                }
            }
        }
Example #15
0
        static void ThrowError(JavaScriptErrorCode err, string location)
        {
            var             sb = new System.Text.StringBuilder();
            JavaScriptValue ex;
            bool            hasEx;

            Native.ThrowIfError(Native.JsHasException(out hasEx));
            object obj = null;

            if (hasEx)
            {
                Native.ThrowIfError(Native.JsGetAndClearException(out ex));
                IntPtr p = IntPtr.Zero;
                Native.JsGetExternalData(ex, out p);
                if (p != IntPtr.Zero)
                {
                    obj = GCHandle.FromIntPtr(p).Target;
                }
                if (err == JavaScriptErrorCode.ScriptCompile)
                {
                    var message = ex.GetIndexedProperty(JavaScriptValue.FromString("message")).ConvertToString().ToString();
                    var line    = ex.GetIndexedProperty(JavaScriptValue.FromString("line")).ConvertToString().ToString();
                    var column  = ex.GetIndexedProperty(JavaScriptValue.FromString("column")).ConvertToString().ToString();
                    sb.AppendFormat("{0}\n   at code ({3}:{1}:{2})", message, line, column, location);
                }
                else if (err == JavaScriptErrorCode.ScriptException)
                {
                    if (ex.ValueType == JavaScriptValueType.Error ||
                        ex.ValueType == JavaScriptValueType.Object)
                    {
                        var    messageobj   = ex.GetIndexedProperty(JavaScriptValue.FromString("message"));
                        IntPtr messageobjex = IntPtr.Zero;
                        Native.JsGetExternalData(messageobj, out messageobjex);
                        string message;
                        if (messageobjex != IntPtr.Zero)
                        {
                            obj = GCHandle.FromIntPtr(messageobjex).Target;
                            if (obj is Exception)
                            {
                                message = ((Exception)obj).Message;
                            }
                            else
                            {
                                message = obj.ToString();
                            }
                        }
                        else
                        {
                            message = messageobj.ConvertToString().ToString();
                        }
                        var stack = ex.GetIndexedProperty(JavaScriptValue.FromString("stack")).ConvertToString().ToString();
                        sb.AppendFormat("{0}\n{1}", message, stack);
                    }
                    else
                    {
                        sb.AppendFormat("{0}", ex.ConvertToString().ToString());
                    }
                }
                else if (ex.ValueType == JavaScriptValueType.Error ||
                         ex.ValueType == JavaScriptValueType.Object)
                {
                    Console.WriteLine("else error?");
                    var errorobj = ex.GetIndexedProperty(JavaScriptValue.FromString("message"));
                    p = IntPtr.Zero;
                    Native.JsGetExternalData(errorobj, out p);
                    if (p != IntPtr.Zero)
                    {
                        obj = GCHandle.FromIntPtr(p).Target;
                    }
                    if (obj != null)
                    {
                        sb.Append(System.Convert.ToString(obj));
                    }
                    else
                    {
                        sb.Append(errorobj.ConvertToString().ToString());
                    }
                }
                else
                {
                    sb.Append(ex.ConvertToString().ToString());
                }
            }
            else
            {
                sb.Append(err);
            }
            throw new ChakraSharpException(sb.ToString(), obj as Exception);
            //return sb.ToString();
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptScriptException"/> class.
 /// </summary>
 /// <param name="code">The error code returned.</param>
 /// <param name="error">The JavaScript error object.</param>
 /// <param name="message">The error message.</param>
 public JavaScriptScriptException(JavaScriptErrorCode code, JavaScriptValue error, string message) :
     base(code, message)
 {
     this.error = error;
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptScriptException"/> class.
 /// </summary>
 /// <param name="code">The error code returned.</param>
 /// <param name="error">The JavaScript error object.</param>
 public JavaScriptScriptException(JavaScriptErrorCode code, JavaScriptValue error) :
     this(code, error, "JavaScript Exception")
 {
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptUsageException"/> class. 
 /// </summary>
 /// <param name="code">The error code returned.</param>
 public JavaScriptUsageException(JavaScriptErrorCode code) :
     this(code, "A fatal exception has occurred in a JavaScript runtime")
 {
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptFatalException"/> class.
 /// </summary>
 /// <param name="code">The error code returned.</param>
 public JavaScriptFatalException(JavaScriptErrorCode code) :
     this(code, "A fatal exception has occurred in a JavaScript runtime")
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="JavaScriptScriptException"/> class.
 /// </summary>
 /// <param name="code">The error code returned.</param>
 /// <param name="error">The JavaScript error object.</param>
 /// <param name="message">The error message.</param>
 public JavaScriptScriptException(JavaScriptErrorCode code, JavaScriptValue error, string message)
     : base(code, message)
 {
     _error = error;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="JavaScriptScriptException"/> class.
 /// </summary>
 /// <param name="code">The error code returned.</param>
 /// <param name="error">The JavaScript error object.</param>
 public JavaScriptScriptException(JavaScriptErrorCode code, JavaScriptValue error)
     : this(code, error, "JavaScript Exception")
 {
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptFatalException"/> class.
 /// </summary>
 /// <param name="code">The error code returned.</param>
 /// <param name="message">The error message.</param>
 public JavaScriptFatalException(JavaScriptErrorCode code, string message) :
     base(code, message)
 {
 }
Example #23
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptException"/> class. 
 /// </summary>
 /// <param name="code">The error code returned.</param>
 /// <param name="message">The error message.</param>
 public JavaScriptException(JavaScriptErrorCode code, string message) :
     base(message)
 {
     this.ErrorCode = code;
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="JavaScriptUsageException"/> class. 
 /// </summary>
 /// <param name="code">The error code returned.</param>
 /// <param name="message">The error message.</param>
 public JavaScriptUsageException(JavaScriptErrorCode code, string message) :
     base(code, message)
 {
 }
Example #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChakraExceptionArgs"/> class.
 /// </summary>
 /// <param name="error">JavaScript runtime error to throw as exception.</param>
 public ChakraExceptionArgs(JavaScriptErrorCode error)
 {
     _error = error;
 }