예제 #1
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="engine"></param>
 /// <param name="cSharpCompiler"></param>
 /// <param name="applicationPartManager"></param>
 /// <param name="tempDataDictionaryFactory"></param>
 /// <param name="razorViewEngineFileProviderAccessor"></param>
 /// <param name="razorPageActivator"></param>
 /// <param name="htmlEncoder"></param>
 /// <param name="razorPageFactoryProvider"></param>
 /// <param name="httpContextAccessor"></param>
 /// <param name="projectCacheProvider"></param>
 /// <param name="loggerFactory"></param>
 /// <param name="razorEngineOptions"></param>
 /// <param name="mvcViewOptions"></param>
 /// <param name="diagnosticSource"></param>
 public DynamicRazorEngine(RazorEngine engine,
                           CSharpCompiler cSharpCompiler,
                           ApplicationPartManager applicationPartManager,
                           ITempDataDictionaryFactory tempDataDictionaryFactory,
                           IRazorViewEngineFileProviderAccessor razorViewEngineFileProviderAccessor,
                           IRazorPageActivator razorPageActivator,
                           HtmlEncoder htmlEncoder,
                           IRazorPageFactoryProvider razorPageFactoryProvider,
                           IHttpContextAccessor httpContextAccessor,
                           IDynamicRazorProjectCacheProvider projectCacheProvider,
                           ILoggerFactory loggerFactory,
                           IOptions <RazorViewEngineOptions> razorEngineOptions,
                           IOptions <MvcViewOptions> mvcViewOptions,
                           DiagnosticSource diagnosticSource,
                           IServiceProvider serviceProvider)
 {
     _engine = engine;
     _tempDataDictionaryFactory           = tempDataDictionaryFactory;
     _razorViewEngineFileProviderAccessor = razorViewEngineFileProviderAccessor;
     _cSharpCompiler           = cSharpCompiler;
     _razorEngineOptions       = razorEngineOptions;
     _applicationPartManager   = applicationPartManager;
     _loggerFactory            = loggerFactory;
     _razorPageActivator       = razorPageActivator;
     _htmlEncoder              = htmlEncoder;
     _httpContextAccessor      = httpContextAccessor;
     _projectCacheProvider     = projectCacheProvider;
     _diagnosticSource         = diagnosticSource;
     _mvcViewOptions           = mvcViewOptions;
     _razorPageFactoryProvider = razorPageFactoryProvider;
     _serviceProvider          = serviceProvider;
 }
예제 #2
0
파일: Program.cs 프로젝트: lulzzz/Lyzard
        static void CompilerTest(string[] args)
        {
            var compiler = new CSharpCompiler();
            var dllPath  = Path.GetFullPath("TestClasses") + CommonFolders.Sep + "TestApp.dll";
            var results  = compiler.Compile("TestApp", "TestClasses", new List <string> {
                Path.GetFullPath("TestClasses/TestClass1.cs"),
                Path.GetFullPath("TestClasses/TestClass2.cs")
            });

            foreach (CompilerError err in results.Errors)
            {
                Console.WriteLine($"{(err.IsWarning ? "WARNING :" : "ERROR  :")} {err.ErrorText}");
            }

            if (!results.Errors.HasErrors)
            {
                var loader = new AppDomainLoader("TestApp", dllPath);

                if (loader.IsLoaded)
                {
                    var testClass1 = loader.RunRemoteFunc <object>(() => {
                        Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ApplicationName);

                        return(null);
                    });
                }
            }
        }
 public ViewInfoContainerCodeGenerator(
     CSharpCompiler compiler,
     CSharpCompilation compilation)
 {
     Compiler    = compiler;
     Compilation = compilation;
 }
