예제 #1
0
        /// <summary>
        /// Adds the specified code to the scripting engine under the specified namespace.
        /// The code that is added will be available only under the namespace specified
        /// instead of in the global scope of the script. The script name will be used
        /// to provide more useful error information if an error occurs during the execution
        /// of the code that was added.
        /// </summary>
        /// <param name="code">The code to be added.</param>
        /// <param name="namespaceName">The name of the namespace to add the code to.</param>
        /// <param name="scriptName">The script name that the code came from.</param>
        /// <exception cref="ArgumentNullException">If code is null.</exception>
        /// <exception cref="ArgumentException">If code is blank.</exception>
        public void AddCode(string code, string namespaceName, string scriptName)
        {
            if (code == null)
            {
                throw new ArgumentNullException("code");
            }

            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentException("code parameter must contain code", "code");
            }

            if (namespaceName != null)
            {
                activeScript.AddNamedItem(namespaceName, ScriptItemFlags.CodeOnly | ScriptItemFlags.IsVisible);
            }

            try
            {
                /*
                 * In the event that the passed in script is not valid syntax
                 * an error will be thrown by the script engine. This will be
                 * handled by the OnScriptError event before the exception
                 * is thrown here so we need to set this variable to use
                 * in the OnScriptError block to figure out the script name
                 * since it won't have been added to the script list.
                 */
                scriptToParse = scriptName;

                EXCEPINFO exceptionInfo = new EXCEPINFO();

                ulong cookie = (ulong)scripts.Count;

                parser.ParseScriptText(
                    code: code,
                    itemName: namespaceName,
                    context: null,
                    delimiter: null,
                    sourceContext: cookie,
                    startingLineNumber: 1u,
                    flags: ScriptTextFlags.IsVisible,
                    pVarResult: IntPtr.Zero,
                    excepInfo: out exceptionInfo);

                ScriptInfo si = new ScriptInfo()
                {
                    Code       = code,
                    ScriptName = scriptName
                };

                scripts.Add(cookie, si);
            }
            finally
            {
                scriptToParse = null;
            }
        }