Ejemplo n.º 1
0
		/// <summary>
		/// Returns a proxy capable of field interception.
		/// </summary>
		/// <returns></returns>
        public override object GetFieldInterceptionProxy() 
        {
            var proxyGenerationOptions = new ProxyGenerationOptions();
            var interceptor = new LazyFieldInterceptor();
            proxyGenerationOptions.AddMixinInstance(interceptor);
            return ProxyGenerator.CreateClassProxy(PersistentClass, proxyGenerationOptions, interceptor);
        }
		public void Mixin_methods_should_be_forwarded_to_target_if_implements_mixin_interface()
		{
			var options = new ProxyGenerationOptions();
			options.AddMixinInstance(new Two());
			var proxy = generator.CreateInterfaceProxyWithTargetInterface(typeof(IOne),
			                                                              new OneTwo(),
			                                                              options);
			var result = (proxy as ITwo).TwoMethod();
			Assert.AreEqual(2, result);
		}
Ejemplo n.º 3
0
        private ILockableDictionary <int, string> Create()
        {
            var options = new ProxyGenerationOptions();

            options.AddMixinInstance(new DeadLockDetector());

            return((ILockableDictionary <int, string>)_proxyGenerator.CreateInterfaceProxyWithTarget(
                       typeof(IDictionary <int, string>),                   // the normal interface
                       new[] { typeof(ILockableDictionary <int, string>) }, // an array of additional interfaces
                       new Dictionary <int, string>(),                      // concrete instance
                       options));                                           // options, which contains the mixin
        }
Ejemplo n.º 4
0
        private ProxyGenerationOptions GetOptionsToMixinCallRouterProvider(ICallRouter callRouter)
        {
            var options = new ProxyGenerationOptions(_allMethodsExceptCallRouterCallsHook);

            // Previously we mixed in the callRouter instance directly, and now we create a wrapper around it.
            // The reason is that we want SubstitutionContext.GetCallRouterFor(substitute) to return us the
            // original callRouter object, rather than the substitute object (as it implemented the ICallRouter interface directly).
            // That need appeared due to the ThreadLocalContext.SetNextRoute() API, which compares the passed callRouter instance by reference.
            options.AddMixinInstance(new StaticCallRouterProvider(callRouter));

            return(options);
        }
    public static IPagedCollection <TModel> GetAsPagedCollection <TModel, TCollection>(int currentPage, int totalPages, int totalCount, TCollection page)
        where TCollection : IModelCollection <TModel>
        where TModel : IPersistableModel
    {
        var generator = new ProxyGenerator();
        var options   = new ProxyGenerationOptions();

        options.AddMixinInstance(new PagingDetails {
            CurrentPage = currentPage, TotalPages = totalPages, TotalCount = totalCount
        });
        return((IPagedCollection <TModel>)generator.CreateClassProxyWithTarget(typeof(TCollection), new[] { typeof(IPagedCollection <TModel>) }, page, options));
    }
Ejemplo n.º 6
0
        public void CanCreateSimpleMixinWithoutGettingExecutionEngineExceptionsOrBadImageExceptions()
        {
            ProxyGenerationOptions proxyGenerationOptions = new ProxyGenerationOptions();

            proxyGenerationOptions.AddMixinInstance(new SimpleMixin());
            object proxy = generator.CreateClassProxy(
                typeof(object), proxyGenerationOptions, new AssertInvocationInterceptor());

            Assert.IsTrue(proxy is ISimpleMixin);

            ((ISimpleMixin)proxy).DoSomething();
        }
Ejemplo n.º 7
0
        public void MixinWithSameInterface_InterfaceWithTarget_AdditionalInterfaces_Derived()
        {
            ProxyGenerationOptions options = new ProxyGenerationOptions();
            SimpleMixin            mixin1  = new SimpleMixin();

            options.AddMixinInstance(mixin1);

            StandardInterceptor interceptor = new StandardInterceptor();
            var proxy = generator.CreateInterfaceProxyWithTarget(typeof(IService), new Type[] { typeof(IDerivedSimpleMixin) }, new ServiceImpl(), options, interceptor);

            Assert.AreEqual(1, (proxy as ISimpleMixin).DoSomething());
        }
Ejemplo n.º 8
0
        private ProxyGenerationOptions GetProxyGenerationOptions(ICancellableDispatcher dispatcher)
        {
            var options = new ProxyGenerationOptions();

            if (!(dispatcher is IFiber fiber))
            {
                return(options);
            }

            options.AddMixinInstance(new FiberProvider(fiber));
            return(options);
        }
Ejemplo n.º 9
0
        internal object GenerateInstance(Type type)
        {
            if (type != OriginalType && !OriginalType.IsAssignableFrom(type))
            {
                throw new Exception(string.Format("Provided type does not match or inherit from '{0}'", OriginalType.FullName));
            }

            var options = new ProxyGenerationOptions(new CryptInjectHook());

            options.AddMixinInstance(Activator.CreateInstance(MixinType));
            return(Generator.CreateClassProxy(OriginalType, options, new EncryptedDataStorageInterceptor()));
        }
        public void Mixin_methods_should_be_forwarded_to_target_if_implements_mixin_interface()
        {
            var options = new ProxyGenerationOptions();

            options.AddMixinInstance(new Two());
            var proxy = generator.CreateInterfaceProxyWithTargetInterface(typeof(IOne),
                                                                          new OneTwo(),
                                                                          options);
            var result = (proxy as ITwo).TwoMethod();

            Assert.AreEqual(2, result);
        }