예제 #4
0
#pragma warning restore RECS0108

        /// <summary>
        /// Constructs new collector instance and cached it data.
        /// </summary>
        /// <param name="collectorSourcePath">Path so source file of the collector.</param>
        /// <returns>Created instance of cached collector data.</returns>
        public static TCollector Create(string collectorSourcePath)
        {
            var safeCollectorSourcePath = collectorSourcePath ?? typeof(TCollectorEnumerator).Name;

            if (!s_CachedCache.ContainsKey(safeCollectorSourcePath))
            {
                TCollectorEnumerator collector = null;
                if (collectorSourcePath != null)
                {
                    var assembly = CSharpCompiler.CompileSourceFile(collectorSourcePath);
                    var assemblyExportedTypes = assembly.GetExportedTypes();
                    foreach (var assemblyExportedType in assemblyExportedTypes)
                    {
                        if (assemblyExportedType.IsSubclassOf(typeof(TCollectorEnumerator)))
                        {
                            collector = (TCollectorEnumerator)Activator.CreateInstance(assemblyExportedType);
                            break;
                        }
                    }
                }

                collector        = collector ?? Activator.CreateInstance <TCollectorEnumerator>();
                collector.Source = collectorSourcePath;

                var cache = (TCollector)Activator.CreateInstance(typeof(TCollector), collector);
                s_CachedCache.Add(safeCollectorSourcePath, cache);
                return(cache);
            }
            return(s_CachedCache[safeCollectorSourcePath]);
        }
예제 #5
0
        protected async Task <Microsoft.Rest.CSharp.Compiler.Compilation.CompilationResult> Compile(IFileSystem fileSystem)
        {
            var compiler = new CSharpCompiler(fileSystem.GetFiles("", "*.cs", SearchOption.AllDirectories)
                                              .Select(each => new KeyValuePair <string, string>(each, fileSystem.ReadAllText(each))).ToArray(), _assemblies);

            return(await compiler.Compile(OutputKind.DynamicallyLinkedLibrary));
        }
예제 #6
0
        /// <summary>
        /// Builds the expected base of touched files.
        /// Adds a hook for temporary file creation as well,
        /// so this method must be called before the execution of
        /// Csc.Run.
        /// </summary>
        private static void BuildTouchedFiles(CSharpCompiler cmd,
                                              string outputPath,
                                              out List <string> expectedReads,
                                              out List <string> expectedWrites)
        {
            expectedReads = cmd.Arguments.MetadataReferences
                            .Select(r => r.Reference).ToList();

            foreach (var file in cmd.Arguments.SourceFiles)
            {
                expectedReads.Add(file.Path);
            }

            var writes = new List <string>();

            writes.Add(outputPath);

            // Hook temporary file creation
            cmd.PathGetTempFileName = () =>
            {
                // Named 'GetFileName', but actually a path
                string tempPath = Path.GetTempFileName();
                writes.Add(tempPath);
                return(tempPath);
            };
            expectedWrites = writes;
        }
예제 #7
0
    private static TestRazorViewCompiler GetViewCompiler(
        TestFileProvider fileProvider                   = null,
        RazorReferenceManager referenceManager          = null,
        IList <CompiledViewDescriptor> precompiledViews = null,
        CSharpCompiler csharpCompiler                   = null)
    {
        fileProvider = fileProvider ?? new TestFileProvider();
        var options = Options.Create(new MvcRazorRuntimeCompilationOptions
        {
            FileProviders = { fileProvider }
        });
        var compilationFileProvider = new RuntimeCompilationFileProvider(options);

        referenceManager = referenceManager ?? CreateReferenceManager();
        precompiledViews = precompiledViews ?? Array.Empty <CompiledViewDescriptor>();

        var hostingEnvironment = Mock.Of <IWebHostEnvironment>(e => e.ContentRootPath == "BasePath");
        var fileSystem         = new FileProviderRazorProjectFileSystem(compilationFileProvider, hostingEnvironment);
        var projectEngine      = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder =>
        {
            RazorExtensions.Register(builder);
        });

        csharpCompiler = csharpCompiler ?? new CSharpCompiler(referenceManager, hostingEnvironment);

        return(new TestRazorViewCompiler(
                   fileProvider,
                   projectEngine,
                   csharpCompiler,
                   precompiledViews));
    }
