예제 #1
0
        public void Compile(string code, string assemblyName)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new ArgumentException("code");
            }
            if (string.IsNullOrEmpty(assemblyName))
            {
                throw new ArgumentNullException("assemblyName");
            }

            string path = Environment.CurrentDirectory;
            string semanticLibPath = Path.Combine(path, "SemanticLib.dll");
            AssemblyFileReference semanticLib = new AssemblyFileReference(semanticLibPath);
            AssemblyFileReference mscorlib = new AssemblyFileReference(typeof(object).Assembly.Location);

            string newCode = @"using SemanticLib; using SemanticLib.Core; using SemanticLib.Plugins; namespace Script { class Program { public static void Main() { " + code + "} } }";
            SyntaxTree tree = SyntaxTree.ParseCompilationUnit(newCode);
            Compilation compilation = Compilation.Create(
                outputName: assemblyName,
                options: new CompilationOptions(assemblyKind: AssemblyKind.DynamicallyLinkedLibrary),
                syntaxTrees: new[] { tree },
                references: new MetadataReference[] { mscorlib, semanticLib });

            string assemblyNameWithExtension = string.Format("{0}.exe", assemblyName);
            var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Save);
            var module = assembly.DefineDynamicModule(assemblyName, assemblyNameWithExtension, true);
            var result = compilation.Emit(module);
            Type programClass = module.GetType("Script.Program");
            MethodInfo mainMethod = programClass.GetMethod("Main");

            assembly.SetEntryPoint(mainMethod, PEFileKinds.ConsoleApplication);
            assembly.Save(assemblyNameWithExtension, PortableExecutableKinds.NotAPortableExecutableImage, ImageFileMachine.I386);
        }
        public static string Generate <T>(this T @this)
        {
            var code = "new StringBuilder()" +
                       string.Join(".Append(\" || \")",
                                   from property in @this.GetType().GetProperties(
                                       BindingFlags.Instance | BindingFlags.Public)
                                   where property.CanRead
                                   select string.Format(".Append(\"{0}: \").Append(Target.{0})",
                                                        property.Name)) + ".ToString()";

            var hostReference =
                new AssemblyFileReference(typeof(ToStringViaRoslynExtensions).Assembly.Location);
            var engine = new ScriptEngine(
                references: new[] { hostReference },
                importedNamespaces: new[] { "System", "System.Text" });
            var host    = new Host <T>(@this);
            var session = Session.Create(host);

            return(engine.Execute <string>(code, session));
        }
예제 #3
0
 private void CreateSafeControls(AssemblyDefinition assembly, AssemblyFileReference assemblyFileReference)
 {
     try
     {
         // Add the safe controls for the assembly
         assemblyFileReference.SafeControls = BuildSafeControlDefinition(assembly, assemblyFileReference.SafeControls);
     }
     catch
     {
         // Throw an exception with a better description
         if (_resoleveException != null)
         {
             throw _resoleveException;
         }
         else
         {
             throw;
         }
     }
 }
예제 #4
0
        private static Assembly CompileCodeIntoAssemblyUsingRoslyn(string code, string assemblyName)
        {
            var syntaxTree = SyntaxTree.ParseCompilationUnit(code);

            var mscorlib = new AssemblyFileReference(typeof(object).Assembly.Location);

            var compilationOptions = new CompilationOptions(assemblyKind: AssemblyKind.DynamicallyLinkedLibrary);

            var compilation = Compilation.Create(assemblyName, compilationOptions, new[] { syntaxTree }, new[] { mscorlib });

            var memStream = new MemoryStream();
            var emitResult = compilation.Emit(memStream);

            if (!emitResult.Success) {
                foreach (Diagnostic diagnostic in emitResult.Diagnostics) {
                    Console.WriteLine(diagnostic.Info.ToString());
                }
            }

            return Assembly.Load(memStream.GetBuffer());
        }
