Exemple #1
0
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
        /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
        /// <returns>A Project created out of the Douments created from the source strings</returns>
        public static Project CreateProject(string[] sources,
                                            string language,
                                            LanguageVersion languageVersionCSharp,
                                            Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var          fileNamePrefix = DefaultFilePathPrefix;
            string       fileExt;
            ParseOptions parseOptions;

            if (language == LanguageNames.CSharp)
            {
                fileExt      = CSharpDefaultFileExt;
                parseOptions = new CSharpParseOptions(languageVersionCSharp);
            }
            else
            {
                fileExt      = VisualBasicDefaultExt;
                parseOptions = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions(languageVersionVB);
            }

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

#pragma warning disable CC0022
            var workspace = new AdhocWorkspace();
#pragma warning restore CC0022

            var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), TestProjectName,
                                                 TestProjectName, language,
                                                 parseOptions: parseOptions,
                                                 metadataReferences: ImmutableList.Create(
                                                     CorlibReference, SystemCoreReference, RegexReference,
                                                     CSharpSymbolsReference, CodeAnalysisReference, JsonNetReference));

            workspace.AddProject(projectInfo);

            var count = 0;
            foreach (var source in sources)
            {
                var newFileName = fileNamePrefix + count + "." + fileExt;
                workspace.AddDocument(projectId, newFileName, SourceText.From(source));
                count++;
            }

            var project = workspace.CurrentSolution.GetProject(projectId);
            var newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(diagOptions);
            var newSolution           = workspace.CurrentSolution.WithProjectCompilationOptions(projectId, newCompilationOptions);
            var newProject            = newSolution.GetProject(projectId);
            return(newProject);
        }
        private static void CreateCompilationMultiFile(string[] filenames)
        {
            string assemblyName = System.Guid.NewGuid().ToString();

            System.Collections.Generic.IEnumerable <Microsoft.CodeAnalysis.MetadataReference> references =
                GetAssemblyReferences();

            Microsoft.CodeAnalysis.SyntaxTree[] syntaxTrees = new Microsoft.CodeAnalysis.SyntaxTree[filenames.Length];

            Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions op = null;

            for (int i = 0; i < filenames.Length; ++i)
            {
                string fileContent = System.IO.File.ReadAllText(filenames[i], System.Text.Encoding.UTF8);
                syntaxTrees[i] = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                    fileContent
                    , op
                    , filenames[i]
                    , System.Text.Encoding.UTF8
                    );
            }



            Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions co =
                new Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilationOptions
                (
                    Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary
                );

            co.WithOptionStrict(Microsoft.CodeAnalysis.VisualBasic.OptionStrict.Off);
            co.WithOptionExplicit(false);
            co.WithOptionInfer(true);


            Microsoft.CodeAnalysis.Compilation compilation = Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation.Create(
                assemblyName,
                syntaxTrees,
                references,
                co
                );


            // byte[] compilationResult = compilation.EmitToArray();

            using (System.IO.MemoryStream dllStream = new System.IO.MemoryStream())
            {
                using (System.IO.MemoryStream pdbStream = new System.IO.MemoryStream())
                {
                    Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(dllStream, pdbStream);
                    if (!emitResult.Success)
                    {
                        CheckCompilationResult(emitResult);
                    } // End if (!emitResult.Success)
                }     // End Using pdbStream
            }         // End Using dllStream



            /*
             * // get the type Program from the assembly
             * System.Type programType = assembly.GetType("Program");
             *
             * // Get the static Main() method info from the type
             * System.Reflection.MethodInfo method = programType.GetMethod("Main");
             *
             * // invoke Program.Main() static method
             * method.Invoke(null, null);
             */

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                Microsoft.CodeAnalysis.Emit.EmitResult result = compilation.Emit(ms);
                ThrowExceptionIfCompilationFailure(result);
                ms.Seek(0, System.IO.SeekOrigin.Begin);


                System.Reflection.Assembly assembly2 = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(ms);
#if NET46
                // Different in full .Net framework
                System.Reflection.Assembly assembly3 = Assembly.Load(ms.ToArray());
#endif
            } // End Using ms
        }
        /// <summary>
        /// Create a project using the inputted strings as sources.
        /// </summary>
        /// <param name="sources">Classes in the form of strings</param>
        /// <param name="language">The language the source code is in</param>
        /// <param name="languageVersionCSharp">C# language version used for compiling the test project, required unless you inform the VB language version.</param>
        /// <param name="languageVersionVB">VB language version used for compiling the test project, required unless you inform the C# language version.</param>
        /// <returns>A Project created out of the Douments created from the source strings</returns>
        public static Project CreateProject(string[] sources,
            string language,
            LanguageVersion languageVersionCSharp,
            Microsoft.CodeAnalysis.VisualBasic.LanguageVersion languageVersionVB)
        {
            var fileNamePrefix = DefaultFilePathPrefix;
            string fileExt;
            ParseOptions parseOptions;
            if (language == LanguageNames.CSharp)
            {
                fileExt = CSharpDefaultFileExt;
                parseOptions = new CSharpParseOptions(languageVersionCSharp);
            }
            else
            {
                fileExt = VisualBasicDefaultExt;
                parseOptions = new Microsoft.CodeAnalysis.VisualBasic.VisualBasicParseOptions(languageVersionVB);
            }

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);
#pragma warning disable CC0022
            var workspace = new AdhocWorkspace();
#pragma warning restore CC0022

            var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), TestProjectName,
                TestProjectName, language,
                parseOptions: parseOptions,
                metadataReferences: ImmutableList.Create(
                    CorlibReference, SystemCoreReference, RegexReference,
                    CSharpSymbolsReference, CodeAnalysisReference, JsonNetReference));

            workspace.AddProject(projectInfo);

            var count = 0;
            foreach (var source in sources)
            {
                var newFileName = fileNamePrefix + count + "." + fileExt;
                workspace.AddDocument(projectId, newFileName, SourceText.From(source));
                count++;
            }

            var project = workspace.CurrentSolution.GetProject(projectId);
            var newCompilationOptions = project.CompilationOptions.WithSpecificDiagnosticOptions(diagOptions);
            var newSolution = workspace.CurrentSolution.WithProjectCompilationOptions(projectId, newCompilationOptions);
            var newProject = newSolution.GetProject(projectId);
            return newProject;
        }