Exemple #1
0
 private void CreateAssemblyDefinition(String sAssemblyName, AssemblyKind akAssemblyKind)
 {
     assemblyName       = sAssemblyName;
     assemblyKind       = akAssemblyKind;
     assemblyDefinition = AssemblyFactory.DefineAssembly(sAssemblyName, TargetRuntime.NET_2_0, akAssemblyKind);
     mainModule         = assemblyDefinition.MainModule;
 }
        protected override AssemblyDefinition Generate()
        {
            var assembly = AssemblyFactory.DefineAssembly(AssemblyName, DllName, TargetRuntime.NET_2_0, AssemblyKind.Dll);

            GenerateTypeB(assembly, GenerateTypeA(assembly));
            return(assembly);
        }
        protected override AssemblyDefinition  Generate()
        {
            var assembly = AssemblyFactory.DefineAssembly(DllName, TargetRuntime.NET_2_0, AssemblyKind.Dll);

            var objectTypeRef = assembly.MainModule.Import(typeof(object));
            var module        = assembly.MainModule;

            var xType = new TypeDefinition("X", "", TypeAttributes.Class, objectTypeRef);

            xType.GenericParameters.Add(new GenericParameter("T", xType));
            module.Types.Add(xType);
            xType.Module = module;

            var aType = new TypeDefinition("A", "", TypeAttributes.Class, null);
            var bType = new TypeDefinition("B", "", TypeAttributes.Class, null);

            var aBaseType = new GenericInstanceType(xType);

            aBaseType.GenericArguments.Add(bType);
            aType.BaseType = aBaseType;

            var bBaseType = new GenericInstanceType(xType);

            bBaseType.GenericArguments.Add(aType);
            bType.BaseType = bBaseType;

            module.Types.Add(aType);
            aType.Module = module;

            module.Types.Add(bType);
            bType.Module = module;

            return(assembly);
        }
Exemple #4
0
        public void AssemblyDefinitionMustBeConvertibleToActualAssembly()
        {
            AssemblyDefinition definition = AssemblyFactory.DefineAssembly("testAssembly", AssemblyKind.Dll);

            Assembly assembly = definition.ToAssembly();

            Assert.IsTrue(assembly != null);
        }
Exemple #5
0
        public void DefineAssembly(string name)
        {
            ASM = AssemblyFactory.DefineAssembly(name, AssemblyKind.Console);

            TypeDefinition prog = new TypeDefinition("Program", string.Empty, TypeAttributes.NotPublic, Import(typeof(object)));

            MethodDefinition main = new MethodDefinition("Main", MethodAttributes.Static | MethodAttributes.Private, Import(typeof(void)));

            main.Parameters.Add(new ParameterDefinition(Import(typeof(string []))));

            prog.Methods.Add(main);

            ASM.MainModule.Types.Add(prog);
            ASM.EntryPoint = main;
            _main          = main.Body;
        }
        public void CecilShouldExtractSampleClassFromSignedAssembly()
        {
            var location = typeof(SampleHelloClass).Assembly.Location;

            var sourceAssembly = AssemblyFactory.GetAssembly(location);

            Assert.IsNotNull(sourceAssembly);

            var definition   = AssemblyFactory.DefineAssembly("testAssembly", AssemblyKind.Dll);
            var targetModule = definition.MainModule;

            foreach (TypeDefinition typeDef in sourceAssembly.MainModule.Types)
            {
                // Copy the source type to the target assembly
                targetModule.Inject(typeDef);
            }

            // Convert the new assemblyDef into an actual assembly
            var assembly = definition.ToAssembly();

            Assert.IsNotNull(assembly);

            var types = assembly.GetTypes();

            Assert.IsTrue(types.Length > 0);

            // The imported type must match the original type
            var firstType = types.FirstOrDefault();

            Assert.IsNotNull(firstType);
            Assert.AreEqual(firstType.Name, typeof(SampleHelloClass).Name);

            var instance = Activator.CreateInstance(firstType);

            Assert.IsNotNull(instance);

            var speakMethod = firstType.GetMethod("Speak");

            Assert.IsNotNull(speakMethod);

            speakMethod.Invoke(instance, new object[] { });
        }