예제 #8
0
        private IEnumerable <string> download(Request requestParams)
        {
            if (String.IsNullOrWhiteSpace(requestParams.DownloadFuncCode))
            {
                return(new [] { Download(requestParams) });
            }

            if (requestParams.DownloadFunc == null)
            {
                CompilerErrorCollection errors;
                RequestDownloadFuncBase obj;
                var code = String.Format(codeTemplate, requestParams.DownloadFuncCode);
                if (!_compiler.CompileClass(ref code, true, out obj, out errors))
                {
                    Log.Add(RecType.UserError, "Compile errors:\r\n" + CSharpCompiler.ErrorsToString(errors, code));
                    return(null);
                }
                if (errors.Count > 0)
                {
                    Log.Add(RecType.UserWarning, "Compile errors:\r\n" + CSharpCompiler.ErrorsToString(errors, code));
                }
                requestParams.DownloadFunc = obj.Func;
            }

            if (requestParams.DownloadFunc == null)
            {
                return(null);
            }

            var preparedRequestParams = (Request)requestParams.Clone();

            return(requestParams.DownloadFunc(preparedRequestParams));
        }
예제 #9
0
        public void ValidCodeCompileTest()
        {
            var validCode =
                @"using System;

namespace Test
{
	public class Program
	{
		public static int Plus(int a, int b)
		{
			return a + b;
		}
	}
}";

            var compiler = new CSharpCompiler();
            var result   = compiler.CompileCode(validCode);

            result.Success.Should().BeTrue();

            var programClass = result.Assembly.GetTypes().FirstOrDefault(type => type.Name == "Program");

            programClass.Should().NotBeNull();

            var plusMethod = programClass.GetMethod("Plus", BindingFlags.Public | BindingFlags.Static);

            plusMethod.Should().NotBeNull();
            plusMethod.Invoke(null, new object[] { 1, 2 }).As <int>().Should().Be(3);
        }
예제 #10
0
 public CodeForm()
 {
     InitializeComponent();
     this.code_combo.SelectedItem = "C++";
     this.selectedCode            = "C++";
     compiler = CSharpCompiler.getInstance();
 }
예제 #11
0
        public FileCompileResult Compile(string fileToCompile)
        {
            CompileResult result;

            if (fileToCompile.EndsWith(".cs"))
            {
                var compiler       = new CSharpCompiler();
                var copiedFileName = fileToCompile + ".cs";
                File.Copy(fileToCompile, copiedFileName);
                result = compiler.Compile(this.csharpCompilerPath, copiedFileName, "/optimize+ /nologo /reference:System.Numerics.dll");
            }
            else if (fileToCompile.EndsWith(".zip"))
            {
                var compiler       = new MsBuildCompiler();
                var copiedFileName = fileToCompile + ".zip";
                File.Copy(fileToCompile, copiedFileName);
                result = compiler.Compile(this.msbuildCompilerPath, copiedFileName, "/t:rebuild /p:Configuration=Release,Optimize=true /verbosity:quiet /nologo");
            }
            else
            {
                throw new ArgumentException("Invalid file extension", "fileToCompile");
            }

            return(new FileCompileResult(result));
        }
예제 #12
0
        public async Task CompileAsync_BadCode_Compilation_Error()
        {
            var compiler = new CSharpCompiler();
            var bytes    = await compiler.CompileAsync(new BuildingTask("badCode", CSharpSnippets.BadCode));

            bytes.Should().BeEmpty();
        }
예제 #13
0
        public async Task CompileAsync_ExceptionCode_Compilation_Successfully_Complete()
        {
            var compiler = new CSharpCompiler();
            var bytes    = await compiler.CompileAsync(new BuildingTask("exCode", CSharpSnippets.ExceptionCode));

            bytes.Should().NotBeEmpty();
        }
예제 #14
0
        public async Task CompileAsync_GoodCode_Compilation_Success()
        {
            var compiler = new CSharpCompiler();
            var bytes    = await compiler.CompileAsync(new BuildingTask("goodCode", CSharpSnippets.GoodCode));

            bytes.Should().NotBeEmpty();
        }
예제 #15
0
        public void CompileAsync_Empty_BuildingTask_Should_Throw_InvalidOperationException(string projectName, string sourceCode)
        {
            var compiler = new CSharpCompiler();
            Func <Task <byte[]> > act = () => compiler.CompileAsync(new BuildingTask(projectName, sourceCode));

            act.Should().ThrowExactly <InvalidOperationException>();
        }
