示例#1
0
 private void CompileTestCodeDom(string code)
 {
     try
     {
         OutputClass     selectedItem    = (OutputClass)this.cbCodeDom.SelectedItem;
         CodeDomProvider codeDomProvider = selectedItem.CodeDomProvider;
         CSharpSnippet   snippet         = new CSharpSnippet("\r\n    public string GenerateCode()\r\n    {\r\n        " + code + "\r\n\r\n        CodeGeneratorOptions codegenopt = new CodeGeneratorOptions();\r\n        codegenopt.BlankLinesBetweenMembers = true;\r\n\r\n        using (System.IO.StringWriter sw = new System.IO.StringWriter())\r\n        {\r\n            " + codeDomProvider.GetType().Name + " provider = new " + codeDomProvider.GetType().Name + "();\r\n\r\n            provider.GenerateCodeFromCompileUnit(_compileunit1, sw, codegenopt);\r\n\r\n            return sw.ToString();\r\n        }\r\n    }   \r\n");
         snippet.Namespaces.Add("System.CodeDom");
         snippet.Namespaces.Add("System.CodeDom.Compiler");
         snippet.Namespaces.Add(codeDomProvider.GetType().Namespace);
         Assembly assembly = codeDomProvider.GetType().Assembly;
         if (!assembly.GlobalAssemblyCache)
         {
             snippet.ReferencedAssemblies.Add(assembly.Location);
         }
         object[] args = new object[0];
         object   obj2 = snippet.Execute("GenerateCode", args);
         if (obj2 != null)
         {
             this.scintillaTestCodeDom.Text = obj2.ToString();
         }
     }
     catch (Exception exception)
     {
         new ExceptionDialog(exception, "Error Generating CodeDom").ShowDialog();
     }
 }
        private static int GetGeneratedColumnOffset(CodeDomProvider codeDomProvider)
        {
            object obj2 = null;

            if (_generatedColumnOffsetDictionary == null)
            {
                _generatedColumnOffsetDictionary = new ListDictionary();
            }
            else
            {
                obj2 = _generatedColumnOffsetDictionary[codeDomProvider.GetType()];
            }
            if (obj2 != null)
            {
                return((int)obj2);
            }
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace   namespace2  = new CodeNamespace("ASP");

            compileUnit.Namespaces.Add(namespace2);
            CodeTypeDeclaration declaration = new CodeTypeDeclaration("ColumnOffsetCalculator")
            {
                IsClass = true
            };

            namespace2.Types.Add(declaration);
            CodeMemberMethod method = new CodeMemberMethod {
                ReturnType = new CodeTypeReference(typeof(void)),
                Name       = "GenerateMethod"
            };

            declaration.Members.Add(method);
            CodeStatement statement = new CodeAssignStatement(new CodeVariableReferenceExpression("__o"), new CodeSnippetExpression("__dummyVar"));

            method.Statements.Add(statement);
            StringBuilder sb     = new StringBuilder();
            StringWriter  writer = new StringWriter(sb, CultureInfo.InvariantCulture);

            codeDomProvider.GenerateCodeFromCompileUnit(compileUnit, writer, null);
            StringReader reader = new StringReader(sb.ToString());
            string       str    = null;
            int          num    = 4;

            while ((str = reader.ReadLine()) != null)
            {
                int index = 0;
                index = str.TrimStart(new char[0]).IndexOf("__dummyVar", StringComparison.Ordinal);
                if (index != -1)
                {
                    num = (index - "__o".Length) + 1;
                }
            }
            _generatedColumnOffsetDictionary[codeDomProvider.GetType()] = num;
            return(num);
        }
示例#3
0
        public void Roundtrip_Extension()
        {
            CodeDomProvider provider  = GetProvider();
            string          ext       = provider.FileExtension;
            CodeDomProvider provider2 = CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(ext));

            Assert.Equal(provider.GetType(), provider2.GetType());
        }
