예제 #1
0
        /// <summary>
        /// Attempts to compile and load a C# script from the specified source code
        /// Depending upon settings, the code may be security verified before being loaded which may result in an exception being thrown.
        /// It is recommended that source code define only a single type however it is not a requirement.
        /// The reason for this is that the return type if <see cref="ScriptType"/> which represents a single type defenition which will return the first defined type if more than one type is defined.
        /// If you need to compile multiple files with dependencies then you should use <see cref="CompileAndLoadScriptSources(string[])"/>.
        /// </summary>
        /// <param name="source">The C# source code to compile</param>
        /// <returns>A <see cref="ScriptType"/> representing the main type in the compiled result.</returns>
        /// <exception cref="SecurityException">The code does not meet the security restrictions defined in the settings menu</exception>
        public ScriptType CompileAndLoadScriptSource(string source)
        {
            // Make sure the compiler is initialized
            CheckCompiler();

            // Convert to array
            string[] sources = { source };

            // Compile the code
            if (compilerService.CompileSources(sources, DynamicCSharp.Settings.assemblyReferences) == false)
            {
                compilerService.PrintErrors();
                return(null);
            }

            // Print any warnings
            if (compilerService.HasWarnings == true)
            {
                compilerService.PrintWarnings();
            }

            // Load the assembly - This will also security check the assembly
            ScriptAssembly assembly = LoadAssembly(compilerService.AssemblyData, compilerService.SymbolsData);

            // Check for assembly
            if (assembly == null)
            {
                return(null);
            }

            // Get the main type
            return(assembly.MainType);
        }