示例#1
0
        protected override EmitResult Compile(MetadataReference[] references, MemoryStream ms, List <SourceFile> sourceFiles)
        {
            VisualBasicCompilationOptions options = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            IEnumerable <SyntaxTree> syntaxTrees = sourceFiles.Where(x => x.FileName.EndsWith(".vb"))
                                                   .Select(x => SyntaxFactory.ParseSyntaxTree(x.SourceCode));

            VisualBasicCompilation compilation = VisualBasicCompilation.Create("implementation.dll")
                                                 .WithOptions(options)
                                                 .AddSyntaxTrees(syntaxTrees)
                                                 .AddReferences(references);

            return(compilation.Emit(ms));
        }
        /// <summary>
        /// Compiles a Visual Basic source code file.
        /// </summary>
        /// <param name="sourceCodeFilePath">Path to the source code file.</param>
        /// <param name="assemblyFilePath">Path to the destination compiled file.</param>
        /// <returns>Result of the compilation.</returns>
        static EmitResult CompileVisualBasic(string sourceCodeFilePath, string assemblyFilePath)
        {
            string assemblyName = Path.GetFileNameWithoutExtension(assemblyFilePath);

            MetadataReference []          references = GetAssemblyReferences();
            VisualBasicCompilationOptions options    = new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            SyntaxTree [] syntaxTree;
            using (Stream stream = File.OpenRead(sourceCodeFilePath)) {
                syntaxTree = new SyntaxTree [] { VisualBasicSyntaxTree.ParseText(SourceText.From(stream)) };
            }

            VisualBasicCompilation compilation = VisualBasicCompilation.Create(assemblyName, syntaxTree, references, options);

            using (Stream output = File.Create(assemblyFilePath)) {
                return(compilation.Emit(output));
            }
        }
示例#3
0
        protected override EmitResult _Compile(string name, List <MetadataReference> references, string[] imports, string code, ref MemoryStream ms)
        {
            Log.Info("Generating VB Code for script compilation for script element {0}", new object[] { id });
            StringBuilder sbUsing = new StringBuilder();

            foreach (string str in imports)
            {
                sbUsing.AppendFormat("Imports {0}\n", str);
            }
            string ccode = string.Format((_IsCondition ? _CODE_BASE_CONDITION_TEMPLATE : (_IsTimerEvent ? _CODE_BASE_TIMER_EVENT_TEMPLATE : _CODE_BASE_SCRIPT_TEMPLATE)), new object[] {
                sbUsing.ToString(),
                _ClassName,
                _FunctionName,
                code
            });
            List <SyntaxTree> tress = new List <SyntaxTree>();

            tress.Add(SyntaxFactory.SyntaxTree(VisualBasicSyntaxTree.ParseText(ccode).GetRoot()));
            VisualBasicCompilation comp = VisualBasicCompilation.Create(name, tress, references, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            return(comp.Emit(ms));
        }
示例#4
0
        static void VBSample()
        {
            SyntaxTree hostTree = VisualBasicSyntaxTree.ParseText(@"
Namespace VBUserCode
    Class VBUserCodeContext
        Inherits DRTInterfaces.VBUserCodeContextBase
        Public Sub New(record As DRTInterfaces.IRecord)
            MyBase.New(record)
        End Sub
        Sub _Execute()
            
        End Sub
    End Class
End Namespace");

            string     usercode     = @"
For Each i In currentRecord.Rows
    Dim val = ValueReference(i, ""myValue"")
    val.Value = 4
    'val = 4
    System.Console.WriteLine(""Did a thing"")
Next
System.Console.WriteLine(""out of loop"")
Dim foo As Integer = 4
";
            SyntaxTree userCodeTree = VisualBasicSyntaxTree.ParseText(
                usercode, new VisualBasicParseOptions(kind: SourceCodeKind.Script)
                );

            var injectedSyntaxNode = new VBUserCodeInjector(userCodeTree).Visit(hostTree.GetRoot());

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Microsoft.VisualBasic.CompilerServices.NewLateBinding).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(VBUserCodeContextBase).Assembly.Location)
            };

            string assemblyName = Path.GetRandomFileName();
            VisualBasicCompilation compilation = VisualBasicCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { injectedSyntaxNode.SyntaxTree },
                references: references,
                options: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            // new VBVisitor().Visit(injectedSyntaxNode);

            Assembly assembly = null;

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in result.Diagnostics)
                    {
                        Console.Error.WriteLine("{0} - {1}: {2}", diagnostic.Id, diagnostic.Location, diagnostic.GetMessage());
                    }
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    assembly = Assembly.Load(ms.ToArray());
                }
            }

            if (assembly != null)
            {
                var rec = new RecordStub();

                Type type = assembly.GetType("VBUserCode.VBUserCodeContext");
                var  obj  = Activator.CreateInstance(type, new object[] { rec }) as VBUserCodeContextBase;
                type.InvokeMember("_Execute",
                                  BindingFlags.Default | BindingFlags.InvokeMethod,
                                  null,
                                  obj,
                                  null);
            }
        }