예제 #16
0
        public void CompileAsync_Null_BuildingTask_Should_Throw_ArgumentNullException()
        {
            var compiler = new CSharpCompiler();
            Func <Task <byte[]> > act = () => compiler.CompileAsync(null);

            act.Should().ThrowExactly <ArgumentNullException>();
        }
예제 #17
0
 public Generator(CSharpCompiler re, TextWriter codeWriter, TextWriter snippetWriter, GeneratorOptions options)
 {
     _re          = re;
     MainCode     = codeWriter;
     SnippetsCode = snippetWriter;
     _options     = options;
 }
예제 #18
0
    public void EnsureOptions_ConfiguresDefaultCompilationOptions()
    {
        // Arrange
        var hostingEnvironment = Mock.Of <IWebHostEnvironment>(h => h.EnvironmentName == "Development");
        var compiler           = new CSharpCompiler(ReferenceManager, hostingEnvironment);

        // Act & Assert
        var compilationOptions = compiler.CSharpCompilationOptions;

        Assert.False(compilationOptions.AllowUnsafe);
        Assert.Equal(ReportDiagnostic.Default, compilationOptions.GeneralDiagnosticOption);
        Assert.Equal(OptimizationLevel.Debug, compilationOptions.OptimizationLevel);
        Assert.Collection(compilationOptions.SpecificDiagnosticOptions.OrderBy(d => d.Key),
                          item =>
        {
            Assert.Equal("CS1701", item.Key);
            Assert.Equal(ReportDiagnostic.Suppress, item.Value);
        },
                          item =>
        {
            Assert.Equal("CS1702", item.Key);
            Assert.Equal(ReportDiagnostic.Suppress, item.Value);
        },
                          item =>
        {
            Assert.Equal("CS1705", item.Key);
            Assert.Equal(ReportDiagnostic.Suppress, item.Value);
        });
    }
예제 #19
0
        protected async Task <CompilationResult> Compile(IFileSystem fileSystem)
        {
            var compiler = new CSharpCompiler(
                fileSystem.GetFiles("GeneratedCode", "*.cs", SearchOption.AllDirectories)
                .Select(each => new KeyValuePair <string, string>(each, fileSystem.ReadFileAsText(each))).ToArray(),
                ManagedAssets.FrameworkAssemblies.Concat(
                    AppDomain.CurrentDomain.GetAssemblies()
                    .Where(each => !each.IsDynamic && !string.IsNullOrEmpty(each.Location))
                    .Select(each => each.Location)
                    .Concat(new[]
            {
                Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                             "Microsoft.Rest.ClientRuntime.dll"),
                Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                             "Microsoft.Rest.ClientRuntime.Azure.dll")
            })
                    ));
            var result = await compiler.Compile(OutputKind.DynamicallyLinkedLibrary);

            // if it failed compiling and we're in an interactive session
            if (!result.Succeeded && System.Environment.OSVersion.Platform == PlatformID.Win32NT && System.Environment.UserInteractive)
            {
                var error = result.Messages.FirstOrDefault(each => each.Severity == DiagnosticSeverity.Error);
                if (error != null)
                {
                    // use this to dump the files to disk for examination
                    // open in Favorite Code Editor
                    InspectWithFavoriteCodeEditor(fileSystem.SaveFilesToTemp(GetType().Name), error.Location.GetMappedLineSpan());
                }
            }

            return(result);
        }
예제 #20
0
        public static ExtensionLoader BuildLoader <TCodeSource>(
            ILog logger,
            IEnumerable <ExtensionTypeRecord> typeRecords,
            IEnumerable <TCodeSource> selectedSources,
            IEnumerable <TCodeSource> additionalSources = null,
            CSharpCompilerOptions compilerOptions       = null,
            Options options = null)
            where TCodeSource : ICodeSource
        {
            options = options ?? new Options();
            var compiler            = new CSharpCompiler <TCodeSource>(compilerOptions ?? new CSharpCompilerOptions());
            var selectedSourcesList = selectedSources as IList <TCodeSource> ?? selectedSources.ToList();
            var results             = compiler.Compile(selectedSourcesList, additionalSources).ToDictionary(r => r.Source.UniqueName);

            var assemblies      = new List <Assembly>(results.Count);
            var orderedSelected = selectedSourcesList.Select(s => results[s.UniqueName]).ToList();

            if (options.InclusionStrategy == InclusionStrategy.AfterFirst)
            {
                // TODO: implement
                throw new NotImplementedException("non-None inclusion strategies not yet implemented, pull requests welcome.");
            }
            else if (options.InclusionStrategy == InclusionStrategy.AfterLast)
            {
                // TODO: implement
                throw new NotImplementedException("non-None inclusion strategies not yet implemented, pull requests welcome.");
            }

            return(new ExtensionLoader(logger, assemblies, typeRecords, options.ThrowOnConstructorMissing));
        }