Exemple #7
0
        /// <summary>
        /// Creates a proxy type using the given
        /// <paramref name="baseType"/> as the base class
        /// and ensures that the proxy type implements the given
        /// interface types.
        /// </summary>
        /// <param name="baseType">The base class from which the proxy type will be derived.</param>
        /// <param name="baseInterfaces">The list of interfaces that the proxy will implement.</param>
        /// <returns>A forwarding proxy.</returns>
        public Type CreateProxyType(Type baseType, IEnumerable <Type> baseInterfaces)
        {
            // Reuse the cached results, if possible
            Type[] originalInterfaces = baseInterfaces.ToArray();
            if (Cache != null && Cache.Contains(baseType, originalInterfaces))
            {
                return(Cache.Get(baseType, originalInterfaces));
            }

            if (!baseType.IsPublic)
            {
                throw new ArgumentException("The proxy factory can only generate proxies from public base classes.",
                                            "baseType");
            }

            bool hasNonPublicInterfaces = (from t in baseInterfaces
                                           where t.IsNotPublic
                                           select t).Count() > 0;

            if (hasNonPublicInterfaces)
            {
                throw new ArgumentException("The proxy factory cannot generate proxies from non-public interfaces.",
                                            "baseInterfaces");
            }

            #region Determine which interfaces need to be implemented

            Type actualBaseType = baseType.IsInterface ? typeof(object) : baseType;
            var  interfaces     = new HashSet <Type>(baseInterfaces);
            // Move the base type into the list of interfaces
            // if the user mistakenly entered
            // an interface type as the base type
            if (baseType.IsInterface)
            {
                interfaces.Add(baseType);
            }

            if (InterfaceExtractor != null)
            {
                // Get the interfaces for the base type
                InterfaceExtractor.GetInterfaces(actualBaseType, interfaces);

                Type[] targetList = interfaces.ToArray();
                // Extract the inherited interfaces
                foreach (Type type in targetList)
                {
                    InterfaceExtractor.GetInterfaces(type, interfaces);
                }
            }

            #endregion

            #region Generate the assembly

            string             assemblyName     = "LinFu.Proxy";
            AssemblyDefinition assembly         = AssemblyFactory.DefineAssembly(assemblyName, AssemblyKind.Dll);
            ModuleDefinition   mainModule       = assembly.MainModule;
            TypeReference      importedBaseType = mainModule.Import(actualBaseType);
            TypeAttributes     attributes       = TypeAttributes.AutoClass | TypeAttributes.Class |
                                                  TypeAttributes.Public | TypeAttributes.BeforeFieldInit;

            #endregion

            #region Initialize the proxy type

            string         guid          = Guid.NewGuid().ToString().Replace("-", "");
            string         typeName      = string.Format("{0}Proxy-{1}", baseType.Name, guid);
            string         namespaceName = "LinFu.Proxy";
            TypeDefinition proxyType     = mainModule.DefineClass(typeName, namespaceName,
                                                                  attributes, importedBaseType);

            proxyType.AddDefaultConstructor();

            #endregion

            if (ProxyBuilder == null)
            {
                throw new NullReferenceException("The 'ProxyBuilder' property cannot be null");
            }

            // Add the list of interfaces to the target type
            foreach (Type interfaceType in interfaces)
            {
                if (!interfaceType.IsInterface)
                {
                    continue;
                }

                TypeReference currentType = mainModule.Import(interfaceType);
                proxyType.Interfaces.Add(currentType);
            }

            // Hand it off to the builder for construction
            ProxyBuilder.Construct(actualBaseType, interfaces, mainModule, proxyType);

            // Verify the assembly, if possible
            if (Verifier != null)
            {
                Verifier.Verify(assembly);
            }

            #region Compile the results

            Assembly compiledAssembly = assembly.ToAssembly();

            IEnumerable <Type> types = null;

            try
            {
                types = compiledAssembly.GetTypes();
            }
            catch (ReflectionTypeLoadException ex)
            {
                types = ex.Types;
            }

            Type result = (from t in types
                           where t != null && t.IsClass
                           select t).FirstOrDefault();

            #endregion

            // Cache the result
            if (Cache != null)
            {
                Cache.Store(result, baseType, originalInterfaces);
            }

            return(result);
        }
 static AssemblyDefinition GetAssembly()
 {
     return(AssemblyFactory.DefineAssembly("foo", AssemblyKind.Dll));
 }
Exemple #9
0
 private AssemblyDefinition GetAssembly()
 {
     return(AssemblyFactory.DefineAssembly("TempAssembly", AssemblyKind.Dll));
 }