Exemplo n.º 1
0
        public void MultipleInstancesPluginTest()
        {
            var assmBuilder1 = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()),
                                                                     AssemblyBuilderAccess.RunAndCollect);
            var moduleBuilder1 = assmBuilder1.DefineDynamicModule(Guid.NewGuid().ToString());

            var typeBuilder1 = moduleBuilder1.DefineType("Plugin1", TypeAttributes.Public);

            typeBuilder1.AddInterfaceImplementation(typeof(IPlugin));
            typeBuilder1.SetParent(typeof(PluginMock1));
            typeBuilder1.CreateType();

            var typeBuilder2 = moduleBuilder1.DefineType("Plugin2", TypeAttributes.Public);

            typeBuilder2.AddInterfaceImplementation(typeof(IPlugin));
            typeBuilder2.SetParent(typeof(PluginMock2));
            typeBuilder2.CreateType();

            var assm1 = moduleBuilder1.Assembly;

            var assmBuffer1 = new Lokad.ILPack.AssemblyGenerator().GenerateAssemblyBytes(assm1);

            var mgr = new PluginsManager(new Configuration()
            {
                Plugins = new List <string>()
            }, new Mock <IDocifyApplication>().Object);

            Assert.ThrowsAsync <MultiplePluginsPerNameException>(() => mgr.LoadPlugins(new PluginInfoMock[]
            {
                new PluginInfoMock("plg1", new FileMock(Location.FromPath("Plugin1Mock.dll"), assmBuffer1))
            }.ToAsyncEnumerable()));
        }
Exemplo n.º 2
0
        protected Delegate CreateDelegate(Type delegateType)
        {
            if (_dynMethod != null)
            {
                return(_dynMethod.CreateDelegate(delegateType));
            }
            else
            {
                var tb       = _emiMethod.DeclaringType as TypeBuilder;
                var t        = tb.CreateType();
                var assembly = t.Assembly;

                try
                {
                    var generator = new Lokad.ILPack.AssemblyGenerator();

                    string path = Path.Combine(Directory.GetCurrentDirectory(), "Dynamic");
                    Directory.CreateDirectory(path);
                    generator.GenerateAssembly(assembly, Path.Combine(path, assembly.GetName().Name + ".dll"));
                }
                catch
                {
                    // we don't care if the assembly could not be created - it is for debug purposes anyway.
                }
                return(t.GetMethod(_emiMethod.Name).CreateDelegate(delegateType));
            }
        }
Exemplo n.º 3
0
        public async Task InitTest()
        {
            var assmBuilder1 = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()),
                                                                     AssemblyBuilderAccess.RunAndCollect);
            var moduleBuilder1 = assmBuilder1.DefineDynamicModule(Guid.NewGuid().ToString());

            var typeBuilder1 = moduleBuilder1.DefineType("Plugin1", TypeAttributes.Public);

            typeBuilder1.AddInterfaceImplementation(typeof(IPlugin));
            typeBuilder1.SetParent(typeof(PluginMock1));
            var p1 = typeBuilder1.CreateType();

            var assm1 = moduleBuilder1.Assembly;

            var assmBuffer1 = new Lokad.ILPack.AssemblyGenerator().GenerateAssemblyBytes(assm1);

            var mgr = new PluginsManager(new Configuration()
            {
                Plugins = new List <string>()
            }, new Mock <IDocifyApplication>().Object);

            await mgr.LoadPlugins(new PluginInfoMock[]
            {
                new PluginInfoMock("plg1", new FileMock(Location.FromPath("Plugin1Mock.dll"), assmBuffer1)),
            }.ToAsyncEnumerable());

            var res = mgr.GetType().GetField("m_Plugins", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(mgr) as IEnumerable <IPluginBase>;

            Assert.AreEqual(1, res.Count());
            Assert.IsInstanceOf(typeof(IPlugin), res.First());
            Assert.AreEqual(p1.FullName, res.First().GetType().FullName);
            Assert.IsNotNull((res.First() as PluginMock1).App);
        }