예제 #21
0
 public Context(CSharpCompiler compiler, RootNode root, Expression currentExpr, BlockNode currentBlock)
 {
     Compiler          = compiler;
     Root              = root;
     CurrentExpression = currentExpr;
     CurrentBlock      = currentBlock;
 }
예제 #22
0
        public override bool Execute(List <string> args)
        {
            SystemHelper.CreateOrCleanDirectory("tmp");
            var compiler = LanguageHelper.GetCompilerPath(ServiceSpecType.Bond30);
            var bondcDir = Path.GetDirectoryName(compiler);

            string[] templates = { "bond_composition_stub.tt" };
            var      arguments = string.Join(" ", args.ToArray()) + " /c#" +
                                 templates.VerboseCombine(" ", t => " /T:" + Path.Combine(bondcDir, t))
                                 + " /O:tmp";

            Console.Write(arguments);
            var err = SystemHelper.RunProcess(compiler, arguments);

            Trace.Assert(err == 0, "bondc code generation failed");

            CSharpCompiler.ToDiskAssembly(
                Directory.GetFiles("tmp", "*_composition_stub.cs", SearchOption.AllDirectories).ToArray(),
                new[] { "rDSN.Tron.Utility.dll", "rDSN.Tron.Contract.dll", "Microsoft.Bond.dll", "Microsoft.Bond.Interfaces.dll", "Microsoft.Bond.Rpc.dll", "Microsoft.Bond.TypeProvider.dll" },
                args.ToArray(),
                "compo.dll"
                );
            Console.ReadLine();
            return(true);
        }
예제 #23
0
        public static CSharpCompilation AddAssemblyMetadata(
            CSharpCompiler compiler,
            CSharpCompilation compilation,
            CompilationOptions compilationOptions)
        {
            if (!string.IsNullOrEmpty(compilationOptions.KeyFile))
            {
                var updatedOptions = compilation.Options.WithStrongNameProvider(new DesktopStrongNameProvider());
                var keyFilePath    = Path.GetFullPath(compilationOptions.KeyFile);

                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || compilationOptions.PublicSign)
                {
                    updatedOptions = updatedOptions.WithCryptoPublicKey(
                        SnkUtils.ExtractPublicKey(File.ReadAllBytes(keyFilePath)));
                }
                else
                {
                    updatedOptions = updatedOptions.WithCryptoKeyFile(keyFilePath)
                                     .WithDelaySign(compilationOptions.DelaySign);
                }

                compilation = compilation.WithOptions(updatedOptions);
            }

            var applicationAssemblyName = Assembly.Load(new AssemblyName(compilationOptions.ApplicationName)).GetName();
            var assemblyVersionContent  = $"[assembly:{typeof(AssemblyVersionAttribute).FullName}(\"{applicationAssemblyName.Version}\")]";
            var syntaxTree = compiler.CreateSyntaxTree(SourceText.From(assemblyVersionContent));

            return(compilation.AddSyntaxTrees(syntaxTree));
        }
예제 #24
0
        public static IVirtualMachine Compile(string asmSource)
        {
            AsmToken[][] asmTokens = AssemblyLexer.LexAsmCode(asmSource);
            X86Assembly  assembly  = X86Assembler.GenerateAssembly(asmTokens);
            string       source    = CSharpGenerator.GenerateSource(assembly);

            return(CSharpCompiler.CompileCSharp(source));
        }