예제 #5
0
        public AssemblyFileReference[] BuildAssemblyFileReference(Dictionary <string, AssemblyInfo> assembliesFound)
        {
            // Temporary list
            this.AssemblyFileReferenceCollection = new Dictionary <string, AssemblyFileReference>(StringComparer.OrdinalIgnoreCase);

            // Add existing Assembly References from Manifest.config into the temporary list AssemblyFileReferenceCollection
            if (this.Solution.Assemblies != null)
            {
                foreach (AssemblyFileReference item in this.Solution.Assemblies)
                {
                    this.AssemblyFileReferenceCollection.Add(item.Location, item);
                }
            }

            //
            foreach (KeyValuePair <string, AssemblyInfo> assemblyEntry in assembliesFound)
            {
                // Create the AssemblyFileReference or use the one from the temporary list
                AssemblyFileReference reference = CreateAssemblyFileReference(assemblyEntry.Value);

                // Add the assembly Reference if it is not already is in the temporary list
                if (reference != null && !this.AssemblyFileReferenceCollection.ContainsKey(reference.Location))
                {
                    this.AssemblyFileReferenceCollection.Add(reference.Location, reference);
                }

                // Add the assembly to the CAB file list
                this.AddToCab(assemblyEntry.Value.FileHandle.FullName, assemblyEntry.Value.Key);
            }

            if (this.AssemblyFileReferenceCollection.Count == 0)
            {
                return(null);
            }

            AssemblyFileReference[] result = new AssemblyFileReference[this.AssemblyFileReferenceCollection.Values.Count];
            this.AssemblyFileReferenceCollection.Values.CopyTo(result, 0);

            return(result);
        }
예제 #6
0
        private AssemblyFileReference CreateManagedAssemblyFileReference(AssemblyInfo assemblyInfo)
        {
            Log.Verbose(string.Format("Adding assembly: {0}", assemblyInfo.Key));


            AssemblyFileReference assemblyFileReference = null;

            if (this.AssemblyFileReferenceCollection.ContainsKey(assemblyInfo.Key))
            {
                // Use an existing Assembly Reference from the Temporary List
                assemblyFileReference = this.AssemblyFileReferenceCollection[assemblyInfo.Key];
            }
            else
            {
                // Create a new Assembly Reference, it will be added later.
                assemblyFileReference = new AssemblyFileReference(assemblyInfo, GetDeploymentTarget(assemblyInfo.TargetType));
            }

            // Load the assembly into Cecil object model 'AssemblyDefinition'
            AssemblyDefinition assembly = AssemblyStore.GetAssembly(assemblyInfo.FileHandle.FullName, this.DLLReferencePath.FullName);

            if (assembly != null)
            {
                assemblyFileReference.AssemblyObject = assembly;

                // Build the safecontrols if the assembly is not a Resource or a reference dll
                if (this.BuildSafeControls)
                {
                    CreateSafeControls(assembly, assemblyFileReference);
                }

                // Add the class resources
                ClassResourceDefinition[] definitions = BuildClassResourceDefinition(assemblyInfo.FileHandle);
                assemblyFileReference.ClassResources = AppendArray <ClassResourceDefinition>(assemblyFileReference.ClassResources, definitions);
            }

            return(assemblyFileReference);
        }
예제 #7
0
        /// <summary>
        /// Creates a AssemblyFileReference object based on the parameters.
        /// It will also auto build the SafeControl objects.
        /// </summary>
        private AssemblyFileReference CreateAssemblyFileReference(AssemblyInfo assemblyInfo)
        {
            AssemblyFileReference assemblyFileReference = null;

            if (!assemblyInfo.Resource)
            {
                if (!assemblyInfo.Reference)
                {
                    if (assemblyInfo.Managed)
                    {
                        // Create normal dll reference
                        assemblyFileReference = CreateManagedAssemblyFileReference(assemblyInfo);
                    }
                    else
                    {
                        // Create Unmanaged reference
                        assemblyFileReference = new AssemblyFileReference(assemblyInfo, SolutionDeploymentTargetType.WebApplication);
                        Log.Verbose(string.Format("Unmanaged Assembly added: {0}", assemblyInfo.Key));
                    }
                }
                else
                {
                    // Add the assembly as a ResourceDLL
                    assemblyFileReference = new AssemblyFileReference(assemblyInfo, GetDeploymentTarget(assemblyInfo.TargetType));
                    Log.Verbose(string.Format("Reference Assembly added: {0}", assemblyInfo.Key));
                }
            }
            else
            {
                // Create Resource reference
                SolutionDeploymentTargetType targetType = (assemblyInfo.Managed) ? assemblyInfo.TargetType : SolutionDeploymentTargetType.WebApplication;
                assemblyFileReference = new AssemblyFileReference(assemblyInfo, targetType);
                Log.Verbose(string.Format("Resource Assembly added: {0}", assemblyInfo.Key));
            }

            return(assemblyFileReference);
        }
