Esempio n. 1
0
        public static void Invoke_Multiple_Parameters_Via_Params_Receives_Correct_Arguments()
        {
            object[] actualArgs   = null;
            object[] invokedArgs  = null;
            object[] expectedArgs = new object[] { 42, "testString", 5.0 };

            TestType_IMultipleParameterService proxy = DispatchProxy.Create <TestType_IMultipleParameterService, TestDispatchProxy>();

            ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
            {
                invokedArgs = args;
                return(String.Empty);
            };

            proxy.ParamsMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]);

            // All separate params should have become a single object[1] array
            Assert.True(invokedArgs != null && invokedArgs.Length == 1,
                        String.Format("Expected single element object[] but actual was {0}",
                                      invokedArgs == null ? "null" : invokedArgs.Length.ToString()));

            // That object[1] should contain an object[3] containing the args
            actualArgs = invokedArgs[0] as object[];
            Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length,
                        String.Format("Invoked expected object[] of length {0} but actual was {1}",
                                      expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString())));
            for (int i = 0; i < expectedArgs.Length; ++i)
            {
                Assert.True(expectedArgs[i].Equals(actualArgs[i]),
                            String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
                                          i, expectedArgs[i], actualArgs[i]));
            }
        }
Esempio n. 2
0
        public static T WithDispatchProxy <T>(object target) where T : class
        {
            var proxy = DispatchProxy.Create <T, DispatchProxyExampleDecorator <T> >();

            (proxy as DispatchProxyExampleDecorator <T>).Target = (T)target;
            return(proxy);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("========原始需求=========");
            User user = new User {
                Name = "Zoe", Age = 18
            };
            IUserService userService = new UserService();

            // 模拟增加一个用户
            userService.AddUser(user);

            Console.WriteLine("========动态代理 实现新需求=========");
            //1. 创建代理对象
            IUserService userService1 = DispatchProxy.Create <IUserService, MyProxy>();

            //2. 因为调用的是实例方法,需要传提具体类型
            ((MyProxy)userService1).TargetClass = new UserService();
            userService1.AddUser(user);

            Console.WriteLine("=============Castle.Core方式==============");
            //先实例化一个代理类生成器
            ProxyGenerator generator = new ProxyGenerator();
            //通过代理类生成器创建
            var u = generator.CreateInterfaceProxyWithTarget <IUserService>(new UserService(), new MyIntercept());

            u.AddUser(user);
            Console.ReadLine();
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            User user = new User {
                Name = "Zoe", Age = 18
            };

            #region 1
            //动态代理
            //1. 创建代理对象
            IUserService userService1 = DispatchProxy.Create <IUserService, MyDecorator>();
            //2. 因为调用的是实例方法,需要传提具体类型
            ((MyDecorator)userService1).TargetClass = new UserService();
            userService1.AddUser(user);

            #endregion
            // 2
            ProxyGenerator generator = new ProxyGenerator();
            //var u = generator.CreateInterfaceProxyWithTarget<IUserService>(new UserService(), new MyIntercept());

            //3
            var services = new ServiceCollection();

            var scope = services.BuildServiceProvider(validateScopes: true);

            CastleInterceptor castleInterceptor = new CastleInterceptor(scope);

            var u = (IUserService)generator.CreateInterfaceProxyWithTarget(typeof(IUserService), new UserService(), castleInterceptor);
            u.AddUser(user);
            u.AddUser(user);  //缓存
            u.Print();
            Console.ReadLine();
        }
Esempio n. 5
0
        public static void Proxy_Declares_Interface_Indexers()
        {
            TestType_IIndexerService proxy        = DispatchProxy.Create <TestType_IIndexerService, TestDispatchProxy>();
            PropertyInfo             propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("Item");

            Assert.NotNull(propertyInfo);
        }
Esempio n. 6
0
        public static void Create_Proxy_Derives_From_DispatchProxy_BaseType()
        {
            TestType_IHelloService proxy = DispatchProxy.Create <TestType_IHelloService, TestDispatchProxy>();

            Assert.NotNull(proxy);
            Assert.IsAssignableFrom <TestDispatchProxy>(proxy);
        }