예제 #25
0
        public async Task ExecuteAsync_GoodCode_Compilation_Success() {
            var compiler = new CSharpCompiler();
            var bytes = await compiler.CompileAsync(new BuildingTask("goodCode", CSharpSnippets.GoodCode));
            var runner = new CSharpRunner();
            var buildResult = await runner.ExecuteAsync(bytes, Array.Empty<string>());

            buildResult.Success.Should().BeTrue();
        }
        public async Task Initialize(Project project)
        {
            _sourceVbProject = project;
            var cSharpCompilationOptions = CSharpCompiler.CreateCompilationOptions();

            _convertedCsProject    = project.ToProjectFromAnyOptions(cSharpCompilationOptions, DoNotAllowImplicitDefault);
            _csharpViewOfVbSymbols = (CSharpCompilation)await project.CreateReferenceOnlyCompilationFromAnyOptionsAsync(cSharpCompilationOptions);
        }
예제 #27
0
        public void InvalidCodeCompileTest()
        {
            var invalidCode = "This is not valid C# code.";

            var compiler = new CSharpCompiler();

            compiler.CompileCode(invalidCode).Success.Should().BeFalse();
        }
예제 #28
0
        public async Task ExecuteAsync_ExceptionCode_Compilation_Successfully_Complete() {
            var compiler = new CSharpCompiler();
            var bytes = await compiler.CompileAsync(new BuildingTask("exCode", CSharpSnippets.ExceptionCode));
            var runner = new CSharpRunner();
            var buildResult = await runner.ExecuteAsync(bytes, Array.Empty<string>());

            buildResult.Success.Should().BeFalse();
        }
예제 #29
0
 public void CompileTest()
 {
     var compiler = new CSharpCompiler("test");
       var func = compiler.Compile("test.prop2 = test.prop;");
       dynamic test = new ExpandoObject();
       test.prop = "test";
       func(test, null);
       Assert.AreEqual(test.prop, test.prop2);
 }
예제 #30
0
        internal Client(IDatabase db, Assembly assembly, TCursor debugInstance)
        {
            _csharpCompiler = new CSharpCompiler();
            _luaHandler     = new LuaHandler(db);
            _delegateReader = DelegateReader.CreateCachedWithDefaultAssemblyProvider();

            DebugInstance = debugInstance;
            Database      = db;
        }
예제 #31
0
 public CSharpCompileDecompilePlagiarismDetector(string csharpCompilerPath, string dotNetDisassemblerPath, ISimilarityFinder similarityFinder)
 {
     this.csharpCompilerPath     = csharpCompilerPath;
     this.dotNetDisassemblerPath = dotNetDisassemblerPath;
     this.csharpCompiler         = new CSharpCompiler();
     this.dotNetDisassembler     = new DotNetDisassembler();
     this.similarityFinder       = similarityFinder;
     this.sourcesCache           = new Dictionary <string, string>();
 }
예제 #32
0
 public static void Test_01()
 {
     CSharpCompiler compiler = new CSharpCompiler();
     compiler.AssemblyName = "test_01";
     compiler.OutputPath = @"test_01\test_01";
     compiler.LanguageVersion = LanguageVersion.CSharp6;
     compiler.OutputKind = OutputKind.ConsoleApplication;
     compiler.OptimizationLevel = OptimizationLevel.Debug;
     compiler.Platform = Platform.AnyCpu;
     compiler.GeneralDiagnosticOption = ReportDiagnostic.Default;
     compiler.WarningLevel = 4;
     compiler.SourceFiles = new string[] { @"test_01\test_01.cs" };
     compiler.Compile();
 }
예제 #33
0
 public void CompileThrowsCompilerExceptionTest()
 {
     var compiler = new CSharpCompiler("test");
       try
       {
     var func = compiler.Compile("not valid c# code");
     func(null, null);
     Assert.Fail();
       }
       catch (Exception err)
       {
     Assert.IsInstanceOfType(err, typeof(CompilerException));
       }
 }
