Exemplo n.º 1
0
        /// <summary>
        /// Creates an instance of T
        /// </summary>
        /// <typeparam name="T">The type of object to create</typeparam>
        /// <param name="name">Name of the class</param>
        /// <returns>A reference to the newly created object.</returns>
        public T CreateInstance <T>(string name) where T : class
        {
            if (!IsCompiled)
            {
                Trace.WriteLine("Script \"" + Name + "\" is not compiled. Can't create a new instance \"" + name + "\" of type \"" + typeof(T).Name + "\"");
                return(default(T));
            }

            // Get type
            Type t = CompiledAssembly.GetType(name);

            if (t == null)
            {
                Trace.WriteLine("Type \"" + name + "\" not found.");
                return(default(T));
            }


            // Check interface
            if (!typeof(T).IsAssignableFrom(t))
            {
                Trace.WriteLine("Type \"" + name + "\" found, but not an instance of \"" + typeof(T).Name + "\".");
                return(default(T));
            }


            // Create an instance
            return(Activator.CreateInstance(t) as T);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets all class implementing an interface
        /// </summary>
        /// <param name="type">Type of the interface or null for evey interfaces</param>
        /// <returns>List of classes</returns>
        public List <string> GetImplementedInterfaces(Type type)
        {
            List <string> list = new List <string>();

            if (!IsCompiled)
            {
                Compile();
            }


            if (CompiledAssembly == null)
            {
                return(list);
            }

            // Loop through types looking for one that implements the given interface
            foreach (Type t in CompiledAssembly.GetTypes())
            {
                foreach (Type ty in t.GetInterfaces())
                {
                    if (ty == type || type == null)
                    {
                        list.Add(t.Name);
                    }
                }
            }

            list.Sort();

            return(list);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Gets a list of specific methods
        /// </summary>
        /// <param name="types">An array of type's parameters</param>
        /// <param name="ret">Retrun value</param>
        /// <returns></returns>
        public List <string> GetMethods(Type[] types, Type ret)
        {
            List <string> list = new List <string>();

            if (!IsCompiled)
            {
                Compile();
            }


            if (CompiledAssembly == null)
            {
                return(list);
            }

            // Loop through types looking for one that implements the given interface
            foreach (Type t in CompiledAssembly.GetTypes())
            {
                foreach (MethodInfo m in t.GetMethods())
                {
                    // return value
                    if (m.ReturnType != ret)
                    {
                        continue;
                    }

                    // Parameters
                    bool ok = false;
                    int  id = 0;
                    foreach (ParameterInfo pi in m.GetParameters())
                    {
                        // Index overrun
                        if (id >= types.Length)
                        {
                            ok = false;
                            break;
                        }

                        // Parameters differents
                        if (pi.ParameterType != types[id])
                        {
                            ok = false;
                            break;
                        }

                        ok = true;

                        // Next
                        id++;
                    }

                    if (ok && id == types.Length)
                    {
                        list.Add(m.Name);
                    }
                }
            }

            return(list);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Returns all methods
        /// </summary>
        /// <returns>Returns a list of method's name</returns>
        public List <string> GetMethods()
        {
            List <string> list = new List <string>();

            if (!IsCompiled)
            {
                Compile();
            }


            if (CompiledAssembly == null)
            {
                return(list);
            }

            // Loop through types looking for one that implements the given interface
            foreach (Type t in CompiledAssembly.GetTypes())
            {
                foreach (MethodInfo m in t.GetMethods())
                {
                    list.Add(m.Name);
                }
            }

            list.Sort();

            return(list);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Invoke a method in the script
        /// </summary>
        /// <param name="method">Method's name</param>
        /// <param name="args">Arguments</param>
        /// <returns>true if args or false</returns>
        // http://msdn.microsoft.com/en-us/library/3y322t50%28v=VS.90%29.aspx => Reflection.Emmit()
        public bool Invoke(string method, params object[] args)
        {
            if (!IsCompiled)
            {
                Trace.WriteLine("Invoking method \"" + method + "\" on uncompiled script \"" + Name + "\"");
                return(false);
            }



            try
            {
                Type[]       type = CompiledAssembly.GetTypes();
                MethodInfo[] mi   = type[0].GetMethods();

                object instance = Activator.CreateInstance(type[0]);
                object result   = type[0].InvokeMember(method,
                                                       BindingFlags.Default | BindingFlags.InvokeMethod,
                                                       null,
                                                       instance,
                                                       args);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception invoking \"" + method + "\" on uncompiled script \"" + Name + "\" : " + e.Message);
            }

            return(true);
        }
Exemplo n.º 6
0
 public object executeFirstMethod()
 {
     if (CompiledAssembly.notNull())
     {
         var parametersValues = InvocationParameters.valuesArray();
         return(CompiledAssembly.executeFirstMethod(ExecuteInStaThread, ExecuteInMtaThread, parametersValues));
     }
     return(null);
 }
Exemplo n.º 7
0
        internal static void Process(string name, byte[] peData, byte[] pdbData, string[] defines, string[] references)
        {
            var compiledAssembly = new CompiledAssembly
            {
                Name             = name,
                InMemoryAssembly = new InMemoryAssembly(peData, pdbData),
                Defines          = defines,
                References       = references
            };

            new PostProcessor().Process(compiledAssembly);
        }
Exemplo n.º 8
0
    static bool ProcessArgs(string[] args)
    {
        bool success = true;

        try
        {
            var options = new Options();

            OptionSet optionSet = new OptionSet()
                                  .Add("a|assembly=", a => { options.AssemblyPath = a; })
                                  .Add("o|outputDir=", a => { options.OutputDir = a; })
                                  .Add("p|processors=", a => options.ILPostProcessorPaths           = a.Split(','))
                                  .Add("f|assemblyFolders=", a => options.AssemblyFolderPaths       = a.Split(','))
                                  .Add("r|assemblyReferences=", a => options.ReferenceAssemblyPaths = a.Split(','))
                                  .Add("d|defines=", a => options.Defines = a.Split(','));
            optionSet.Parse(args);

            AssemblyFolderPaths = options.AssemblyFolderPaths.ToArray();

            NamedILPostProcessors = options.ILPostProcessorPaths
                                    .Select(p => Assembly.LoadFrom(p))
                                    .SelectMany(asm => asm.GetTypes().Where(t => typeof(ILPostProcessor).IsAssignableFrom(t)))
                                    .Select(t => new NamedILPostProcessorWrapper(t.FullName, (ILPostProcessor)Activator.CreateInstance(t)))
                                    .ToArray();

            OutputAsmPath = Path.Combine(options.OutputDir, Path.GetFileName(options.AssemblyPath));
            OutputPdbPath = Path.ChangeExtension(OutputAsmPath, "pdb");
            InputAssembly = new CompiledAssembly(options.AssemblyPath, options.ReferenceAssemblyPaths.ToArray(), options.Defines?.ToArray() ?? Array.Empty <string>());
        }
        catch (Exception e)
        {
            var rtle = e as ReflectionTypeLoadException;

            if (rtle == null)
            {
                throw;
            }

            Console.Error.WriteLine("ILPostProcessorRunner caught the following exception while processing arguments:\n" + e);

            if (rtle != null)
            {
                foreach (Exception inner in rtle.LoaderExceptions)
                {
                    Console.Error.WriteLine(inner);
                }
            }

            success = false;
        }

        return(success);
    }
Exemplo n.º 9
0
        /// <summary>
        /// Create an instance of the specified type, adding it to the Instances collection.
        /// </summary>
        public IRuntimeSemanticType Create(string typeName, IRuntimeSemanticType parent = null)
        {
            Assert.That(SemanticTypes.ContainsKey(typeName), "The semantic type " + typeName + " has not been declared.");
            IRuntimeSemanticType t = (IRuntimeSemanticType)CompiledAssembly.CreateInstance("SemanticTypes." + typeName);

            t.Initialize(this);
            Guid guid = Guid.NewGuid();                                 // We create a unique key for this instance.

            Instances[guid] = (new SemanticTypeInstance()
            {
                Name = typeName, Instance = t, Parent = parent, Key = guid, Definition = SemanticTypes[typeName]
            });

            NewSemanticType.Fire(this, new NewSemanticTypeEventArgs(t));

            return(t);
        }
Exemplo n.º 10
0
        public static Assembly CompileScreenSouceCode(String strSourceCode, String strViewNo)
        {
            if (System.IO.Directory.Exists(@"Temp") == false)
            {
                System.IO.Directory.CreateDirectory(@"Temp");
            }

            iCount++;

            CompiledAssembly ass = (CompiledAssembly)Compiler.CompileAssembly(strSourceCode, CodeType.CSharp, String.Format(@"TempScreen{0}_{1}.dll", strViewNo, iCount),
                                                                              new string[] { "System.dll", "System.Data.dll", "System.Core.dll", "Microsoft.CSharp.dll", "System.Drawing.dll", "System.Windows.Forms.dll", "ABCBaseScreen.dll", "dll", "ABCControls.dll", "ABCStudio.exe", "ABCApp.exe", "BaseObjects.dll", "BusinessObjects.dll",
                                                                                             "DevExpress.Data.v12.1.dll", "DevExpress.Utils.v12.1.dll", "DevExpress.XtraBars.v12.1.dll", "DevExpress.XtraEditors.v12.1.dll" });

            if (ass == null || ass.Errors.Errors.Length > 0)
            {
                return(null);
            }

            return(ass.Assembly);
        }
Exemplo n.º 11
0
    static bool ProcessArgs(string[] args)
    {
        bool success = true;

        try
        {
            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(o =>
            {
                NamedILPostProcessors = o.ILPostProcessorPaths
                                        .Select(p => Assembly.LoadFrom(p))
                                        .SelectMany(asm => asm.GetTypes().Where(t => typeof(ILPostProcessor).IsAssignableFrom(t)))
                                        .Select(t => new NamedILPostProcessorWrapper(t.FullName, (ILPostProcessor)Activator.CreateInstance(t)))
                                        .ToArray();

                var assemblyPath = args[0];
                OutputAsmPath    = Path.Combine(o.OutputDir, Path.GetFileName(assemblyPath));
                OutputPdbPath    = Path.ChangeExtension(OutputAsmPath, "pdb");
                InputAssembly    = new CompiledAssembly(assemblyPath, o.ReferenceAssemblyPaths.ToArray(), o.ScriptingDefines.ToArray());
            });
        }
        catch (Exception e)
        {
            Console.WriteLine("ILPostProcessorRunner caught the following exception while processing arguments:\n" + e);

            var rtle = e as ReflectionTypeLoadException;
            if (rtle != null)
            {
                foreach (Exception inner in rtle.LoaderExceptions)
                {
                    Console.WriteLine(inner);
                }
            }

            success = false;
        }

        return(success);
    }
Exemplo n.º 12
0
        private void EmitContentFiles(string outDir)
        {
            if (string.IsNullOrEmpty(_cSharpProject.FilePath))
            {
                return;
            }
            var p            = Project1.Load(_cSharpProject.FilePath);
            var contentFiles = (from i in p.Items
                                where i.BuildAction == BuildActions.Content
                                select PathUtil.MakeWinPath(i.Name, PathUtil.SeparatorProcessing.Append)).ToArray();

            if (!contentFiles.Any())
            {
                return;
            }
            var attr   = CompiledAssembly.GetCustomAttribute <ResourcesDirectoryAttribute>();
            var srcDir = PathUtil.MakeWinPath(attr == null ? null : attr.Source, PathUtil.SeparatorProcessing.Append,
                                              PathUtil.SeparatorProcessing.Append).ToLower();
            var dstDir = PathUtil.MakeWinPath(attr == null ? null : attr.Destination,
                                              PathUtil.SeparatorProcessing.Append, PathUtil.SeparatorProcessing.Append);
            // ReSharper disable once PossibleNullReferenceException
            var projectDir = new FileInfo(_cSharpProject.FilePath).Directory.FullName;

            foreach (var fileName in contentFiles)
            {
                if (!fileName.ToLower().StartsWith(srcDir))
                {
                    continue;
                }
                var relDestFilename = dstDir + fileName.Substring(srcDir.Length);
                var dstFile         = Path.Combine(outDir, relDestFilename.Substring(1));
                var srcFile         = Path.Combine(projectDir, fileName.Substring(1));
                Console.WriteLine("copy {0} to {1}", fileName, relDestFilename);
                // ReSharper disable once PossibleNullReferenceException
                new FileInfo(dstFile).Directory.Create();
                File.Copy(srcFile, dstFile, true);
            }
        }
Exemplo n.º 13
0
        private AssemblyLoadResult CompileInMemory(string name, Compilation compilation, IEnumerable <ResourceDescription> resources)
        {
            using (var pdbStream = new MemoryStream())
                using (var assemblyStream = new MemoryStream())
                {
#if DESKTOP
                    EmitResult result = compilation.Emit(assemblyStream, pdbStream: pdbStream, manifestResources: resources);
#else
                    EmitResult result = compilation.Emit(assemblyStream);
#endif

                    if (!result.Success)
                    {
                        return(ReportCompilationError(result));
                    }

                    var assemblyBytes = assemblyStream.ToArray();

#if DESKTOP
                    var pdbBytes = pdbStream.ToArray();
#endif

                    var compiled = new CompiledAssembly
                    {
#if DESKTOP
                        Assembly = Assembly.Load(assemblyBytes, pdbBytes),
#else
                        Assembly = Assembly.Load(assemblyBytes),
#endif
                        MetadataReference = compilation.ToMetadataReference()
                    };

                    _compiledAssemblies[name] = compiled;

                    return(new AssemblyLoadResult(compiled.Assembly));
                }
        }
Exemplo n.º 14
0
        private static bool Run(Options options)
        {
            TypeCollection totalTypeCollection;

            try
            {
                totalTypeCollection = LoadAll(options);
            }
            catch (IOException e)
            {
                Console.WriteLine("Error loading files: " + e.Message);
                return(false);
            }

            options.Log("Preparing output template C# source code.");

            string template = Assembly.GetExecutingAssembly()
                              .GetEmbeddedResourceText("Crossdox/DefaultTemplates/SingleDocument.template");

            string sourceCode = SourceCodeGenerator.CreateFullSourceFile(template,
                                                                         "SingleDocument.template",
                                                                         new[]
            {
                new TemplateArg(typeof(NameInfo), "RootNamespace"),
                new TemplateArg(typeof(TypeCollection), "Types")
            },
                                                                         includeName =>
            {
                string includeText = Assembly.GetExecutingAssembly()
                                     .GetEmbeddedResourceText("Crossdox/DefaultTemplates/" + includeName);
                return(includeText);
            }
                                                                         );

            options.Log("Compiling output template source code.");

            string crossdoxCacheFolder             = Path.Combine(Path.GetTempPath(), "crossdox");
            CompiledAssemblyCache assemblyCache    = new CompiledAssemblyCache(crossdoxCacheFolder);
            CompiledAssembly      compiledAssembly = assemblyCache.LoadOrCompile(options, sourceCode, "SingleDocument.template");

            if (compiledAssembly.HasErrors)
            {
                foreach (string error in compiledAssembly.Errors)
                {
                    Console.Error.WriteLine("Error compiling script: " + error);
                }
                return(false);
            }

            Assembly assembly = compiledAssembly.ToAssembly();

            options.Log("Reflecting against template assembly.");

            Type            compiledTemplate         = assembly.GetType("TemplateScript.CompiledTemplate");
            ConstructorInfo constructor              = compiledTemplate.GetConstructor(Type.EmptyTypes);
            object          compiledTemplateInstance = constructor.Invoke(new object[0]);

            MethodInfo runMethod = compiledTemplate.GetMethod("Run");

            object[] runArgs = new object[]
            {
                new NameInfo(null, "Test", null, null, default),
                totalTypeCollection,
            };

            options.Log("Invoking template assembly Run() method.");

            string result;

            try
            {
                result = (string)runMethod.Invoke(compiledTemplateInstance, runArgs);
            }
            catch (TargetInvocationException e)
            {
                if (e.InnerException != null)
                {
                    Console.Error.WriteLine("Error running script: " + e.InnerException);
                }
                else
                {
                    Console.Error.WriteLine("Error running script: " + e);
                }
                return(false);
            }

            if (result != null)
            {
                Console.WriteLine(result);
            }

            return(true);
        }
Exemplo n.º 15
0
        private AssemblyLoadResult CompileInMemory(string name, Compilation compilation, IEnumerable<ResourceDescription> resources)
        {
            using (var pdbStream = new MemoryStream())
            using (var assemblyStream = new MemoryStream())
            {
            #if DESKTOP
                EmitResult result = compilation.Emit(assemblyStream, pdbStream: pdbStream, manifestResources: resources);
            #else
                EmitResult result = compilation.Emit(assemblyStream);
            #endif

                if (!result.Success)
                {
                    return ReportCompilationError(result);
                }

                var assemblyBytes = assemblyStream.ToArray();

            #if DESKTOP
                var pdbBytes = pdbStream.ToArray();
            #endif

                var compiled = new CompiledAssembly
                {
            #if DESKTOP
                    Assembly = Assembly.Load(assemblyBytes, pdbBytes),
            #else
                    Assembly = Assembly.Load(assemblyBytes),
            #endif
                    MetadataReference = compilation.ToMetadataReference()
                };

                _compiledAssemblies[name] = compiled;

                return new AssemblyLoadResult(compiled.Assembly);
            }
        }