Ejemplo n.º 11
0
        public void ServiceClientInterceptionIsPossibleWithMixins()
        {
            var options = new ProxyGenerationOptions();

            options.AddMixinInstance(new Dictionary <int, int>());

            // Build the service-side container
            var sb = new ContainerBuilder();

            sb.RegisterType <TestService>().As <ITestService>();

            // Build the client-side container with interception
            // around the client proxy. Issue 361 was that there
            // seemed to be trouble around getting this to work.
            var cb = new ContainerBuilder();

            cb.Register(c => CreateChannelFactory()).SingleInstance();
            cb
            .Register(c => c.Resolve <ChannelFactory <ITestService> >().CreateChannel())
            .InterceptTransparentProxy(options, typeof(IClientChannel))
            .UseWcfSafeRelease();

            using (var sc = sb.Build())
            {
                // Start the self-hosted test service
                var host = CreateTestServiceHost(sc);
                host.Open();
                try
                {
                    using (var cc = cb.Build())
                    {
                        // Make a call through the client to the service -
                        // it should be intercepted.
                        var client = cc.Resolve <ITestService>();
                        var dict   = client as IDictionary <int, int>;

                        Assert.IsNotNull(dict);

                        dict.Add(1, 2);

                        Assert.AreEqual(2, dict[1]);

                        dict.Clear();

                        Assert.IsEmpty(dict);
                    }
                }
                finally
                {
                    host.Close();
                }
            }
        }
Ejemplo n.º 12
0
        public void TwoMixins()
        {
            ProxyGenerationOptions proxyGenerationOptions = new ProxyGenerationOptions();

            SimpleMixin mixin1 = new SimpleMixin();
            OtherMixin  mixin2 = new OtherMixin();

            proxyGenerationOptions.AddMixinInstance(mixin1);
            proxyGenerationOptions.AddMixinInstance(mixin2);

            AssertInvocationInterceptor interceptor = new AssertInvocationInterceptor();

            object proxy = generator.CreateClassProxy(
                typeof(SimpleClass),
                proxyGenerationOptions,
                interceptor
                );

            Assert.IsFalse(interceptor.Invoked);

            Assert.IsNotNull(proxy);
            Assert.IsTrue(typeof(SimpleClass).IsAssignableFrom(proxy.GetType()));

            ISimpleMixin mixin = proxy as ISimpleMixin;

            Assert.IsNotNull(mixin);
            Assert.AreEqual(1, mixin.DoSomething());

            Assert.IsTrue(interceptor.Invoked);
            Assert.AreSame(proxy, interceptor.proxy);
            Assert.AreSame(mixin1, interceptor.mixin);

            IOtherMixin other = proxy as IOtherMixin;

            Assert.IsNotNull(other);
            Assert.AreEqual(3, other.Sum(1, 2));
            Assert.IsTrue(interceptor.Invoked);
            Assert.AreSame(proxy, interceptor.proxy);
            Assert.AreSame(mixin2, interceptor.mixin);
        }
Ejemplo n.º 13
0
        static EntityHelper()
        {
            var scope = new ModuleScope(false, false, new EntityProxyNameScope(), ASSEMBLY_NAME, MODULE_PATH, ASSEMBLY_NAME, MODULE_PATH);

            generator = new ProxyGenerator(new DefaultProxyBuilder(scope));

            options = new ProxyGenerationOptions(new EntityInterceptorFilter())
            {
                Selector = new EntityInterceptorSelector()
            };

            options.AddMixinInstance(new EntityObject());
        }
Ejemplo n.º 14
0
        public static TClass MakeFreezable <TClass>() where TClass : class, new()
        {
            var options = new ProxyGenerationOptions(new FreezableProxyGenerationHook())
            {
                Selector = _selector
            };

            options.AddMixinInstance(new List <string>());
            var freezableInterceptor = new FreezableInterceptor();
            var proxy = Generator.CreateClassProxy <TClass>(options, freezableInterceptor, new CallLoggingInterceptor());

            return(proxy);
        }
        public void Null_target_can_be_replaced()
        {
            var options = new ProxyGenerationOptions();

            options.AddMixinInstance(new Two());
            var interceptor = new ChangeTargetInterceptor(new OneTwo());
            var proxy       = generator.CreateInterfaceProxyWithTargetInterface(typeof(IOne),
                                                                                default(object),
                                                                                options,
                                                                                interceptor);

            Assert.AreEqual(3, ((IOne)proxy).OneMethod());
        }