예제 #34
0
        public void Compile()
        {
            CompilerSettings s = new CompilerSettings();
              CSharpCompiler c = new CSharpCompiler(s);

              ICompilerResults cr = c.CompileFiles(new string[] { @"..\..\etc\testdata\compiler\compile_ok.cs" });
              Assert.True(cr.Success);

              Assembly a = cr.GetCompiledAssemblies().First();
              Type t = a.GetType("QCV.Test.TestCompilation");
              Assert.NotNull(t);
              object o = Activator.CreateInstance(t);
              Assert.NotNull(o);
              object result = t.GetMethod("GetString").Invoke(o, null);
              Assert.NotNull(result);
              Assert.AreEqual("Compilation Succeeded", result as string);
        }
예제 #35
0
        public void CSharpCompilerShouldWorkWhenGivenValidSourceCode()
        {
            const string Source = @"using System;
class Program
{
    static void Main()
    {
        Console.WriteLine(""It works!"");
    }
}";

            var compiler = new CSharpCompiler();
            var result = compiler.Compile(CSharpCompilerPath, FileHelpers.SaveStringToTempFile(Source), string.Empty);

            Assert.IsTrue(result.IsCompiledSuccessfully, "Compilation is not successful");
            Assert.IsFalse(string.IsNullOrWhiteSpace(result.OutputFile), "Output file is null");
            Assert.IsTrue(result.OutputFile.EndsWith(".exe"), "Output file does not ends with .exe");
        }
예제 #36
0
 public static void Test_02()
 {
     string frameworkDir = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\";
     CSharpCompiler compiler = new CSharpCompiler();
     compiler.AssemblyName = "test_form_01";
     compiler.OutputPath = @"test_form_01\test_form_01.exe";
     compiler.PdbPath = @"test_form_01\test_form_01.pdb";
     compiler.LanguageVersion = LanguageVersion.CSharp6;
     compiler.OutputKind = OutputKind.WindowsApplication;
     compiler.OptimizationLevel = OptimizationLevel.Debug;
     compiler.Platform = Platform.AnyCpu;
     compiler.GeneralDiagnosticOption = ReportDiagnostic.Default;
     compiler.WarningLevel = 4;
     compiler.Win32ResourceFile = @"test_form_01\test.res";
     compiler.SourceFiles = new string[] { @"test_form_01\Program.cs", @"test_form_01\Form1.cs", @"test_form_01\Form1.Designer.cs", @"test_form_01\Resources.Designer.cs" };
     compiler.ResourceFiles = new ResourceFile[] { new ResourceFile { File = @"test_form_01\Test_WinForm_01.Properties.Resources.resources", Namespace = "Test_WinForm_01.Properties.Resources.resources" } };
     compiler.AssembliesFiles = new string[] { frameworkDir + "mscorlib.dll", frameworkDir + "System.dll", frameworkDir + "System.Windows.Forms.dll", frameworkDir + "System.Drawing.dll" };
     compiler.Compile();
 }
예제 #37
0
 public static void Test_01()
 {
     string frameworkDir = @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\";
     CSharpCompiler compiler = new CSharpCompiler();
     compiler.AssemblyName = "test_01";
     compiler.OutputPath = @"test_01\test_01.exe";
     compiler.PdbPath = @"test_01\test_01.pdb";
     compiler.LanguageVersion = LanguageVersion.CSharp6;
     compiler.OutputKind = OutputKind.ConsoleApplication;
     compiler.OptimizationLevel = OptimizationLevel.Debug;
     compiler.Platform = Platform.AnyCpu;
     compiler.GeneralDiagnosticOption = ReportDiagnostic.Default;
     compiler.WarningLevel = 4;
     compiler.SourceFiles = new string[] { @"test_01\test_01.cs" };
     // Could not find file 'C:\pib\drive\google\dev\project\.net\Test\Test.Test_01\Source\Test_Compiler\vs\Test_Roslyn_01\bin\Debug\mscorlib.dll'
     //compiler.AssembliesFiles = new string[] { "mscorlib.dll", "System.dll" };
     compiler.AssembliesFiles = new string[] { frameworkDir + "mscorlib.dll", frameworkDir + "System.dll" };
     compiler.Compile();
 }
