Пример #1
0
        public override void MainSetup()
        {
            base.MainSetup();

            var project = Solution.Projects.FirstOrDefault(x => x.FileName.Equals(ProjectFile));

            Assert.True(null != project, "Failed to load project from Solution.Projects.  This is a bug with the Test");

            if (FailIfNoCodeGenerated)
            {
                Assert.False(string.IsNullOrEmpty(GeneratedCode), "No Code was Generated");
            }

            //http://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-sharp-code-fragments
            var csc = new CSharpCodeProvider(
                new Dictionary <string, string>()
            {
                { "CompilerVersion", "v4.0" }
            });

            var referencedAssemblies =
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(a => !a.FullName.StartsWith("mscorlib", StringComparison.InvariantCultureIgnoreCase))
                .Where(a => !a.IsDynamic)     //necessary because a dynamic assembly will throw and exception when calling a.Location.  But unsure why there are dynamic assemblies in the Current Domain
                .Select(a => a.Location)
                .Union(AddAdditionalReferencedAssemblies())
                .Distinct()
                .ToArray();

            var parameters = new CompilerParameters(
                referencedAssemblies);

            CompilerResults = csc.CompileAssemblyFromSource(parameters,
                                                            SourceCode + GeneratedCode);

            var errors = CompilerResults.PrettyPrintErrorList();

            if (!string.IsNullOrEmpty(errors))
            {
                _hasCompilerErrors = true;

                var logMessage = "Compilation Errors: \r\n: " + errors;

                Console.WriteLine(logMessage);

                if (FailOnCompilerErrors)
                {
                    Assert.Fail();
                }
            }
        }