예제 #8
0
        public static string Complete(string code, int position, int line, int ch)
        {
            JavaScriptSerializer json = new JavaScriptSerializer();
            try
            {
                position--;
                bool is_using = false;
                string[] lines = code.Split("\n".ToCharArray(), StringSplitOptions.None);
                string l = lines[line];
                if ((new Regex(@"^\s*using\s+[^(]+")).IsMatch(l))
                    is_using = true;

                if (code[position] != '.')
                {
                    while (code[position] != '.' && "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_".Count(f => f == code[position]) != 0)
                    {
                        position--;
                    }
                    if (code[position] != '.')
                        return json.Serialize(new List<string>());
                }
                if (is_using)
                {
                    for (int i = position; code[i] != '\n'; )
                        code = code.Remove(i, 1);
                }
                else
                {
                    code = code.Insert(position, " ");
                }

                var tree = Roslyn.Compilers.CSharp.SyntaxTree.ParseCompilationUnit(code);
                var mscorlib = new AssemblyFileReference(typeof(object).Assembly.Location);
                var core = new AssemblyFileReference(typeof(Queryable).Assembly.Location);
                var data = new AssemblyFileReference(typeof(System.Data.DataTable).Assembly.Location);
                var xml = new AssemblyFileReference(typeof(System.Xml.XmlAttribute).Assembly.Location);
                var xml_linq = new AssemblyFileReference(typeof(System.Xml.Linq.XAttribute).Assembly.Location);
                var c_sharp = new AssemblyFileReference(typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly.Location);
                var anot = new AssemblyFileReference(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute).Assembly.Location);
                var comp = new AssemblyFileReference(typeof(System.ComponentModel.Composition.ImportAttribute).Assembly.Location);
                var web = new AssemblyFileReference(typeof(System.Web.HttpRequest).Assembly.Location);
                var http = new AssemblyFileReference(typeof(System.Net.Http.HttpClient).Assembly.Location);
                var numerics = new AssemblyFileReference(typeof(System.Numerics.BigInteger).Assembly.Location);
                var drawing = new AssemblyFileReference(typeof(System.Drawing.Image).Assembly.Location);
                //var newton_json = new AssemblyFileReference(typeof(Newtonsoft.Json.JsonSerializer).Assembly.Location);

                var compilation = Roslyn.Compilers.CSharp.Compilation.Create(
                    "MyCompilation",
                    syntaxTrees: new[] { tree },
                    references: new[] { mscorlib, core, data, xml, xml_linq, c_sharp, anot, comp, web, http, numerics, drawing/*, newton_json*/ });

                var semanticModel = compilation.GetSemanticModel(tree);

                var p = tree.GetRoot().FindToken(position).Parent;

                if (is_using)
                {
                    var usn = p.AncestorsAndSelf().OfType<UsingDirectiveSyntax>().FirstOrDefault();
                    if (usn != null)
                    {
                        List<string> namespaces = new List<string>();
                        var nameInfo = semanticModel.GetSymbolInfo(usn.Name);
                        var systemSymbol = (NamespaceSymbol)nameInfo.Symbol;
                        foreach (var ns in systemSymbol.GetNamespaceMembers())
                            namespaces.Add(ns.Name);

                        return json.Serialize(namespaces);
                    }
                    else
                        return json.Serialize(new List<string>());
                }

                ExpressionSyntax identifier = p as ExpressionSyntax;
                if (p is MemberAccessExpressionSyntax)
                {
                    identifier = p.ChildNodes().FirstOrDefault() as ExpressionSyntax;
                }

                if (identifier == null)
                    identifier = p as LiteralExpressionSyntax;
                if (identifier == null)
                    identifier = p as ParenthesizedExpressionSyntax;

                if (identifier == null)
                    identifier = p.Parent as InvocationExpressionSyntax;

                if (identifier == null)
                    identifier = p.Parent as ObjectCreationExpressionSyntax;

                if (identifier == null)
                    return json.Serialize(new List<string>());

                var semanticInfo = semanticModel.GetTypeInfo(identifier);
                var type = semanticInfo.Type;

                var symbols = semanticModel.LookupSymbols(position, container: type,
                                                                    options: LookupOptions.IncludeExtensionMethods | LookupOptions.Default);

                List<string> res = new List<string>();
                foreach (var symbol in symbols)
                {
                    var result = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
                    if (symbol.Kind == SymbolKind.Method)
                    {
                        result = result.Substring(result.IndexOf(" ")); //cut return type
                    }
                    result = result.Substring(result.IndexOf(".") + 1); //cut containing type
                    if (symbol.Kind == SymbolKind.Method)
                    {
                        var prefix = result.Substring(0, result.IndexOf('(')); //cut redundant generics info
                        prefix = prefix.Substring(0, prefix.IndexOf('<') == -1 ? prefix.Length : prefix.IndexOf('<'));
                        result = prefix + result.Substring(result.IndexOf('('));
                    }
                    //if (result.Length > 100)
                    //{
                    //    result = result.Substring(0, 100) + " ...";
                    //    if (symbol.Kind == SymbolKind.Method)
                    //        result += ")";
                    //}
                    if (!res.Contains(result))
                        res.Add(result);
                }
                res.Sort();

                return json.Serialize(res);
            }
            catch (Exception e)
            {
                //Utils.Log.LogInfo(e.Message+"\n\n\n"+code, "code completion error, position: "+position);
                return json.Serialize(new List<string>());
            }
        }