Esempio n. 7
0
        public static void Proxy_Declares_Interface_Events()
        {
            TestType_IEventService proxy = DispatchProxy.Create <TestType_IEventService, TestDispatchProxy>();
            EventInfo eventInfo          = proxy.GetType().GetTypeInfo().GetDeclaredEvent("AddRemove");

            Assert.NotNull(eventInfo);
        }
Esempio n. 8
0
        public static void Invoke_Indexer_Setter_And_Getter_Invokes_Correct_Methods()
        {
            List <MethodInfo> invokedMethods = new List <MethodInfo>();

            TestType_IIndexerService proxy = DispatchProxy.Create <TestType_IIndexerService, TestDispatchProxy>();

            ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
            {
                invokedMethods.Add(method);
                return(null);
            };


            proxy["key"] = "testValue";
            string actualValue = proxy["key"];

            Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count));

            PropertyInfo propertyInfo = typeof(TestType_IIndexerService).GetTypeInfo().GetDeclaredProperty("Item");

            Assert.NotNull(propertyInfo);

            MethodInfo expectedMethod = propertyInfo.SetMethod;

            Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}",
                                                                                                        expectedMethod.Name, invokedMethods[0]));

            expectedMethod = propertyInfo.GetMethod;
            Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}",
                                                                                                        expectedMethod.Name, invokedMethods[1]));

            Assert.Null(actualValue);
        }
Esempio n. 9
0
        /// <summary>
        /// Gets an RPC proxy for the provided interface.
        /// </summary>
        /// <typeparam name="IT">The interface type.</typeparam>
        /// <param name="configuration">The configuration.</param>
        /// <returns></returns>
        public IT Proxy <IT>(ProxyConfiguration configuration)
        {
            // check type is interface
            TypeInfo typeInfo = typeof(IT).GetTypeInfo();

            if (!typeInfo.IsInterface)
            {
                throw new InvalidOperationException("A static RPC proxy must be derived from an interface");
            }

            // get contract attribute
            RpcContractAttribute contractAttr = typeInfo.GetCustomAttribute <RpcContractAttribute>();

            if (contractAttr == null)
            {
                throw new InvalidOperationException("A static RPC proxy must be decorated with a contract attribute");
            }

            // create proxy
            IT            proxy    = DispatchProxy.Create <IT, RpcProxy <IT> >();
            RpcProxy <IT> rpcProxy = (RpcProxy <IT>)(object) proxy;

            rpcProxy.Channel       = this;
            rpcProxy.Configuration = configuration;

            return(proxy);
        }
Esempio n. 10
0
        public static void Proxy_Declares_Interface_Properties()
        {
            TestType_IPropertyService proxy = DispatchProxy.Create <TestType_IPropertyService, TestDispatchProxy>();
            PropertyInfo propertyInfo       = proxy.GetType().GetTypeInfo().GetDeclaredProperty("ReadWrite");

            Assert.NotNull(propertyInfo);
        }
Esempio n. 11
0
        public static object ForceAdapt(object value, Type from, Type to, IInterceptor interceptor)
        {
            var dispatched = (DispatchedObject)DispatchProxy.Create(to, interceptor);

            dispatched.Implementation = value;
            return(dispatched);
        }
Esempio n. 12
0
        public static void Invoke_Multiple_Parameters_Receives_Correct_Arguments()
        {
            object[] invokedArgs  = null;
            object[] expectedArgs = new object[] { (int)42, "testString", (double)5.0 };

            TestType_IMultipleParameterService proxy = DispatchProxy.Create <TestType_IMultipleParameterService, TestDispatchProxy>();

            ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
            {
                invokedArgs = args;
                return(0.0);
            };

            proxy.TestMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]);

            Assert.True(invokedArgs != null && invokedArgs.Length == expectedArgs.Length,
                        String.Format("Expected {0} arguments but actual was {1}",
                                      expectedArgs.Length, invokedArgs == null ? "null" : invokedArgs.Length.ToString()));

            for (int i = 0; i < expectedArgs.Length; ++i)
            {
                Assert.True(expectedArgs[i].Equals(invokedArgs[i]),
                            String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
                                          i, expectedArgs[i], invokedArgs[i]));
            }
        }