示例#4
0
        /// <summary>
        /// Fixes the compiler path to get it run.
        /// </summary>
        private static void FixCompilerPath(CodeDomProvider provider)
        {
            FieldInfo memberInfo = provider.GetType().GetField("_compilerSettings", BindingFlags.Instance | BindingFlags.NonPublic);

            if (memberInfo != null)
            {
                object    settings = memberInfo.GetValue(provider);
                FieldInfo path     = settings.GetType().GetField("_compilerFullPath", BindingFlags.Instance | BindingFlags.NonPublic);
                path?.SetValue(settings, @"D:\bin\roslyn\csc.exe");
            }
        }
示例#5
0
        // TODO: Move compilation stuff elsewhere.
        // TODO: Consider IronPython support: http://www.ironpython.info/index.php/Using_Compiled_Python_Classes_from_.NET/CSharp_IP_2.6
        internal List <ExportedAssembly> GetAssemblies(string pathResolveRoot, DnaLibrary dnaLibrary)
        {
            List <ExportedAssembly> list = new List <ExportedAssembly>();
            // Dynamically compile this project to an in-memory assembly

            CodeDomProvider provider = GetProvider();

            if (provider == null)
            {
                return(list);
            }

            CompilerParameters cp = new CompilerParameters();
            bool isFsharp         = false;

            // TODO: Debug build ?
            // cp.IncludeDebugInformation = true;
            cp.GenerateExecutable = false;
            //cp.OutputAssembly = Name; // TODO: Keep track of built assembly for the project
            cp.GenerateInMemory      = true;
            cp.TreatWarningsAsErrors = false;

            // This is attempt to fix the bug reported on the group, where the add-in compilation fails if the add-in is put into c:\
            // It is caused by a quirk of the 'Path.GetDirectoryName' function when dealing with the path "c:\test.abc"
            // - it leaves the last DirectorySeparator in the path in this special case.
            // Thanks to Nemo for the great fix.
            //local variable to hold the quoted/unquoted version of the executing dirction
            string ProcessedExecutingDirectory = DnaLibrary.ExecutingDirectory;

            if (ProcessedExecutingDirectory.IndexOf(' ') != -1)
            {
                ProcessedExecutingDirectory = "\"" + ProcessedExecutingDirectory + "\"";
            }

            //set compiler command line vars as needed
            if (provider is Microsoft.VisualBasic.VBCodeProvider)
            {
                cp.CompilerOptions = " /libPath:" + ProcessedExecutingDirectory;
                if (DefaultImports)
                {
                    string importsList = "Microsoft.VisualBasic,System,System.Collections,System.Collections.Generic,System.Data,System.Diagnostics,ExcelDna.Integration";
                    if (Environment.Version.Major >= 4)
                    {
                        importsList += ",System.Linq,System.Xml.Linq";
                    }
                    cp.CompilerOptions += " /imports:" + importsList;
                }
            }
            else if (provider is Microsoft.CSharp.CSharpCodeProvider)
            {
                cp.CompilerOptions = " /lib:" + ProcessedExecutingDirectory;
            }
            else if (provider.GetType().FullName.ToLower().IndexOf(".jscript.") != -1)
            {
                cp.CompilerOptions = " /lib:" + ProcessedExecutingDirectory;
            }
            else if (provider.GetType().FullName == "Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider")
            {
                isFsharp           = true;
                cp.CompilerOptions = " --nologo -I " + ProcessedExecutingDirectory; // In F# 2.0, the --nologo is redundant - I leave it because it does no harm.

                // FSharp 2.0 compiler will target .NET 4 unless we do something to ensure .NET 2.0.
                // It seems adding an explicit reference to the .NET 2.0 version of mscorlib.dll is good enough.
                if (Environment.Version.Major < 4)
                {
                    // Explicitly add a reference to the mscorlib version from the currently running .NET version
                    string libPath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "mscorlib.dll");
                    cp.ReferencedAssemblies.Add(libPath);
                }
            }

            // TODO: Consider what to do if we can't resolve some of the Reference paths -- do we try to compile anyway, throw an exception, ...what?
            List <string> refPaths = GetReferencePaths(pathResolveRoot, provider);

            cp.ReferencedAssemblies.AddRange(refPaths.ToArray());

            List <string> sources = GetSources(pathResolveRoot);

            CompilerResults cr;

            try
            {
                cr = provider.CompileAssemblyFromSource(cp, sources.ToArray());
            }
            catch (Win32Exception wex)
            {
                if (isFsharp)
                {
                    Logger.DnaCompilation.Error("There was an error in loading the add-in " + DnaLibrary.CurrentLibraryName + " (" + DnaLibrary.XllPath + "):");
                    string fsBinPath = Environment.GetEnvironmentVariable("FSHARP_BIN");
                    string msg;
                    if (fsBinPath == null)
                    {
                        msg = "    Calling the F# compiler failed (\"" + wex.Message + "\").\r\n" +
                              "    Please check that the F# compiler is correctly installed.\r\n" +
                              "    This error can sometimes be fixed by creating an FSHARP_BIN environment variable.\r\n" +
                              "    Create an environment variable FSHARP_BIN with the full path to the directory containing \r\n" +
                              "    the F# compiler fsc.exe - for example \r\n" +
                              "        \"" + @"C:\Program Files (x86)\Microsoft SDKs\F#\3.0\Framework\v4.0\""";
                    }
                    else
                    {
                        msg = "    Calling the F# compiler failed (\"" + wex.Message + "\").\r\n" +
                              "    Please check that the F# compiler is correctly installed, and that the FSHARP_BIN environment variable is correct\r\n" +
                              "    (it currently points to " + fsBinPath + ").";
                    }
                    Logger.DnaCompilation.Error(msg);
                    return(list);
                }
                throw;
            }


            foreach (string path in tempAssemblyPaths)
            {
                File.Delete(path);
            }
            tempAssemblyPaths.Clear();


            if (cr.Errors.HasErrors)
            {
                Logger.DnaCompilation.Error("There was an error in loading the add-in " + DnaLibrary.CurrentLibraryName + " (" + DnaLibrary.XllPath + "):");
                Logger.DnaCompilation.Error("There were errors when compiling project: " + Name);
                foreach (CompilerError err in cr.Errors)
                {
                    Logger.DnaCompilation.Error("    " + err.ToString());
                }
                return(list);
            }

            // Success !!
            // Now add all the references
            // TODO: How to remove again??
            foreach (Reference r in References)
            {
                AssemblyReference.AddAssembly(r.Path);
            }

            // TODO: Create TypeLib for execution-time compiled assemblies.
            list.Add(new ExportedAssembly(cr.CompiledAssembly, ExplicitExports, ExplicitRegistration, ComServer, true, null, dnaLibrary));
            return(list);
        }