Ejemplo n.º 16
0
        public void ProxyGenerationOptionsRespectedOnDeserializationComplex()
        {
            var hook    = new MethodFilterHook("(get_Current)|(GetExecutingObject)");
            var options = new ProxyGenerationOptions(hook);

            options.AddMixinInstance(new SerializableMixin());
            options.Selector = new SerializableInterceptorSelector();

            var holder = new ComplexHolder();

            holder.Type    = typeof(MySerializableClass);
            holder.Element = generator.CreateClassProxy(typeof(MySerializableClass), new Type[0], options,
                                                        new StandardInterceptor());

            // check holder elements
            Assert.AreEqual(typeof(MySerializableClass), holder.Type);
            Assert.IsNotNull(holder.Element);
            Assert.IsTrue(holder.Element is MySerializableClass);
            Assert.AreNotEqual(typeof(MySerializableClass), holder.Element.GetType());

            // check whether options were applied correctly
            Assert.AreEqual(holder.Element.GetType(), holder.Element.GetType().GetMethod("get_Current").DeclaringType);
            Assert.AreNotEqual(holder.Element.GetType(),
                               holder.Element.GetType().GetMethod("CalculateSumDistanceNow").DeclaringType);
            Assert.AreEqual(holder.Element.GetType().BaseType,
                            holder.Element.GetType().GetMethod("CalculateSumDistanceNow").DeclaringType);
            var options2 = (ProxyGenerationOptions)holder.Element.GetType().
                           GetField("proxyGenerationOptions", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);

            Assert.IsNotNull(Array.Find(options2.MixinsAsArray(), delegate(object o) { return(o is SerializableMixin); }));
            Assert.IsNotNull(options2.Selector);

            var otherHolder = SerializeAndDeserialize(holder);

            // check holder elements
            Assert.AreEqual(typeof(MySerializableClass), otherHolder.Type);
            Assert.IsNotNull(otherHolder.Element);
            Assert.IsTrue(otherHolder.Element is MySerializableClass);
            Assert.AreNotEqual(typeof(MySerializableClass), otherHolder.Element.GetType());

            // check whether options were applied correctly
            Assert.AreEqual(otherHolder.Element.GetType(), otherHolder.Element.GetType().GetMethod("get_Current").DeclaringType);
            Assert.AreNotEqual(otherHolder.Element.GetType(),
                               otherHolder.Element.GetType().GetMethod("CalculateSumDistanceNow").DeclaringType);
            Assert.AreEqual(otherHolder.Element.GetType().BaseType,
                            otherHolder.Element.GetType().GetMethod("CalculateSumDistanceNow").DeclaringType);
            options2 = (ProxyGenerationOptions)otherHolder.Element.GetType().
                       GetField("proxyGenerationOptions", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
            Assert.IsNotNull(Array.Find(options2.MixinsAsArray(), delegate(object o) { return(o is SerializableMixin); }));
            Assert.IsNotNull(options2.Selector);
        }
Ejemplo n.º 17
0
        private ProxyGenerationOptions CreateProxyGenerationOptions(Type type, MockCreationSettings settings, MockMixin mockMixinImpl = null)
        {
            var options = new ProxyGenerationOptions();

            if (mockMixinImpl != null)
            {
                options.AddMixinInstance(mockMixinImpl);
            }
            foreach (var mixin in settings.Mixins)
            {
                options.AddMixinInstance(mixin);
            }

            if (settings.AdditionalProxyTypeAttributes != null)
            {
                foreach (var attr in settings.AdditionalProxyTypeAttributes)
                {
                    options.AdditionalAttributes.Add(attr);
                }
            }

            return(options);
        }
        public void Should_detect_and_report_setting_null_as_target_for_Mixin_methods()
        {
            var options = new ProxyGenerationOptions();

            options.AddMixinInstance(new Two());
            var interceptor = new ChangeTargetInterceptor(null);
            var proxy       = generator.CreateInterfaceProxyWithTargetInterface(typeof(IOne),
                                                                                new One(),
                                                                                options,
                                                                                interceptor);

            Assert.Throws(typeof(NotImplementedException), () =>
                          (proxy as ITwo).TwoMethod());
        }
		public void Invocation_should_be_IChangeInvocationTarget_for_Mixin_methods()
		{
			var options = new ProxyGenerationOptions();
			options.AddMixinInstance(new Two());
			var interceptor = new ChangeTargetInterceptor(new OneTwo());
			var proxy = generator.CreateInterfaceProxyWithTargetInterface(typeof(IOne),
			                                                              new One(),
			                                                              options,
			                                                              interceptor);

			var result = (proxy as ITwo).TwoMethod();

			Assert.AreEqual(2, result);
		}
        public void Invocation_should_be_IChangeInvocationTarget_for_target_methods()
        {
            var options = new ProxyGenerationOptions();

            options.AddMixinInstance(new Two());
            var interceptor = new ChangeTargetInterceptor(new OneTwo());
            var proxy       = generator.CreateInterfaceProxyWithTargetInterface(typeof(IOne),
                                                                                new One(),
                                                                                options,
                                                                                interceptor);
            var result = (proxy as IOne).OneMethod();

            Assert.AreEqual(3, result);
        }
Ejemplo n.º 21
0
        internal T CreateProxy <T>(Partial <T> owner) where T : class
        {
            // TODO: Filter interceptors, only run on Set & add PartialProxyInterceptor
            var options = new ProxyGenerationOptions(new PartialProxyGenerationHook(typeof(T)));

            options.AddMixinInstance(new PartialProxy <T>(owner));

            var proxy = _proxyGenerator.CreateClassProxy(
                typeof(T),
                options,
                new PartialInterceptor <T>(owner));

            return((T)proxy);
        }
Ejemplo n.º 22
0
 private static IShape CreateShape(Type baseType)
 {
     // Don't generate a proxy for shape types
     if (typeof(IShape).IsAssignableFrom(baseType))
     {
         var shape = Activator.CreateInstance(baseType) as IShape;
         return(shape);
     }
     else
     {
         var options = new ProxyGenerationOptions();
         options.AddMixinInstance(new ShapeViewModel());
         return((IShape)ProxyGenerator.CreateClassProxy(baseType, options));
     }
 }
Ejemplo n.º 23
0
        private static object BuildProxy <T>(IContent node)
        {
            var ops = new ProxyGenerationOptions();

            ops.AddMixinInstance(new LazyContentResolverMixin(node));

            var classToProxy = typeof(T);

            // Determine whether to use constructor that takes IPublishedContent
            var useContentConstructor = classToProxy.GetConstructors().Any(c => c.GetParameters().Any(p => p.ParameterType == typeof(IContent)));

            return(useContentConstructor
                ? _generator.CreateClassProxy(classToProxy, ops, new object[] { node }, _interceptor)
                : _generator.CreateClassProxy(classToProxy, ops, _interceptor));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 创建指定类型的实体代理对象
        /// </summary>
        /// <returns>实体代理对象</returns>
        /// <param name="type">类型</param>
        public static object CreateProxy(Type @type)
        {
            ProxyGenerationOptions options = new ProxyGenerationOptions(new EntityInterceptorFilter())
            {
                Selector = new EntityInterceptorSelector()
            };

            options.AddMixinInstance(new EntityObject());

            object target = generator.CreateClassProxy(@type, options, new EntityInterceptor());

            ((IEntityObject)target).Reset();

            return(target);
        }
Ejemplo n.º 25
0
        private FormFieldInfo AppendWebPart(FormFieldInfo formFieldInfo, IWebPart webPart)
        {
            var options = new ProxyGenerationOptions();

            options.AddMixinInstance(new WebPartHolder
            {
                WebPart = webPart,
            });

            var result = this.proxyGenerator.CreateClassProxyWithTarget(formFieldInfo, options);

            ((IWebPartHolder)result).WebPart = webPart;

            return(result as FormFieldInfo);
        }
Ejemplo n.º 26
0
        public void Mix()
        {
            var options = new ProxyGenerationOptions();

            // the instances for A and B would be the user provided and yours
            options.AddMixinInstance(new A());
            options.AddMixinInstance(new B());
            var proxy = new ProxyGenerator().CreateClassProxy <object>(options);

            Assert.IsAssignableFrom <IA>(proxy);
            Assert.IsAssignableFrom <IB>(proxy);

            try
            {
                ((IA)proxy).Do();
            }
            catch (NotImplementedException ex)
            {
                if (ex.Message != "A")
                {
                    throw;
                }
            }

            try
            {
                ((IB)proxy).Something();
            }
            catch (NotImplementedException ex)
            {
                if (ex.Message != "B")
                {
                    throw;
                }
            }
        }
Ejemplo n.º 27
0
        public void MixinImplementingMoreThanOneInterface()
        {
            ProxyGenerationOptions proxyGenerationOptions = new ProxyGenerationOptions();

            ComplexMixin mixin_instance = new ComplexMixin();

            proxyGenerationOptions.AddMixinInstance(mixin_instance);

            AssertInvocationInterceptor interceptor = new AssertInvocationInterceptor();

            object proxy = generator.CreateClassProxy(
                typeof(SimpleClass),
                proxyGenerationOptions,
                interceptor
                );

            Assert.IsNotNull(proxy);
            Assert.IsTrue(typeof(SimpleClass).IsAssignableFrom(proxy.GetType()));

            Assert.IsFalse(interceptor.Invoked);

            IThird inter3 = proxy as IThird;

            Assert.IsNotNull(inter3);
            inter3.DoThird();

            Assert.IsTrue(interceptor.Invoked);
            Assert.AreSame(proxy, interceptor.proxy);
            Assert.AreSame(mixin_instance, interceptor.mixin);

            ISecond inter2 = proxy as ISecond;

            Assert.IsNotNull(inter2);
            inter2.DoSecond();

            Assert.IsTrue(interceptor.Invoked);
            Assert.AreSame(proxy, interceptor.proxy);
            Assert.AreSame(mixin_instance, interceptor.mixin);

            IFirst inter1 = proxy as IFirst;

            Assert.IsNotNull(inter1);
            inter1.DoFirst();

            Assert.IsTrue(interceptor.Invoked);
            Assert.AreSame(proxy, interceptor.proxy);
            Assert.AreSame(mixin_instance, interceptor.mixin);
        }
Ejemplo n.º 28
0
    public static IEnumerable <T> ProxyAddMixins <T>(this IEnumerable <T> collection, params Func <T, object>[] mixinSelectors)
        where T : class
    {
        ProxyGenerator factory = new ProxyGenerator();

        foreach (T item in collection)
        {
            ProxyGenerationOptions o = new ProxyGenerationOptions();
            foreach (var func in mixinSelectors)
            {
                object mixin = func(item);
                o.AddMixinInstance(mixin);
            }
            yield return(factory.CreateClassProxyWithTarget <T>(item, o));
        }
    }
        public void MixinsAppliedOnDeserialization()
        {
            var options = new ProxyGenerationOptions();
            options.AddMixinInstance(new SerializableMixin());

            var proxy = (MySerializableClass)generator.CreateClassProxy(
                typeof(MySerializableClass),
                new Type[0],
                options,
                new StandardInterceptor());

            Assert.IsTrue(proxy is IMixedInterface);

            var otherProxy = SerializeAndDeserialize(proxy);
            Assert.IsTrue(otherProxy is IMixedInterface);
        }
Ejemplo n.º 30
0
            private ProxyGenerationOptions CreateOptions()
            {
                if (_filterMethods.Any() || _mixins.Any())
                {
                    var options = new ProxyGenerationOptions();
                    if (_filterMethods.Any())
                    {
                        options.Hook = new ProxyGenerationHookImpl(_filterMethods);
                    }
                    _mixins.ForEach(mi => options.AddMixinInstance(mi));

                    return(options);
                }

                return(null);
            }
Ejemplo n.º 31
0
        static void Main(string[] args)
        {
            var generator = new ProxyGenerator();

            var options = new ProxyGenerationOptions()
            {
                Hook     = new InterceptorFilter(),
                Selector = new InterceptorSelector()
            };

            var entity = generator.CreateClassProxy <User>(options,
                                                           new CallingLogInterceptor(),
                                                           new SimpleLogInterceptor());

            entity.Name = "Lex";
            entity.Age  = 28;
            entity.Sex  = "Male";

            Console.WriteLine("The entity is: " + entity);

            Console.WriteLine("Type of the entity: " + entity.GetType().FullName);

            Console.ReadKey();

            var storageNode = generator.CreateInterfaceProxyWithTargetInterface <IStorageNode>(
                new StorageNode("master"),
                new DualNodeInterceptor(new StorageNode("slave")),
                new CallingLogInterceptor());

            storageNode.Save("my message"); //应该调用master对象
            storageNode.IsDead = true;
            storageNode.Save("my message"); //应该调用slave对象
            storageNode.Save("my message"); //应该调用master对象

            Console.ReadKey();

            options = new ProxyGenerationOptions();
            options.AddMixinInstance(new ClassA());
            var objB = generator.CreateClassProxy <ClassB>(options, new CallingLogInterceptor());

            objB.ActionB();
            var objA = objB as IActionA;

            objA.ActionA();

            Console.ReadKey();
        }
Ejemplo n.º 32
0
        // 7.运行期使用“合并”方式修改对象行为 Mixin
        public static void Main27(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            ProxyGenerator generator = new ProxyGenerator();
            var            options   = new ProxyGenerationOptions();

            options.AddMixinInstance(new ClassA());
            ClassB objB = generator.CreateClassProxy <ClassB>(options, new CallingLogInterceptor());

            objB.ActionB();
            InterfaceA objA = objB as InterfaceA;

            objA.ActionA();

            Console.Read();
        }
Ejemplo n.º 33
0
        public void LoadAssemblyIntoCache_DifferentGenerationOptions()
        {
            var savedScope = new ModuleScope(true);
            var builder    = new DefaultProxyBuilder(savedScope);

            var options1 = new ProxyGenerationOptions();

            options1.AddMixinInstance(new DateTime());
            var options2 = ProxyGenerationOptions.Default;

            var cp1 = builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, options1);
            var cp2 = builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, options2);

            Assert.AreNotSame(cp1, cp2);
            Assert.AreSame(cp1, builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, options1));
            Assert.AreSame(cp2, builder.CreateClassProxyType(typeof(object), Type.EmptyTypes, options2));

            var path = savedScope.SaveAssembly();

            CrossAppDomainCaller.RunInOtherAppDomain(delegate(object[] args)
            {
                var newScope   = new ModuleScope(false);
                var newBuilder = new DefaultProxyBuilder(newScope);

                var assembly = Assembly.LoadFrom((string)args[0]);
                newScope.LoadAssemblyIntoCache(assembly);

                var newOptions1 = new ProxyGenerationOptions();
                newOptions1.AddMixinInstance(new DateTime());
                var newOptions2 = ProxyGenerationOptions.Default;

                var loadedCP1 = newBuilder.CreateClassProxyType(typeof(object),
                                                                Type.EmptyTypes,
                                                                newOptions1);
                var loadedCP2 = newBuilder.CreateClassProxyType(typeof(object),
                                                                Type.EmptyTypes,
                                                                newOptions2);
                Assert.AreNotSame(loadedCP1, loadedCP2);
                Assert.AreEqual(assembly, loadedCP1.Assembly);
                Assert.AreEqual(assembly, loadedCP2.Assembly);
            }, path);

            File.Delete(path);
        }
