Beispiel #1
0
        public CompileResult Compile()
        {
            var result = new CompileResult();

            //var assemblyPath = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
            var assemblyName = Guid.NewGuid().ToString();

            this.Source = CleanSource(this.Source);

            var syntaxTrees = CSharpSyntaxTree.ParseText(this.Source);

            // set up compilation
            var compilation = CSharpCompilation.Create(assemblyName)
                .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                .AddReferences(references)
                .AddSyntaxTrees(syntaxTrees);

            // build the assembly
            Assembly assembly = null;

            using (var stream = new MemoryStream())
            {
                // this is broked...
                EmitResult compileResult = compilation.Emit(stream);

                // we get here, with diagnostic errors (check compileResult.Diagnostics)
                if (compileResult.Success)
                {
                    stream.Position = 0;

                    assembly = Accessor.LoadFromStream(stream, null);
                }
                else
                {
                    result.IsValid = false;
                    result.Errors = compileResult.Diagnostics.Select(d => d.ToString());
                }

            }

            if (assembly != null)
            {
                // iterate over the types in the assembly
                var types = assembly.GetExportedTypes();
                if (types.Length == 1)
                {
                    _compiledType = types[0];
                    result.IsValid = true;
                }
                if (types.Length > 1)
                {
                    result.IsValid = false;
                    result.Errors = new[] { "We currently only support a single type through this website. Install GenFu in your own project to generate data for multiple types." };
                }
            }
            _isCompiled = result.IsValid;

            return result;
        }