Exemplo n.º 4
0
        public void Save(AssemblyBuilder ass, string filename, ImageFileMachine machineKind)
        {
#if !NETCOREAPP2_1_OR_GREATER
            ass.Save(filename, PortableExecutableKinds.ILOnly, machineKind);
#elif LOKAD
            var gen = new Lokad.ILPack.AssemblyGenerator();
            gen.GenerateAssembly(ass, filename);
#endif
        }
Exemplo n.º 5
0
        private static void SaveDebugAssembly(AssemblyBuilder ab)
        {
            Console.Error.WriteLine("Saving '{0}'", ab.GetName().Name + ".dll");
#if DNC
            var generator = new Lokad.ILPack.AssemblyGenerator();
            generator.GenerateAssembly(ab, ab.GetName().Name + ".dll");
#else
            ab.Save(ab.GetName().Name + ".dll");
#endif
        }
Exemplo n.º 6
0
        public void Compile()
        {
            GenStmt(_stmt);

            _il.Emit(OpCodes.Ret);
            _typeBuilder.CreateType();
            _modb.CreateGlobalFunctions();
            var generator = new Lokad.ILPack.AssemblyGenerator();

            generator.GenerateAssembly(_asmb, this._moduleName);
        }
        static void Main(string[] args)
        {
            var doc    = XDocument.Load("../../StringResources.xml");
            var xitems = doc.Element("resources").Elements("item");

            var items = xitems.Select(i => new {
                Key     = i.Attribute("key").Value,
                Value   = i.Attribute("value").Value,
                Comment = i.Attribute("comment").Value,
            });

            var srName         = new AssemblyName("StringResources");
            var srAssemBuilder = AssemblyBuilder.DefineDynamicAssembly(srName, AssemblyBuilderAccess.RunAndCollect);
            var srModBuilder   = srAssemBuilder.DefineDynamicModule($"{srName.Name}.dll");

            var commentAttrCons = typeof(CommentAttribute).GetConstructors()[0];

            var srType = srModBuilder.DefineType("StringResources.Resource", TypeAttributes.Public);

            foreach (var item in items)
            {
                var srProp        = srType.DefineProperty(item.Key, PropertyAttributes.HasDefault, typeof(string), Type.EmptyTypes);
                var srCommentAttr = new CustomAttributeBuilder(commentAttrCons, new object[] { item.Comment });
                srProp.SetCustomAttribute(srCommentAttr);

                var srPropGetter = srType.DefineMethod($"get_{item.Key}", MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Static, typeof(string), Type.EmptyTypes);
                var getterIl     = srPropGetter.GetILGenerator();
                getterIl.Emit(OpCodes.Ldstr, item.Value);
                getterIl.Emit(OpCodes.Ret);
                srProp.SetGetMethod(srPropGetter);
                srPropGetter.SetCustomAttribute(srCommentAttr);
            }
            var type = srType.CreateType();

            const string outputAssembly = "../../out/StringResources.dll";

            if (File.Exists(outputAssembly))
            {
                File.Delete(outputAssembly);
            }

            var assemblyGenerator = new Lokad.ILPack.AssemblyGenerator();

            assemblyGenerator.GenerateAssembly(srAssemBuilder, outputAssembly);
        }
Exemplo n.º 8
0
        public void TestEmit()
        {
            var doc    = NifSchema.LoadEmbedded();
            var basics = new Dictionary <string, Type>()
            {
                { "uint64", typeof(ulong) },
                { "int64", typeof(long) },
                { "ulittle32", typeof(uint) },
                { "uint", typeof(uint) },
                { "int", typeof(int) },
                { "ushort", typeof(ushort) },
                { "short", typeof(short) },
                { "char", typeof(char) },
                { "byte", typeof(byte) },
                { "bool", typeof(bool) },
                { "BlockTypeIndex", typeof(int) },
                { "FileVersion", typeof(int) },
                { "float", typeof(float) },
                { "hfloat", typeof(float) },
                { "HeaderString", typeof(string) },
                { "LineString", typeof(string) },
                { "Ptr", typeof(int) },
                { "Ref", typeof(int) },
                { "StringOffset", typeof(uint) },
                { "NiFixedString", typeof(uint) },
            };
            var version = doc.Versions
                          .Find(v => v.Id == "V20_2_0_7_SSE")
                          .GetVersionKeys()
                          .First();

            var name     = new AssemblyName("MyNonStandardLibrary");
            var access   = AssemblyBuilderAccess.Run;
            var assembly = AssemblyBuilder.DefineDynamicAssembly(name, access);
            var module   = assembly.DefineDynamicModule("MyNonStandardLibrary.dll");

            var schema = new SchemaDocumentBuilder(module, doc, basics, version);

            var generator = new Lokad.ILPack.AssemblyGenerator();

            generator.GenerateAssembly(assembly, "./MyNonStandardLibrary.dll");
        }