Ejemplo n.º 34
0
		public void SimpleMixin_ClassProxy()
		{
			ProxyGenerationOptions options = new ProxyGenerationOptions();
			SimpleMixin mixin_instance = new SimpleMixin();
			options.AddMixinInstance(mixin_instance);

			AssertInvocationInterceptor interceptor = new AssertInvocationInterceptor();

			object proxy = generator.CreateClassProxy(typeof (SimpleClass), options, interceptor);

			Assert.IsNotNull(proxy);
			Assert.IsTrue(typeof (SimpleClass).IsAssignableFrom(proxy.GetType()));

			Assert.IsFalse(interceptor.Invoked);

			ISimpleMixin mixin = proxy as ISimpleMixin;
			Assert.IsNotNull(mixin);
			Assert.AreEqual(1, mixin.DoSomething());

			Assert.IsTrue(interceptor.Invoked);
			Assert.AreSame(proxy, interceptor.proxy);
			Assert.AreSame(mixin_instance, interceptor.mixin);
		}
Ejemplo n.º 35
0
		public void MixinWithSameInterface_InterfaceWithTarget_AdditionalInterfaces_Derived()
		{
			ProxyGenerationOptions options = new ProxyGenerationOptions();
			SimpleMixin mixin1 = new SimpleMixin();
			options.AddMixinInstance(mixin1);

			StandardInterceptor interceptor = new StandardInterceptor();
			var proxy = generator.CreateInterfaceProxyWithTarget(typeof(IService), new Type[] { typeof(IDerivedSimpleMixin) }, new ServiceImpl(), options, interceptor);
			Assert.AreEqual(1, (proxy as ISimpleMixin).DoSomething());
		}