示例#6
0
        private static Assembly CompileCode(CodeDomProvider prov, bool v35, WXMLCodeDomGeneratorSettings settings,
                                            WXMLModel model, params CodeCompileUnit[] units)
        {
            WormCodeDomGenerator gen = new WormCodeDomGenerator(model, settings);
            CompilerResults      result;
            CompilerParameters   prms = new CompilerParameters
            {
                GenerateExecutable      = false,
                GenerateInMemory        = true,
                IncludeDebugInformation = false,
                TreatWarningsAsErrors   = false/*,
                                                * OutputAssembly = "testAssembly.dll"*/
            };

            prms.ReferencedAssemblies.Add("System.dll");
            prms.ReferencedAssemblies.Add("System.Data.dll");
            prms.ReferencedAssemblies.Add("System.XML.dll");
            if (v35)
            {
                prms.ReferencedAssemblies.Add("System.Core.dll");
            }
            if ((settings.GenerateMode.HasValue ? settings.GenerateMode.Value : model.GenerateMode) != GenerateModeEnum.EntityOnly)
            {
                //prms.ReferencedAssemblies.Add("CoreFramework.dll");
                prms.ReferencedAssemblies.Add("Worm.Orm.dll");
                if (model.LinqSettings != null && model.LinqSettings.Enable)
                {
                    prms.ReferencedAssemblies.Add("Worm.Linq.dll");
                }
            }

            prms.TempFiles.KeepFiles = true;

            CodeCompileUnit singleUnit = new CodeCompileUnit();

            if (settings.SingleFile.HasValue ? settings.SingleFile.Value : model.GenerateSingleFile)
            {
                singleUnit = gen.GetFullSingleUnit(typeof(Microsoft.VisualBasic.VBCodeProvider).IsAssignableFrom(prov.GetType()) ? LinqToCodedom.CodeDomGenerator.Language.VB : LinqToCodedom.CodeDomGenerator.Language.CSharp);
                singleUnit.Namespaces.Add(new CodeNamespace("System"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Data"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Data.Linq"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Linq"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Linq.Expressions"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Collections.Generic"));
                var l = new List <CodeCompileUnit>();
                l.Add(singleUnit);
                if (units != null)
                {
                    l.AddRange(units);
                    foreach (var item in units)
                    {
                        singleUnit.Namespaces.AddRange(item.Namespaces);
                    }
                }
                result = prov.CompileAssemblyFromDom(prms, l.ToArray());
            }
            else
            {
                Dictionary <string, CodeCompileFileUnit> dic =
                    gen.GetCompileUnits(typeof(Microsoft.VisualBasic.VBCodeProvider).IsAssignableFrom(prov.GetType()) ? LinqToCodedom.CodeDomGenerator.Language.VB : LinqToCodedom.CodeDomGenerator.Language.CSharp);

                foreach (CodeCompileFileUnit unit in dic.Values)
                {
                    singleUnit.Namespaces.AddRange(unit.Namespaces);
                }
                var l = new List <CodeCompileUnit>(dic.Values.OfType <CodeCompileUnit>());
                if (units != null)
                {
                    l.AddRange(units);
                    foreach (var item in units)
                    {
                        singleUnit.Namespaces.AddRange(item.Namespaces);
                    }
                }

                singleUnit.Namespaces.Add(new CodeNamespace("System"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Data"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Data.Linq"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Linq"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Linq.Expressions"));
                singleUnit.Namespaces.Add(new CodeNamespace("System.Collections.Generic"));

                result = prov.CompileAssemblyFromDom(prms, l.ToArray());
            }

            prov.GenerateCodeFromCompileUnit(singleUnit, Console.Out, new CodeGeneratorOptions());

            if (result.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError str in result.Errors)
                {
                    sb.AppendLine(str.ToString());
                }
                Assert.Fail(sb.ToString());
            }

            return(result.CompiledAssembly);
        }
示例#7
0
        internal static int GetGeneratedColumnOffset(CodeDomProvider codeDomProvider)
        {
            object o = null;

            if (_generatedColumnOffsetDictionary == null)
            {
                _generatedColumnOffsetDictionary = new ListDictionary();
            }
            else
            {
                o = _generatedColumnOffsetDictionary[codeDomProvider.GetType()];
            }

            if (o == null)
            {
                CodeCompileUnit ccu = new CodeCompileUnit();

                CodeNamespace cnamespace = new CodeNamespace("ASP");
                ccu.Namespaces.Add(cnamespace);

                CodeTypeDeclaration type = new CodeTypeDeclaration("ColumnOffsetCalculator");
                type.IsClass = true;
                cnamespace.Types.Add(type);

                CodeMemberMethod method = new CodeMemberMethod();
                method.ReturnType = new CodeTypeReference(typeof(void));
                method.Name       = "GenerateMethod";
                type.Members.Add(method);

                CodeStatement simpleAssignment = new CodeAssignStatement(
                    new CodeVariableReferenceExpression(BaseTemplateCodeDomTreeGenerator.tempObjectVariable),
                    new CodeSnippetExpression(_dummyVariable));
                method.Statements.Add(simpleAssignment);

                StringBuilder sb = new StringBuilder();
                StringWriter  w  = new StringWriter(sb, CultureInfo.InvariantCulture);

                codeDomProvider.GenerateCodeFromCompileUnit(ccu, w, null);

                StringReader reader = new StringReader(sb.ToString());
                String       line   = null;

                int offset = _defaultColumnOffset;

                while ((line = reader.ReadLine()) != null)
                {
                    int index = 0;
                    line = line.TrimStart();
                    if ((index = line.IndexOf(_dummyVariable, StringComparison.Ordinal)) != -1)
                    {
                        offset = index - BaseTemplateCodeDomTreeGenerator.tempObjectVariable.Length + 1;
                    }
                }

                // Save the offset per type.
                _generatedColumnOffsetDictionary[codeDomProvider.GetType()] = offset;

                return(offset);
            }

            return((int)o);
        }
示例#8
0
        private static void GenerateMultipleFilesOutput(string outputFolder, WXMLModel model,
                                                        CodeDomProvider codeDomProvider, bool separateFolder,
                                                        IEnumerable <string> skipEntities, IEnumerable <string> processEntities, bool testRun,
                                                        WormCodeDomGenerator gen)
        {
            List <string> errorList     = new List <string>();
            int           totalEntities = 0;
            int           totalFiles    = 0;

            foreach (EntityDefinition entity in model.OwnEntities)
            {
                //bool skip = false;
                //if (processEntities.Length != 0)
                //{
                //    skip = true;
                //    foreach (string processEntityId in processEntities)
                //    {
                //        if (processEntityId == entity.Identifier)
                //        {
                //            skip = false;
                //            break;
                //        }
                //    }
                //}
                //foreach (string skipEntityId in skipEntities)
                //{
                //    if (skipEntityId == entity.Identifier)
                //    {
                //        skip = true;
                //        break;
                //    }
                //}

                if (skipEntities.Contains(entity.Identifier))
                {
                    continue;
                }

                if (processEntities.Count() > 0 && !processEntities.Contains(entity.Identifier))
                {
                    continue;
                }

                string privateFolder;
                if (separateFolder)
                {
                    privateFolder = outputFolder + Path.DirectorySeparatorChar.ToString() + entity.Name + Path.DirectorySeparatorChar;
                }
                else
                {
                    privateFolder = outputFolder + Path.DirectorySeparatorChar.ToString();
                }

                var units = gen.GetEntityCompileUnits(entity.Identifier, typeof(VBCodeProvider).IsAssignableFrom(codeDomProvider.GetType()) ? LinqToCodedom.CodeDomGenerator.Language.VB : LinqToCodedom.CodeDomGenerator.Language.CSharp);

                Console.Write(".");

                if (!Directory.Exists(privateFolder))
                {
                    Directory.CreateDirectory(privateFolder);
                }

                foreach (var unit in units)
                {
                    Console.Write(".");
                    try
                    {
                        GenerateCode(codeDomProvider, unit, Path.GetFullPath(privateFolder + Path.DirectorySeparatorChar.ToString() + unit.Filename), testRun);
                        Console.Write(".");
                        totalFiles++;
                    }
                    catch (Exception exc)
                    {
                        Console.Write(".");
                        errorList.Add(
                            string.Format("Entity: {0}; file: {1}; message: {2}", entity.Identifier, unit.Filename, exc.Message));
                    }
                }
                totalEntities++;
            }

            try
            {
                var ctx = gen.GetLinqContextCompliteUnit(typeof(VBCodeProvider).IsAssignableFrom(codeDomProvider.GetType()) ? LinqToCodedom.CodeDomGenerator.Language.VB : LinqToCodedom.CodeDomGenerator.Language.CSharp);
                if (ctx != null)
                {
                    GenerateCode(codeDomProvider, ctx,
                                 Path.GetFullPath(
                                     outputFolder +
                                     Path.DirectorySeparatorChar.ToString() +
                                     ctx.Filename
                                     ), testRun);
                    Console.Write(".");
                    totalFiles++;
                }
            }
            catch (Exception exc)
            {
                Console.Write(".");
                errorList.Add(
                    string.Format("Linq context file failed to generate: {0}", exc.Message));
            }

            Console.WriteLine();

            Console.WriteLine("Result:");
            Console.WriteLine("\t {0} entities processed", totalEntities);
            Console.WriteLine("\t {0} files generated", totalFiles);
            Console.WriteLine("\t {0} errors encountered", errorList.Count);
            if (errorList.Count != 0)
            {
                Console.WriteLine("Errors:");
                foreach (string s in errorList)
                {
                    Console.WriteLine("\t" + s);
                    for (int i = 0; i < Console.WindowWidth; i++)
                    {
                        Console.Write("-");
                    }
                    Console.WriteLine();
                }
            }
        }
        /// <include file='doc\BaseCompiler.uex' path='docs/doc[@for="BaseCompiler.GetCompiledType"]/*' />
        /// <devdoc>
        ///
        /// </devdoc>
        protected Type GetCompiledType()
        {
            // Instantiate an ICompiler based on the language
            CodeDomProvider codeProvider = (CodeDomProvider)HttpRuntime.CreatePublicInstance(
                CompilerInfo.CompilerType);
            ICodeCompiler compiler = codeProvider.CreateCompiler();

            _generator = codeProvider.CreateGenerator();

            _stringResourceBuilder = new StringResourceBuilder();

            // Build the data tree that needs to be compiled
            BuildSourceDataTree();

            // Create the resource file if needed
            if (_stringResourceBuilder.HasStrings)
            {
                string resFileName = _compilParams.TempFiles.AddExtension("res");
                _stringResourceBuilder.CreateResourceFile(resFileName);
                CompilParams.Win32Resource = resFileName;
            }

            // Compile into an assembly
            CompilerResults results;

            try {
                results = codeProvider.CreateCompiler().CompileAssemblyFromDom(_compilParams, _sourceData);
            }
            catch (Exception e) {
                throw new HttpUnhandledException(HttpRuntime.FormatResourceString(SR.CompilationUnhandledException, codeProvider.GetType().FullName), e);
            }

            string fullTypeName = _sourceDataNamespace.Name + "." + _sourceDataClass.Name;

            ThrowIfCompilerErrors(results, codeProvider, _sourceData, null, null);

            // After the compilation, update the list of assembly dependencies to be what
            // the assembly actually needs.
            Parser.AssemblyDependencies = Util.GetReferencedAssembliesHashtable(
                results.CompiledAssembly);

            // Get the type from the assembly
            return(results.CompiledAssembly.GetType(fullTypeName, true /*throwOnFail*/));
        }
示例#10
0
        private void WriteAssembly(string sourceFilePath)
        {
            // Create the provider.

            CodeDomProvider provider = CreateCodeProvider();

            // Create the assembly.

//			ICodeCompiler compiler = provider.CreateCompiler();
            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory   = false;
            parameters.OutputAssembly     = m_assemblyInfo.Name;

            // Add all the referenced assemblies to the compiler options (since we're not passing m_unit to the compiler).

            foreach (string reference in m_unit.ReferencedAssemblies)
            {
                parameters.ReferencedAssemblies.Add(reference);
            }

            // The IncludeDebugInformation flag does more than it says - it also disables optimization and defines
            // the "DEBUG" compile time constant. Only do this in the Debug build. In Release build manually
            // add the "/debug+" compiler argument (the same for both csc.exe and vbc.exe), so that a PDB file
            // is generated, but optimization is still enabled.

#if DEBUG
            parameters.IncludeDebugInformation = true;
#else
            Trace.Assert(provider is Microsoft.CSharp.CSharpCodeProvider || provider is Microsoft.VisualBasic.VBCodeProvider,
                         "Unexpected type of code provider: " + provider.GetType().FullName);
            parameters.IncludeDebugInformation = false;
            parameters.CompilerOptions         = "/debug+";
#endif

            string tempPath = Path.Combine(Path.GetDirectoryName(m_assemblyInfo.Name), "Source");

            // Make sure the path is there.

            bool createDir = !Directory.Exists(tempPath);
            if (createDir)
            {
                Directory.CreateDirectory(tempPath);
            }

            parameters.TempFiles           = new System.CodeDom.Compiler.TempFileCollection(tempPath, true);
            parameters.TempFiles.KeepFiles = false;

            try
            {
                CompilerResults results = provider.CompileAssemblyFromFile(parameters, sourceFilePath);
                if (results.Errors.HasErrors)
                {
                    StringBuilder sb = new StringBuilder(System.Environment.NewLine);
                    foreach (CompilerError error in results.Errors)
                    {
                        sb.Append(error.ErrorText);
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new System.ApplicationException("An attempt to compile the '" + m_assemblyInfo.Name
                                                          + "' assembly has failed with the following errors: " + sb.ToString());
                }
            }
            finally
            {
                // Delete the temporary directory, if we created it.

                DirectoryInfo dirInfo = new DirectoryInfo(tempPath);
                if (createDir && dirInfo.GetFiles().Length == 0 && dirInfo.GetDirectories().Length == 0)
                {
                    dirInfo.Delete();
                }
            }
        }
示例#11
0
        // TODO: Move compilation stuff elsewhere.
        public List <Assembly> GetAssemblies()
        {
            List <Assembly> list = new List <Assembly>();
            // Dynamically compile this project to an in-memory assembly
            CodeDomProvider provider = GetProvider();

            if (provider == null)
            {
                return(list);
            }

            CompilerParameters cp = new CompilerParameters();

            // TODO: Debug build ?
            // cp.IncludeDebugInformation = true;
            cp.GenerateExecutable = false;
            //cp.OutputAssembly = Name; // TODO: Keep track of built assembly for the project
            cp.GenerateInMemory      = true;
            cp.TreatWarningsAsErrors = false;

            if (provider is Microsoft.VisualBasic.VBCodeProvider)
            {
                cp.CompilerOptions = " /libPath:\"" + DnaLibrary.ExecutingDirectory + "\" ";
                if (DefaultImports)
                {
                    string importsList = "Microsoft.VisualBasic,System,System.Collections,System.Collections.Generic,System.Data,System.Diagnostics,ExcelDna.Integration";
                    cp.CompilerOptions += " /imports:" + importsList;
                }
            }
            else if (provider is Microsoft.CSharp.CSharpCodeProvider)
            {
                cp.CompilerOptions = " /lib:\"" + DnaLibrary.ExecutingDirectory + "\" ";
            }
            else if (provider.GetType().FullName == "Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider")
            {
                cp.CompilerOptions = " --nologo -I " + DnaLibrary.ExecutingDirectory;
            }

            List <string> references = GetReferences().ConvertAll <string>(delegate(Reference item) { return(item.AssemblyPath); });

            cp.ReferencedAssemblies.AddRange(references.ToArray());

            List <string>   sources = GetSourceItems().ConvertAll <string>(delegate(SourceItem item) { return(item.Code); });
            CompilerResults cr      = provider.CompileAssemblyFromSource(cp, sources.ToArray());

            // TODO: URGENT: Revisit...
            if (tempIntegrationAssemblyPath != null)
            {
                File.Delete(tempIntegrationAssemblyPath);
                tempIntegrationAssemblyPath = null;
            }

            if (cr.Errors.HasErrors)
            {
                ExcelDna.Logging.LogDisplay.WriteLine("There were errors when compiling project: " + Name);
                foreach (CompilerError err in cr.Errors)
                {
                    ExcelDna.Logging.LogDisplay.WriteLine(err.ToString());
                }
                return(list);
            }

            // Success !!
            // Now add all the references
            // TODO: How to remove again??
            foreach (Reference r in References)
            {
                AssemblyReference.AddAssembly(r.AssemblyPath);
            }

            list.Add(cr.CompiledAssembly);
            return(list);
        }
示例#12
0
        private SourceCompilerCachedEntry CompileAndCache()
        {
            BaseCompiler.GenerateCompilerParameters(_compilParams);

            // Get the set of config assemblies for our context
            IDictionary configAssemblies = CompilationConfiguration.GetAssembliesFromContext(_context);

            if (_assemblies == null)
            {
                _assemblies = new Hashtable();
            }

            // Add all the assemblies from the config object to the hashtable
            // This guarantees uniqueness
            if (configAssemblies != null)
            {
                foreach (Assembly asm in configAssemblies.Values)
                {
                    _assemblies[asm] = null;
                }
            }

            // And the assembly of the application object (global.asax)
            _assemblies[HttpApplicationFactory.ApplicationType.Assembly] = null;

            // Now add all the passed in assemblies to the compilParams
            foreach (Assembly asm in _assemblies.Keys)
            {
                _compilParams.ReferencedAssemblies.Add(Util.GetAssemblyCodeBase(asm));
            }

            // Instantiate the Compiler
            CodeDomProvider codeProvider = (CodeDomProvider)HttpRuntime.CreatePublicInstance(_compilerType);
            ICodeCompiler   compiler     = codeProvider.CreateCompiler();
            CompilerResults results;

            // Compile the source file or string into an assembly

            try {
                _utcStart = DateTime.UtcNow;

                // If we have a source file, read it as a string and compile it.  This way,
                // the compiler never needs to read the original file, avoiding permission
                // issues (see ASURT 112718)
                if (_sourceString == null)
                {
                    _sourceString = Util.StringFromFile(_physicalPath, _context);

                    // Put in some context so that the file can be debugged.
                    _linePragma = new CodeLinePragma(_physicalPath, 1);
                }

                CodeSnippetCompileUnit snippetCompileUnit = new CodeSnippetCompileUnit(_sourceString);
                snippetCompileUnit.LinePragma = _linePragma;
                results = compiler.CompileAssemblyFromDom(_compilParams, snippetCompileUnit);
            }
            catch (Exception e) {
                throw new HttpUnhandledException(HttpRuntime.FormatResourceString(SR.CompilationUnhandledException, codeProvider.GetType().FullName), e);
            }

            BaseCompiler.ThrowIfCompilerErrors(results, codeProvider,
                                               null, _physicalPath, _sourceString);

            SourceCompilerCachedEntry scce = new SourceCompilerCachedEntry();

            // Load the assembly
            scce._assembly = results.CompiledAssembly;

            // If we have a type name, load the type from the assembly
            if (_typeName != null)
            {
                scce._type = scce._assembly.GetType(_typeName);

                // If the type could not be loaded, delete the assembly and rethrow
                if (scce._type == null)
                {
                    PreservedAssemblyEntry.RemoveOutOfDateAssembly(scce._assembly.GetName().Name);

                    // Remember why we failed
                    _typeNotFoundInAssembly = true;

                    throw new HttpException(
                              HttpRuntime.FormatResourceString(SR.Could_not_create_type, _typeName));
                }
            }

            CacheEntryToDisk(scce);
            CacheEntryToMemory(scce);

            return(scce);
        }