Exemplo n.º 9
0
        public void Create_Simply_Type_Test()
        {
            MessageBuilder.GetMessageType <SimplyModel>();
            MessageBuilder.GetMessageType <SimplyModel2>();
            MessageBuilder.GetMessageType <NullableModel>();
            MessageBuilder.GetMessageType <EnumModel>();
            MessageBuilder.GetMessageType <CollectionModel>();
            MessageBuilder.GetMessageType <DictionaryModel>();
            MessageBuilder.GetMessageType <ContentModel>();
            MessageBuilder.GetMessageType <MessageModel>();
            MessageBuilder.GetMessageType <ObjectCollectionModel>();
            MessageBuilder.GetMessageType <ObjectDictionaryModel>();
            MessageBuilder.GetMessageType <PointModel>();
            MessageBuilder.GetMessageType <ValueConstructorModel>();

            var generator = new Lokad.ILPack.AssemblyGenerator();
            var bytes     = generator.GenerateAssemblyBytes(MessageBuilder.GetAssembly());

            File.WriteAllBytes("dynamic.dll", bytes);
        }
Exemplo n.º 10
0
        public async Task LoadSettingsTest()
        {
            var assmBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()),
                                                                    AssemblyBuilderAccess.RunAndCollect);

            var moduleBuilder = assmBuilder.DefineDynamicModule(Guid.NewGuid().ToString());

            var typeBuilder = moduleBuilder.DefineType("Plugin1", TypeAttributes.Public);

            typeBuilder.AddInterfaceImplementation(typeof(IPlugin <MockSettings1>));
            typeBuilder.SetParent(typeof(PluginMock <MockSettings1>));
            typeBuilder.CreateType();

            var assm = moduleBuilder.Assembly;

            var assmBuffer = new Lokad.ILPack.AssemblyGenerator().GenerateAssemblyBytes(assm);

            var conf = new MetadataSerializer().Deserialize <Configuration>("^plg1:\r\n  prop-two: 0.1\r\n  prp3:\r\n    - A\r\n    - B");

            conf.Plugins = new List <string>(new string[] { "plg1" });

            var mgr = new PluginsManager(conf, new Mock <IDocifyApplication>().Object);

            await mgr.LoadPlugins(new PluginInfoMock[]
            {
                new PluginInfoMock("plg1", new FileMock(Location.FromPath("mockplugins.dll"), assmBuffer))
            }.ToAsyncEnumerable());

            var res = mgr.GetType().GetField("m_Plugins", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(mgr) as IEnumerable <IPluginBase>;
            var plg = res.OfType <PluginMock <MockSettings1> >().FirstOrDefault();

            Assert.IsNotNull(plg);
            Assert.IsNotNull(plg.Settings);
            Assert.IsNotNull(plg.App);
            Assert.AreEqual("A", plg.Settings.Prp1);
            Assert.AreEqual(0.1, plg.Settings.PropTwo);
            Assert.That(new string[] { "A", "B" }.SequenceEqual(plg.Settings.Prp3));
        }