Ejemplo n.º 36
0
		public void TwoMixinsWithSameInterface()
		{
			ProxyGenerationOptions options = new ProxyGenerationOptions();
			SimpleMixin mixin1 = new SimpleMixin();
			OtherMixinImplementingISimpleMixin mixin2 = new OtherMixinImplementingISimpleMixin();
			options.AddMixinInstance(mixin1);
			options.AddMixinInstance(mixin2);

			StandardInterceptor interceptor = new StandardInterceptor();

			Assert.Throws<InvalidMixinConfigurationException>(() =>
				generator.CreateClassProxy(typeof(SimpleClass), options, interceptor)
			);
		}
Ejemplo n.º 37
0
		public void TestTypeCachingWithMultipleMixins()
		{
			ProxyGenerationOptions options = new ProxyGenerationOptions();
			SimpleMixin mixin_instance1 = new SimpleMixin();
			ComplexMixin mixin_instance2 = new ComplexMixin();
			options.AddMixinInstance(mixin_instance1);
			options.AddMixinInstance(mixin_instance2);

			AssertInvocationInterceptor interceptor = new AssertInvocationInterceptor();

			object proxy1 = generator.CreateClassProxy(typeof (SimpleClass), options, interceptor);

			options = new ProxyGenerationOptions();
			mixin_instance1 = new SimpleMixin();
			mixin_instance2 = new ComplexMixin();
			options.AddMixinInstance(mixin_instance2);
			options.AddMixinInstance(mixin_instance1);

			interceptor = new AssertInvocationInterceptor();

			object proxy2 = generator.CreateClassProxy(typeof (SimpleClass), options, interceptor);

			Assert.IsTrue(proxy1.GetType().Equals(proxy2.GetType()));
		}