예제 #38
0
        public static void CompileProject(string projectFile)
        {
            CSharpProject project = CSharpProject.Create(projectFile);

            CSharpCompiler compiler = new CSharpCompiler();
            compiler.LanguageVersion = project.LanguageVersion;
            compiler.OutputKind = project.OutputKind;
            compiler.OptimizationLevel = project.OptimizationLevel;
            compiler.Platform = project.Platform;
            compiler.GeneralDiagnosticOption = project.GeneralDiagnosticOption;
            compiler.WarningLevel = project.WarningLevel;

            compiler.AssemblyName = project.AssemblyName;
            compiler.OutputPath = project.OutputPath;
            compiler.PdbPath = project.PdbPath;
            compiler.Win32ResourceFile = project.Win32ResourceFile;
            compiler.PreprocessorSymbols = project.PreprocessorSymbols;
            compiler.SourceFiles = project.SourceFiles;
            compiler.ResourceFiles = project.ResourceFiles;
            compiler.AssembliesFiles = project.AssembliesFiles;
            compiler.Compile();
        }
예제 #39
0
 private Action<object, object> Compile()
 {
     var compiler = new CSharpCompiler(Field);
       return compiler.Compile(_code);
 }
예제 #40
0
        protected TranslationTestHelper(string asmName, string src, bool isDebug)
        {
            var compiler = new CSharpCompiler();
            var asm = Assembly.Load(asmName);
            var result = compiler.CompileSource(src, asm, isDebug);

            var dir = Path.GetDirectoryName(result.PathToAssembly);
            var compiledAsmName = Path.GetFileNameWithoutExtension(result.PathToAssembly);

            this.resolver.AddSearchDirectory(dir);

            this.typeSystem = new TypeSystem(this.resolver);
            this.CompiledAssembly = this.typeSystem.LoadAssembly(compiledAsmName);

            //this.CompiledAssembly.MainModule.LoadSymbols();
            var pathToPdb = Path.Combine(dir, compiledAsmName + ".pdb");
            File.Delete(pathToPdb);

            File.Delete(result.PathToAssembly);
        }
예제 #41
0
        /// <summary>
        /// Builds the expected base of touched files.
        /// Adds a hook for temporary file creation as well,
        /// so this method must be called before the execution of
        /// Csc.Run.
        /// </summary>
        private static void BuildTouchedFiles(CSharpCompiler cmd, 
                                              string outputPath,
                                              out List<string> expectedReads,
                                              out List<string> expectedWrites)
        {
            expectedReads = cmd.Arguments.MetadataReferences
                .Select(r => r.Reference).ToList();

            foreach (var file in cmd.Arguments.SourceFiles)
            {
                expectedReads.Add(file.Path);
            }

            var writes = new List<string>();
            writes.Add(outputPath);

            // Hook temporary file creation
            cmd.PathGetTempFileName = () =>
            {
                // Named 'GetFileName', but actually a path
                string tempPath = Path.GetTempFileName();
                writes.Add(tempPath);
                return tempPath;
            };
            expectedWrites = writes;
        }
예제 #42
0
 public CustomCompilationService(CSharpCompiler compiler,
     IRazorViewEngineFileProviderAccessor fileProviderAccessor, IOptions<RazorViewEngineOptions> optionsAccessor,
     ILoggerFactory loggerFactory) : base(compiler, fileProviderAccessor, optionsAccessor, loggerFactory)
 {
 }
예제 #43
0
 public void CanCompile()
 {
     CompilerSettings s = new CompilerSettings();
       CSharpCompiler c = new CSharpCompiler(s);
       Assert.True(c.CanCompileFile(@"..\..\etc\testdata\compiler\compile_ok.cs"));
 }
        /// <summary>
        /// Builds the expected base of touched files.
        /// Adds a hook for temporary file creation as well,
        /// so this method must be called before the execution of
        /// Csc.Run.
        /// </summary>
        private static void BuildTouchedFiles(CSharpCompiler cmd,
                                              string outputPath,
                                              out List<string> expectedReads,
                                              out List<string> expectedWrites)
        {
            expectedReads = cmd.Arguments.MetadataReferences
                .Select(r => r.Reference).ToList();

            foreach (var file in cmd.Arguments.SourceFiles)
            {
                expectedReads.Add(file.Path);
            }

            var writes = new List<string>();
            writes.Add(outputPath);

            expectedWrites = writes;
        }