Exemplo n.º 11
0
        public void NoPluginFoundTest()
        {
            var assmBuilder1 = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()),
                                                                     AssemblyBuilderAccess.RunAndCollect);
            var moduleBuilder1 = assmBuilder1.DefineDynamicModule(Guid.NewGuid().ToString());

            var typeBuilder1 = moduleBuilder1.DefineType("Plugin1", TypeAttributes.Public);
            var p1           = typeBuilder1.CreateType();

            var assm1 = moduleBuilder1.Assembly;

            var assmBuffer1 = new Lokad.ILPack.AssemblyGenerator().GenerateAssemblyBytes(assm1);

            var mgr = new PluginsManager(new Configuration()
            {
                Plugins = new List <string>()
            }, new Mock <IDocifyApplication>().Object);

            Assert.ThrowsAsync <MissingPluginImplementationException>(() => mgr.LoadPlugins(new PluginInfoMock[]
            {
                new PluginInfoMock("plg1", new FileMock(Location.FromPath("Plugin1Mock.dll"), assmBuffer1))
            }.ToAsyncEnumerable()));
        }
Exemplo n.º 12
0
        //use this instead
        //https://github.com/ltrzesniewski/InlineIL.Fody


        public static void GenerateCil()
        {
            var aName = new AssemblyName("DynamicAssemblyExample");
            var ab    =
                AssemblyBuilder.DefineDynamicAssembly(
                    aName,
                    AssemblyBuilderAccess.RunAndCollect);

            // For a single-module assembly, the module name is usually
            // the assembly name plus an extension.
            var mb =
                ab.DefineDynamicModule(aName.Name);

            var tb = mb.DefineType(
                "MyDynamicType",
                TypeAttributes.Public);

            // Add a private field of type int (Int32).
            var fbNumber = tb.DefineField(
                "m_number",
                typeof(int),
                FieldAttributes.Private);

            // Define a constructor that takes an integer argument and
            // stores it in the private field.
            Type[] parameterTypes = { typeof(int) };
            var    ctor1          = tb.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                parameterTypes);

            var ctor1IL = ctor1.GetILGenerator();

            // For a constructor, argument zero is a reference to the new
            // instance. Push it on the stack before calling the base
            // class constructor. Specify the default constructor of the
            // base class (System.Object) by passing an empty array of
            // types (Type.EmptyTypes) to GetConstructor.
            ctor1IL.Emit(OpCodes.Ldarg_0);
            ctor1IL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
            // Push the instance on the stack before pushing the argument
            // that is to be assigned to the private field m_number.
            ctor1IL.Emit(OpCodes.Ldarg_0);
            ctor1IL.Emit(OpCodes.Ldarg_1);
            ctor1IL.Emit(OpCodes.Stfld, fbNumber);
            ctor1IL.Emit(OpCodes.Ret);


            // Define a default constructor that supplies a default value
            // for the private field. For parameter types, pass the empty
            // array of types or pass null.
            var ctor0 = tb.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                Type.EmptyTypes);

            var ctor0IL = ctor0.GetILGenerator();

            // For a constructor, argument zero is a reference to the new
            // instance. Push it on the stack before pushing the default
            // value on the stack, then call constructor ctor1.
            ctor0IL.Emit(OpCodes.Ldarg_0);
            ctor0IL.Emit(OpCodes.Ldc_I4_S, 42);
            ctor0IL.Emit(OpCodes.Call, ctor1);
            ctor0IL.Emit(OpCodes.Ret);

            // Define a property named Number that gets and sets the private
            // field.
            //
            // The last argument of DefineProperty is null, because the
            // property has no parameters. (If you don't specify null, you must
            // specify an array of Type objects. For a parameterless property,
            // use the built-in array with no elements: Type.EmptyTypes)
            var pbNumber = tb.DefineProperty(
                "Number",
                PropertyAttributes.HasDefault,
                typeof(int),
                null);

            // The property "set" and property "get" methods require a special
            // set of attributes.
            const System.Reflection.MethodAttributes getSetAttr = MethodAttributes.Public |
                                                                  MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            // Define the "get" accessor method for Number. The method returns
            // an integer and has no arguments. (Note that null could be
            // used instead of Types.EmptyTypes)
            var mbNumberGetAccessor = tb.DefineMethod(
                "get_Number",
                getSetAttr,
                typeof(int),
                Type.EmptyTypes);

            var numberGetIL = mbNumberGetAccessor.GetILGenerator();

            // For an instance property, argument zero is the instance. Load the
            // instance, then load the private field and return, leaving the
            // field value on the stack.
            numberGetIL.Emit(OpCodes.Ldarg_0);
            numberGetIL.Emit(OpCodes.Ldfld, fbNumber);
            numberGetIL.Emit(OpCodes.Ret);

            // Define the "set" accessor method for Number, which has no return
            // type and takes one argument of type int (Int32).
            var mbNumberSetAccessor = tb.DefineMethod(
                "set_Number",
                getSetAttr,
                null,
                new Type[] { typeof(int) });

            var numberSetIL = mbNumberSetAccessor.GetILGenerator();

            // Load the instance and then the numeric argument, then store the
            // argument in the field.
            numberSetIL.Emit(OpCodes.Ldarg_0);
            numberSetIL.Emit(OpCodes.Ldarg_1);
            numberSetIL.Emit(OpCodes.Stfld, fbNumber);
            numberSetIL.Emit(OpCodes.Ret);

            // Last, map the "get" and "set" accessor methods to the
            // PropertyBuilder. The property is now complete.
            pbNumber.SetGetMethod(mbNumberGetAccessor);
            pbNumber.SetSetMethod(mbNumberSetAccessor);

            // Define a method that accepts an integer argument and returns
            // the product of that integer and the private field m_number. This
            // time, the array of parameter types is created on the fly.
            var meth = tb.DefineMethod(
                "MyMethod",
                MethodAttributes.Public,
                typeof(int),
                new Type[] { typeof(int) });

            var methIL = meth.GetILGenerator();

            // To retrieve the private instance field, load the instance it
            // belongs to (argument zero). After loading the field, load the
            // argument one and then multiply. Return from the method with
            // the return value (the product of the two numbers) on the
            // execution stack.
            methIL.Emit(OpCodes.Ldarg_0);
            methIL.Emit(OpCodes.Ldfld, fbNumber);
            methIL.Emit(OpCodes.Ldarg_1);
            methIL.Emit(OpCodes.Mul);
            methIL.Emit(OpCodes.Ret);

            // Finish the type.
            var t = tb.CreateType();

            // The following line saves the single-module assembly. This
            // requires AssemblyBuilderAccess to include Save. You can now
            // type "ildasm MyDynamicAsm.dll" at the command prompt, and
            // examine the assembly. You can also write a program that has
            // a reference to the assembly, and use the MyDynamicType type.
            //
            var assembly  = Assembly.GetAssembly(t);
            var generator = new Lokad.ILPack.AssemblyGenerator();

            generator.GenerateAssembly(assembly, aName.Name + "_1.dll");

            GetCil(aName.Name + "_1.dll");

            var mi = t.GetMethod("MyMethod");
            var pi = t.GetProperty("Number");

            // Create an instance of MyDynamicType using the default
            // constructor.
            var o1 = Activator.CreateInstance(t);

            // Display the value of the property, then change it to 127 and
            // display it again. Use null to indicate that the property
            // has no index.
            Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null));
            pi.SetValue(o1, 127, null);
            Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null));

            // Call MyMethod, passing 22, and display the return value, 22
            // times 127. Arguments must be passed as an array, even when
            // there is only one.
            object[] arguments = { 22 };
            Console.WriteLine("o1.MyMethod(22): {0}", mi.Invoke(o1, arguments));

            // Create an instance of MyDynamicType using the constructor
            // that specifies m_Number. The constructor is identified by
            // matching the types in the argument array. In this case,
            // the argument array is created on the fly. Display the
            // property value.
            var o2 = Activator.CreateInstance(t, new object[] { 5280 });

            Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, null));
        }
Exemplo n.º 13
0
        private static void Save(Type typ, string path)
        {
            var generator = new Lokad.ILPack.AssemblyGenerator();

            generator.GenerateAssembly(typ.Assembly, path);
        }
Exemplo n.º 14
0
        public static void WriteAssemblyToDisk(this Type BaseType, string FileName)
        {
            var generator = new Lokad.ILPack.AssemblyGenerator();

            generator.GenerateAssembly(Assembly.GetAssembly(BaseType), FileName);
        }