Ejemplo n.º 38
0
		public void MixinImplementingMoreThanOneInterface()
		{
			ProxyGenerationOptions proxyGenerationOptions = new ProxyGenerationOptions();

			ComplexMixin mixin_instance = new ComplexMixin();
			proxyGenerationOptions.AddMixinInstance(mixin_instance);

			AssertInvocationInterceptor interceptor = new AssertInvocationInterceptor();

			object proxy = generator.CreateClassProxy(
				typeof (SimpleClass), proxyGenerationOptions, interceptor);

			Assert.IsNotNull(proxy);
			Assert.IsTrue(typeof (SimpleClass).IsAssignableFrom(proxy.GetType()));

			Assert.IsFalse(interceptor.Invoked);

			IThird inter3 = proxy as IThird;
			Assert.IsNotNull(inter3);
			inter3.DoThird();

			Assert.IsTrue(interceptor.Invoked);
			Assert.AreSame(proxy, interceptor.proxy);
			Assert.AreSame(mixin_instance, interceptor.mixin);

			ISecond inter2 = proxy as ISecond;
			Assert.IsNotNull(inter2);
			inter2.DoSecond();

			Assert.IsTrue(interceptor.Invoked);
			Assert.AreSame(proxy, interceptor.proxy);
			Assert.AreSame(mixin_instance, interceptor.mixin);

			IFirst inter1 = proxy as IFirst;
			Assert.IsNotNull(inter1);
			inter1.DoFirst();

			Assert.IsTrue(interceptor.Invoked);
			Assert.AreSame(proxy, interceptor.proxy);
			Assert.AreSame(mixin_instance, interceptor.mixin);
		}
		public void ProxyGenerationOptionsRespectedOnDeserializationComplex ()
		{
			ProxyObjectReference.ResetScope ();

			MethodFilterHook hook = new MethodFilterHook ("get_Current");
			ProxyGenerationOptions options = new ProxyGenerationOptions (hook);
			options.AddMixinInstance (new SerializableMixin());
			options.Selector = new SerializableInterceptorSelector ();

			ComplexHolder holder = new ComplexHolder();
			holder.Type = typeof (MySerializableClass);
			holder.Element = generator.CreateClassProxy (typeof (MySerializableClass), new Type[0], options, new StandardInterceptor ());

			// check holder elements
			Assert.AreEqual (typeof (MySerializableClass), holder.Type);
			Assert.IsNotNull (holder.Element);
			Assert.IsTrue (holder.Element is MySerializableClass) ;
			Assert.AreNotEqual (typeof (MySerializableClass), holder.Element.GetType ());

			// check whether options were applied correctly
			Assert.AreEqual (holder.Element.GetType (), holder.Element.GetType ().GetMethod ("get_Current").DeclaringType);
			Assert.AreNotEqual (holder.Element.GetType (), holder.Element.GetType ().GetMethod ("CalculateSumDistanceNow").DeclaringType);
			Assert.AreEqual (holder.Element.GetType ().BaseType, holder.Element.GetType ().GetMethod ("CalculateSumDistanceNow").DeclaringType);
			ProxyGenerationOptions options2 = (ProxyGenerationOptions) holder.Element.GetType ().GetField ("proxyGenerationOptions").GetValue (null);
			Assert.IsNotNull (Array.Find (options2.MixinsAsArray (), delegate (object o) { return o is SerializableMixin; }));
			Assert.IsNotNull (options2.Selector);

			ComplexHolder otherHolder = (ComplexHolder) SerializeAndDeserialize (holder);

			// check holder elements
			Assert.AreEqual (typeof (MySerializableClass), otherHolder.Type);
			Assert.IsNotNull (otherHolder.Element);
			Assert.IsTrue (otherHolder.Element is MySerializableClass);
			Assert.AreNotEqual(typeof (MySerializableClass), otherHolder.Element.GetType());

			// check whether options were applied correctly
			Assert.AreEqual (otherHolder.Element.GetType (), otherHolder.Element.GetType ().GetMethod ("get_Current").DeclaringType);
			Assert.AreNotEqual (otherHolder.Element.GetType (), otherHolder.Element.GetType ().GetMethod ("CalculateSumDistanceNow").DeclaringType);
			Assert.AreEqual (otherHolder.Element.GetType ().BaseType, otherHolder.Element.GetType ().GetMethod ("CalculateSumDistanceNow").DeclaringType);
			options2 = (ProxyGenerationOptions) otherHolder.Element.GetType ().GetField ("proxyGenerationOptions").GetValue (null);
			Assert.IsNotNull (Array.Find (options2.MixinsAsArray (), delegate (object o) { return o is SerializableMixin; }));
			Assert.IsNotNull (options2.Selector);
		}
Ejemplo n.º 40
0
		public void TwoMixinsWithSameInterface()
		{
			ProxyGenerationOptions options = new ProxyGenerationOptions();
			SimpleMixin mixin1 = new SimpleMixin();
			OtherMixinImplementingISimpleMixin mixin2 = new OtherMixinImplementingISimpleMixin();
			options.AddMixinInstance(mixin1);
			options.AddMixinInstance(mixin2);

			StandardInterceptor interceptor = new StandardInterceptor();
			generator.CreateClassProxy(typeof(SimpleClass), options, interceptor);
		}