Esempio n. 13
0
        public static void Create_Proxy_Implements_Internal_Interfaces()
        {
            TestType_InternalInterfaceService proxy = DispatchProxy.Create <TestType_PublicInterfaceService_Implements_Internal, TestDispatchProxy>();

            Assert.NotNull(proxy);

            // ensure we emit a valid attribute definition
            Type iactAttributeType = proxy.GetType().Assembly.GetType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute");

            Assert.NotNull(iactAttributeType);
            ConstructorInfo constructor = iactAttributeType.GetConstructor(new[] { typeof(string) });

            Assert.NotNull(constructor);
            PropertyInfo propertyInfo = iactAttributeType.GetProperty("AssemblyName");

            Assert.NotNull(propertyInfo);
            Assert.NotNull(propertyInfo.GetMethod);

            string name = "anAssemblyName";
            object attributeInstance = constructor.Invoke(new object[] { name });

            Assert.NotNull(attributeInstance);
            object actualName = propertyInfo.GetMethod.Invoke(attributeInstance, null);

            Assert.Equal(name, actualName);
        }
Esempio n. 14
0
        public static TInterface ToProxy <TInterface>(IProxyable proxyable)
        {
            var proxy = DispatchProxy.Create <TInterface, DelegatingDispatchProxy>();

            ((DelegatingDispatchProxy)(object)proxy).InvokeDelegate = proxyable.Invoke;
            return(proxy);
        }
Esempio n. 15
0
        public static void Invoke_Receives_Correct_Arguments()
        {
            object[] actualArgs = null;

            TestType_IHelloService proxy = DispatchProxy.Create <TestType_IHelloService, TestDispatchProxy>();

            ((TestDispatchProxy)proxy).CallOnInvoke = (method, args) =>
            {
                actualArgs = args;
                return(string.Empty);
            };

            proxy.Hello("testInput");

            object[] expectedArgs = new object[] { "testInput" };
            Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length,
                        string.Format("Invoked expected object[] of length {0} but actual was {1}",
                                      expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString())));
            for (int i = 0; i < expectedArgs.Length; ++i)
            {
                Assert.True(expectedArgs[i].Equals(actualArgs[i]),
                            string.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
                                          i, expectedArgs[i], actualArgs[i]));
            }
        }
Esempio n. 16
0
        public static T Creator(ReflectObject reflect)
        {
            T instance = DispatchProxy.Create <T, ReflectProxy <T> >();

            instance.Reflect = reflect;
            return(instance);
        }
        public static IWebElement Create(IElementLocator elementLocator, IEnumerable <By> bys)
        {
            var proxiedObject = DispatchProxy.Create <IWebElement, WebElementProxy>();

            (proxiedObject as WebElementProxy)?.SetParameters(elementLocator, bys);

            return(proxiedObject);
        }
Esempio n. 18
0
        public static T Create(T decorated, IProxyActions actions)
        {
            object proxy = DispatchProxy.Create <T, DynamicProxy <T> >();

            ((DynamicProxy <T>)proxy)._decorated = decorated;
            ((DynamicProxy <T>)proxy)._actions   = actions;
            return((T)proxy);
        }
Esempio n. 19
0
        public T GetForEmit <T>()
        {
            var tmp   = DispatchProxy.Create <T, SyncProxy>();
            var proxy = tmp as SyncProxy;

            proxy.Call = Call;
            return(tmp);
        }
        public static IRelationalCommand Create(IRelationalCommand instance)
        {
            var obj = DispatchProxy.Create <IRelationalCommand, RivenOracleRelationalCommandProxy>();

            (obj as RivenOracleRelationalCommandProxy)._command = instance;

            return(obj);
        }
Esempio n. 21
0
        public static T Create <T>(T instance)
        {
            object proxy = DispatchProxy.Create <T, AopProxy <T> >();

            ((AopProxy <T>)proxy).SetInstance(instance);

            return((T)proxy);
        }
Esempio n. 22
0
        public WrapperTest(Func <T, T> createWrapper)
        {
            T target = DispatchProxy.Create <T, TestProxy>();

            targetProxy          = target as TestProxy;
            targetProxy.Defaults = defaults;
            source = createWrapper(target);
        }