예제 #9
0
        public static string Complete(string code, int position, int line, int ch)
        {
            JavaScriptSerializer json = new JavaScriptSerializer();

            try
            {
                position--;
                bool     is_using = false;
                string[] lines    = code.Split("\n".ToCharArray(), StringSplitOptions.None);
                string   l        = lines[line];
                if ((new Regex(@"^\s*using\s+[^(]+")).IsMatch(l))
                {
                    is_using = true;
                }

                if (code[position] != '.')
                {
                    while (code[position] != '.' && "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_".Count(f => f == code[position]) != 0)
                    {
                        position--;
                    }
                    if (code[position] != '.')
                    {
                        return(json.Serialize(new List <string>()));
                    }
                }
                if (is_using)
                {
                    for (int i = position; code[i] != '\n';)
                    {
                        code = code.Remove(i, 1);
                    }
                }
                else
                {
                    code = code.Insert(position, " ");
                }


                var tree     = Roslyn.Compilers.CSharp.SyntaxTree.ParseCompilationUnit(code);
                var mscorlib = new AssemblyFileReference(typeof(object).Assembly.Location);
                var core     = new AssemblyFileReference(typeof(Queryable).Assembly.Location);
                var data     = new AssemblyFileReference(typeof(System.Data.DataTable).Assembly.Location);
                var xml      = new AssemblyFileReference(typeof(System.Xml.XmlAttribute).Assembly.Location);
                var xml_linq = new AssemblyFileReference(typeof(System.Xml.Linq.XAttribute).Assembly.Location);
                var c_sharp  = new AssemblyFileReference(typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly.Location);
                var anot     = new AssemblyFileReference(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute).Assembly.Location);
                var comp     = new AssemblyFileReference(typeof(System.ComponentModel.Composition.ImportAttribute).Assembly.Location);
                var web      = new AssemblyFileReference(typeof(System.Web.HttpRequest).Assembly.Location);
                var http     = new AssemblyFileReference(typeof(System.Net.Http.HttpClient).Assembly.Location);
                var numerics = new AssemblyFileReference(typeof(System.Numerics.BigInteger).Assembly.Location);
                var drawing  = new AssemblyFileReference(typeof(System.Drawing.Image).Assembly.Location);
                //var newton_json = new AssemblyFileReference(typeof(Newtonsoft.Json.JsonSerializer).Assembly.Location);

                var compilation = Roslyn.Compilers.CSharp.Compilation.Create(
                    "MyCompilation",
                    syntaxTrees: new[] { tree },
                    references: new[] { mscorlib, core, data, xml, xml_linq, c_sharp, anot, comp, web, http, numerics, drawing /*, newton_json*/ });

                var semanticModel = compilation.GetSemanticModel(tree);

                var p = tree.GetRoot().FindToken(position).Parent;

                if (is_using)
                {
                    var usn = p.AncestorsAndSelf().OfType <UsingDirectiveSyntax>().FirstOrDefault();
                    if (usn != null)
                    {
                        List <string> namespaces   = new List <string>();
                        var           nameInfo     = semanticModel.GetSymbolInfo(usn.Name);
                        var           systemSymbol = (NamespaceSymbol)nameInfo.Symbol;
                        foreach (var ns in systemSymbol.GetNamespaceMembers())
                        {
                            namespaces.Add(ns.Name);
                        }

                        return(json.Serialize(namespaces));
                    }
                    else
                    {
                        return(json.Serialize(new List <string>()));
                    }
                }


                ExpressionSyntax identifier = p as ExpressionSyntax;
                if (p is MemberAccessExpressionSyntax)
                {
                    identifier = p.ChildNodes().FirstOrDefault() as ExpressionSyntax;
                }

                if (identifier == null)
                {
                    identifier = p as LiteralExpressionSyntax;
                }
                if (identifier == null)
                {
                    identifier = p as ParenthesizedExpressionSyntax;
                }

                if (identifier == null)
                {
                    identifier = p.Parent as InvocationExpressionSyntax;
                }

                if (identifier == null)
                {
                    identifier = p.Parent as ObjectCreationExpressionSyntax;
                }

                if (identifier == null)
                {
                    return(json.Serialize(new List <string>()));
                }

                var semanticInfo = semanticModel.GetTypeInfo(identifier);
                var type         = semanticInfo.Type;

                var symbols = semanticModel.LookupSymbols(position, container: type,
                                                          options: LookupOptions.IncludeExtensionMethods | LookupOptions.Default);

                List <string> res = new List <string>();
                foreach (var symbol in symbols)
                {
                    var result = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
                    if (symbol.Kind == SymbolKind.Method)
                    {
                        result = result.Substring(result.IndexOf(" ")); //cut return type
                    }
                    result = result.Substring(result.IndexOf(".") + 1); //cut containing type
                    if (symbol.Kind == SymbolKind.Method)
                    {
                        var prefix = result.Substring(0, result.IndexOf('(')); //cut redundant generics info
                        prefix = prefix.Substring(0, prefix.IndexOf('<') == -1 ? prefix.Length : prefix.IndexOf('<'));
                        result = prefix + result.Substring(result.IndexOf('('));
                    }
                    //if (result.Length > 100)
                    //{
                    //    result = result.Substring(0, 100) + " ...";
                    //    if (symbol.Kind == SymbolKind.Method)
                    //        result += ")";
                    //}
                    if (!res.Contains(result))
                    {
                        res.Add(result);
                    }
                }
                res.Sort();

                return(json.Serialize(res));
            }
            catch (Exception e)
            {
                //Utils.Log.LogInfo(e.Message+"\n\n\n"+code, "code completion error, position: "+position);
                return(json.Serialize(new List <string>()));
            }
        }