Ejemplo n.º 41
0
		public void TwoMixins()
		{
			ProxyGenerationOptions proxyGenerationOptions = new ProxyGenerationOptions();

			SimpleMixin mixin1 = new SimpleMixin();
			OtherMixin mixin2 = new OtherMixin();

			proxyGenerationOptions.AddMixinInstance(mixin1);
			proxyGenerationOptions.AddMixinInstance(mixin2);

			AssertInvocationInterceptor interceptor = new AssertInvocationInterceptor();

			object proxy = generator.CreateClassProxy(
				typeof (SimpleClass), proxyGenerationOptions, interceptor);

			Assert.IsFalse(interceptor.Invoked);

			Assert.IsNotNull(proxy);
			Assert.IsTrue(typeof (SimpleClass).IsAssignableFrom(proxy.GetType()));

			ISimpleMixin mixin = proxy as ISimpleMixin;
			Assert.IsNotNull(mixin);
			Assert.AreEqual(1, mixin.DoSomething());

			Assert.IsTrue(interceptor.Invoked);
			Assert.AreSame(proxy, interceptor.proxy);
			Assert.AreSame(mixin1, interceptor.mixin);

			IOtherMixin other = proxy as IOtherMixin;
			Assert.IsNotNull(other);
			Assert.AreEqual(3, other.Sum(1, 2));
			Assert.IsTrue(interceptor.Invoked);
			Assert.AreSame(proxy, interceptor.proxy);
			Assert.AreSame(mixin2, interceptor.mixin);
		}
		public void ProxyKnowsItsGenerationOptions ()
		{
			MethodFilterHook hook = new MethodFilterHook (".*");
			ProxyGenerationOptions options = new ProxyGenerationOptions (hook);
			options.AddMixinInstance (new SerializableMixin ());

			object proxy = generator.CreateClassProxy (
					typeof (MySerializableClass),
					new Type[0],
					options,
					new StandardInterceptor ());

			FieldInfo field = proxy.GetType ().GetField ("proxyGenerationOptions");
			Assert.IsNotNull (field);
			Assert.AreSame (options, field.GetValue (proxy));

			base.Init ();

			proxy = generator.CreateInterfaceProxyWithoutTarget (typeof (IService), new StandardInterceptor ());
			field = proxy.GetType ().GetField ("proxyGenerationOptions");
			Assert.AreSame (ProxyGenerationOptions.Default, field.GetValue (proxy));

			base.Init ();

			proxy = generator.CreateInterfaceProxyWithTarget (typeof (IService), new ServiceImpl(), options, new StandardInterceptor ());
			field = proxy.GetType ().GetField ("proxyGenerationOptions");
			Assert.AreSame (options, field.GetValue (proxy));

			base.Init ();

			proxy = generator.CreateInterfaceProxyWithTargetInterface (typeof (IService), new ServiceImpl(), new StandardInterceptor ());
			field = proxy.GetType ().GetField ("proxyGenerationOptions");
			Assert.AreSame (ProxyGenerationOptions.Default, field.GetValue (proxy));
		}
		public void Equals_EqualNonEmptyOptions()
		{
			_options1 = new ProxyGenerationOptions();
			_options2 = new ProxyGenerationOptions();

			_options1.BaseTypeForInterfaceProxy = typeof (IConvertible);
			_options2.BaseTypeForInterfaceProxy = typeof (IConvertible);

			SimpleMixin mixin = new SimpleMixin();
			_options1.AddMixinInstance(mixin);
			_options2.AddMixinInstance(mixin);

			IProxyGenerationHook hook = new AllMethodsHook();
			_options1.Hook = hook;
			_options2.Hook = hook;

			IInterceptorSelector selector = new AllInterceptorSelector();
			_options1.Selector = selector;
			_options2.Selector = selector;

			Assert.AreEqual(_options1, _options2);
		}
		public void Uses_The_Provided_Options()
		{
			var options = new ProxyGenerationOptions();
			options.AddMixinInstance(new SimpleMixin());

			var target = new SimpleClassWithProperty();
			var proxy = generator.CreateClassProxyWithTarget(target, options);

			Assert.IsInstanceOf(typeof(ISimpleMixin), proxy);
		}
		public void ProxyGenerationOptionsRespectedOnDeserialization ()
		{
			ProxyObjectReference.ResetScope();

			MethodFilterHook hook = new MethodFilterHook ("get_Current");
			ProxyGenerationOptions options = new ProxyGenerationOptions (hook);
			options.AddMixinInstance (new SerializableMixin());
			options.Selector = new SerializableInterceptorSelector ();

			MySerializableClass proxy = (MySerializableClass) generator.CreateClassProxy (
			    typeof (MySerializableClass),
			    new Type[0],
			    options,
			    new StandardInterceptor());

			Assert.AreEqual (proxy.GetType(), proxy.GetType().GetMethod ("get_Current").DeclaringType);
			Assert.AreNotEqual (proxy.GetType(), proxy.GetType().GetMethod ("CalculateSumDistanceNow").DeclaringType);
			Assert.AreEqual (proxy.GetType().BaseType, proxy.GetType().GetMethod ("CalculateSumDistanceNow").DeclaringType);
			ProxyGenerationOptions options2 = (ProxyGenerationOptions) proxy.GetType().GetField("proxyGenerationOptions").GetValue(null);
			Assert.IsNotNull (Array.Find (options2.MixinsAsArray (), delegate (object o) { return o is SerializableMixin; }));
			Assert.IsNotNull (options2.Selector);

			MySerializableClass otherProxy = (MySerializableClass) SerializeAndDeserialize (proxy);
			Assert.AreEqual (otherProxy.GetType(), otherProxy.GetType().GetMethod ("get_Current").DeclaringType);
			Assert.AreNotEqual (otherProxy.GetType(), otherProxy.GetType().GetMethod ("CalculateSumDistanceNow").DeclaringType);
			Assert.AreEqual (otherProxy.GetType().BaseType, otherProxy.GetType().GetMethod ("CalculateSumDistanceNow").DeclaringType);
			options2 = (ProxyGenerationOptions) otherProxy.GetType ().GetField ("proxyGenerationOptions").GetValue (null);
			Assert.IsNotNull (Array.Find (options2.MixinsAsArray (), delegate (object o) { return o is SerializableMixin; }));
			Assert.IsNotNull (options2.Selector);
		}
		public void MixinsAppliedOnDeserialization ()
		{
			ProxyObjectReference.ResetScope ();

			ProxyGenerationOptions options = new ProxyGenerationOptions ();
			options.AddMixinInstance (new SerializableMixin ());

			MySerializableClass proxy = (MySerializableClass) generator.CreateClassProxy (
					typeof (MySerializableClass),
					new Type[0],
					options,
					new StandardInterceptor ());

			Assert.IsTrue (proxy is IMixedInterface);

			MySerializableClass otherProxy = (MySerializableClass) SerializeAndDeserialize (proxy);
			Assert.IsTrue (otherProxy is IMixedInterface);
		}
		public void Null_target_can_be_replaced()
		{
			var options = new ProxyGenerationOptions();
			options.AddMixinInstance(new Two());
			var interceptor = new ChangeTargetInterceptor(new OneTwo());
			var proxy = generator.CreateInterfaceProxyWithTargetInterface(typeof(IOne),
			                                                              default(object),
			                                                              options,
			                                                              interceptor);

			Assert.AreEqual(3, ((IOne) proxy).OneMethod());
		}