Esempio n. 23
0
 public T BuilderDecorator(Action <MethodInfo, object[]> beforeAction, Action <MethodInfo, object[], object> afterAction)
 {
     _proxy = DispatchProxy.Create <T, DecoratorProxy <T> >();
     ((DecoratorProxy <T>)_proxy).Wrapped      = this._component;
     ((DecoratorProxy <T>)_proxy).BeforeAction = beforeAction;
     ((DecoratorProxy <T>)_proxy).AfterAction  = afterAction;
     return((T)_proxy);
 }
        /// <summary>
        /// 创建代理的 IRelationalCommandBuilder
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static IRelationalCommandBuilder Create(IRelationalCommandBuilder instance)
        {
            var obj = DispatchProxy.Create <IRelationalCommandBuilder, RivenOracleRelationalCommandBuilderProxy>();

            (obj as RivenOracleRelationalCommandBuilderProxy)._builder = instance;

            return(obj);
        }
Esempio n. 25
0
        public static void Create_Proxy_Derives_From_DispatchProxy_BaseType()
        {
            TestType_IHelloService proxy = DispatchProxy.Create <TestType_IHelloService, TestDispatchProxy>();

            Assert.NotNull(proxy);
            Assert.True(typeof(TestDispatchProxy).GetTypeInfo().IsAssignableFrom(proxy.GetType().GetTypeInfo()),
                        String.Format("Proxy type {0} did not derive from {1}", proxy.GetType().Name, typeof(TestDispatchProxy).Name));
        }
Esempio n. 26
0
        public static T Create <T>(int timeout = 10000)
        {
            object result;

            result = DispatchProxy.Create <T, HttpInterfaceProxy>();
            ((HttpInterfaceProxy)result).TimeOut = timeout;
            return((T)result);
        }
Esempio n. 27
0
        static void Main(string[] args)
        {
            new YouTuService().SyncBook();

            var queryProxy = DispatchProxy.Create <ISql, SqlProxy>();

            Console.WriteLine("Hello World!");
        }
Esempio n. 28
0
        public static T Create <T>(IServiceProvider sp)
        {
            var serviceInstance = sp.GetService(typeof(T));
            var proxy           = DispatchProxy.Create <T, InvokeProxy>();

            ((InvokeProxy)(object)proxy).Initialize(typeof(T), serviceInstance);
            return(proxy);
        }
Esempio n. 29
0
        public static void Create_Same_Proxy_Type_And_Base_Type_Reuses_Same_Generated_Type()
        {
            TestType_IHelloService proxy1 = DispatchProxy.Create <TestType_IHelloService, TestDispatchProxy>();
            TestType_IHelloService proxy2 = DispatchProxy.Create <TestType_IHelloService, TestDispatchProxy>();

            Assert.NotNull(proxy1);
            Assert.NotNull(proxy2);
            Assert.IsType(proxy1.GetType(), proxy2);
        }
Esempio n. 30
0
        public TService DecorateWithTand <TService, TImplementation>(TImplementation toBeDecorated)
            where TService : class
            where TImplementation : class, TService
        {
            var proxy = DispatchProxy.Create <TService, TandProxy <TService> >();

            InitProxy <TService, TImplementation>(proxy, toBeDecorated);
            return(proxy);
        }
Esempio n. 31
0
File: Main.cs Progetto: mind0n/hive
		void Main_Load(object sender, EventArgs e)
		{
			var bind = new WSHttpBinding();
			bind.SendTimeout = new TimeSpan(0, 0, 0, 0, 100000);
			bind.OpenTimeout = new TimeSpan(0, 0, 0, 0, 100000);
			bind.Security.Mode = SecurityMode.Message;
			//bind.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
			bind.MaxReceivedMessageSize = 10000;
			var addr = new EndpointAddress("http://localhost:10023/FavUrl");
			proxy = new DispatchProxy(bind, addr);
			//proxy.ClientCredentials.UserName.UserName = "******";
			//proxy.ClientCredentials.UserName.Password = "******";
			

			//proxy.ClientCredentials.ClientCertificate.SetCertificate(
			//    StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "client.com"
			//);
		}