Ejemplo n.º 48
0
		public void MixinForInterfaces()
		{
			ProxyGenerationOptions proxyGenerationOptions = new ProxyGenerationOptions();

			SimpleMixin mixin_instance = new SimpleMixin();
			proxyGenerationOptions.AddMixinInstance(mixin_instance);

			AssertInvocationInterceptor interceptor = new AssertInvocationInterceptor();

			MyInterfaceImpl target = new MyInterfaceImpl();

			object proxy = generator.CreateInterfaceProxyWithTarget(
				typeof (IMyInterface), target, proxyGenerationOptions, interceptor);

			Assert.IsNotNull(proxy);
			Assert.IsTrue(typeof (IMyInterface).IsAssignableFrom(proxy.GetType()));

			Assert.IsFalse(interceptor.Invoked);

			ISimpleMixin mixin = proxy as ISimpleMixin;
			Assert.IsNotNull(mixin);
			Assert.AreEqual(1, mixin.DoSomething());

			Assert.IsTrue(interceptor.Invoked);
			Assert.AreSame(proxy, interceptor.proxy);
			Assert.AreSame(mixin_instance, interceptor.mixin);
		}
		public void Should_detect_and_report_setting_null_as_target_for_Mixin_methods()
		{
			var options = new ProxyGenerationOptions();
			options.AddMixinInstance(new Two());
			var interceptor = new ChangeTargetInterceptor(null);
			var proxy = generator.CreateInterfaceProxyWithTargetInterface(typeof(IOne),
			                                                              new One(),
			                                                              options,
			                                                              interceptor);

			Assert.Throws(typeof(NotImplementedException), () =>
			                                               (proxy as ITwo).TwoMethod());
		}
Ejemplo n.º 50
0
		public void CanCreateSimpleMixinWithoutGettingExecutionEngineExceptionsOrBadImageExceptions()
		{
			ProxyGenerationOptions proxyGenerationOptions = new ProxyGenerationOptions();
			proxyGenerationOptions.AddMixinInstance(new SimpleMixin());
			object proxy = generator.CreateClassProxy(
				typeof (object), proxyGenerationOptions, new AssertInvocationInterceptor());

			Assert.IsTrue(proxy is ISimpleMixin);

			((ISimpleMixin) proxy).DoSomething();
		}
Ejemplo n.º 51
0
		public void LoadAssemblyIntoCache_DifferentGenerationOptions()
		{
			var savedScope = new ModuleScope(true);
			var builder = new DefaultProxyBuilder(savedScope);

			var options1 = new ProxyGenerationOptions();
			options1.AddMixinInstance(new DateTime());
			var options2 = ProxyGenerationOptions.Default;

			var cp1 = builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, options1);
			var cp2 = builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, options2);
			Assert.AreNotSame(cp1, cp2);
			Assert.AreSame(cp1, builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, options1));
			Assert.AreSame(cp2, builder.CreateClassProxyType(typeof (object), Type.EmptyTypes, options2));

			var path = savedScope.SaveAssembly();

			CrossAppDomainCaller.RunInOtherAppDomain(delegate(object[] args)
			                                         	{
			                                         		var newScope = new ModuleScope(false);
			                                         		var newBuilder = new DefaultProxyBuilder(newScope);

			                                         		var assembly = Assembly.LoadFrom((string) args[0]);
			                                         		newScope.LoadAssemblyIntoCache(assembly);

			                                         		var newOptions1 = new ProxyGenerationOptions();
			                                         		newOptions1.AddMixinInstance(new DateTime());
			                                         		var newOptions2 = ProxyGenerationOptions.Default;

			                                         		var loadedCP1 = newBuilder.CreateClassProxyType(typeof (object),
			                                         		                                                Type.EmptyTypes,
			                                         		                                                newOptions1);
			                                         		var loadedCP2 = newBuilder.CreateClassProxyType(typeof (object),
			                                         		                                                Type.EmptyTypes,
			                                         		                                                newOptions2);
			                                         		Assert.AreNotSame(loadedCP1, loadedCP2);
			                                         		Assert.AreEqual(assembly, loadedCP1.Assembly);
			                                         		Assert.AreEqual(assembly, loadedCP2.Assembly);
			                                         	}, path);

			File.Delete(path);
		}
		private ProxyGenerationOptions MixIn(object mixin)
		{
			var options = new ProxyGenerationOptions();
			options.AddMixinInstance(mixin);
			return options;
		}