/// <summary>
        /// Intercepts an exported value.
        /// </summary>
        /// <param name="value">The value to be intercepted.</param>
        /// <returns>Intercepted value.</returns>
        public object Intercept(object value)
        {
            var interfaces = value.GetType().GetInterfaces();

            ProxyFactory factory = new ProxyFactory(value);

            foreach (var intf in interfaces)
            {
                factory.AddInterface(intf);
            }

            if (this.advices != null)
            {
                foreach (var advice in this.advices)
                {
                    factory.AddAdvice(advice);
                }
            }
            else
            {
                foreach (var advisor in this.advisors)
                {
                    factory.AddAdvisor(advisor);
                }
            }

            return factory.GetProxy();
        }
Exemplo n.º 2
0
 public void Should_create_a_non_target_proxy_using_a_delegate()
 {
     Func<IMethodInvocation, object> del = delegate(IMethodInvocation mi) { return "ack"; };
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create<Goo>(del);
     Assert.Equal("ack", proxy.Go());
 }
        protected ProxyObjectReference(SerializationInfo info, StreamingContext context)
        {
            // Deserialize the base type using its assembly qualified name
            string qualifiedName = info.GetString("__baseType");
            _baseType = Type.GetType(qualifiedName, true, false);

            // Rebuild the list of interfaces
            List<Type> interfaceList = new List<Type>();
            int interfaceCount = info.GetInt32("__baseInterfaceCount");
            for(int i = 0; i < interfaceCount; i++)
            {
                string keyName = string.Format("__baseInterface{0}", i);
		string currentQualifiedName = info.GetString(keyName);
                Type interfaceType = Type.GetType(currentQualifiedName, true, false);

                interfaceList.Add(interfaceType);
            }

            // Reconstruct the proxy
            ProxyFactory factory = new ProxyFactory();
            Type proxyType = factory.CreateProxyType(_baseType, interfaceList.ToArray());

            // Initialize the proxy with the deserialized data
            object[] args = new object[] { info, context };
            _proxy = (IProxy)Activator.CreateInstance(proxyType, args);
        }
Exemplo n.º 4
0
 public void Should_create_a_non_target_proxy_using_an_anonymous_method()
 {
     Func<IMethodInvocation, object> del = mi => "ack";
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create<IFoo>( del );
     Assert.Equal("ack", proxy.Go());
 }
Exemplo n.º 5
0
 public void Should_create_a_proxy_using_a_target_object_and_a_lambda()
 {
     var target = new Goo();
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create(target, mi => mi.Method.Invoke(mi.Target, mi.Arguments));
     Assert.Equal("ack", proxy.Go());
 }
Exemplo n.º 6
0
 public void ProxyFactoryConstructorTest()
 {
     ITest test = ProxyFactory.CreateProxy<ITest>(typeof(RTest));
     object aaa = test.Test();
     ProxyFactory target = new ProxyFactory();
     Assert.Inconclusive("TODO: 实现用来验证目标的代码");
 }
Exemplo n.º 7
0
		/*----------------------------------------------------------------------------------------*/
		#region Disposal
		/// <summary>
		/// Releases all resources held by the object.
		/// </summary>
		/// <param name="disposing"><see langword="True"/> if managed objects should be disposed, otherwise <see langword="false"/>.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && !IsDisposed)
				_factory = null;

			base.Dispose(disposing);
		}
Exemplo n.º 8
0
 public void Should_create_a_non_target_proxy_using_a_generic_type_and_an_interceptor()
 {
     var interceptor = new ReturnValueInterceptor("ack");
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create<Goo>(interceptor);
     Assert.Equal("ack", proxy.Go());
 }
Exemplo n.º 9
0
 public void Should_create_a_proxy_using_a_lambda()
 {
     var target = new Foo();
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create<IFoo>(mi => target.Go()); //-> non-reflective call
     Assert.Equal("ack", proxy.Go());
 }
Exemplo n.º 10
0
        public void Test()
        {
            var proxyFactory = new ProxyFactory();

            var advisedFoo = proxyFactory.Create<IFoo>(new Foo(), new BarAdvice());

            advisedFoo.Bar();
        }
Exemplo n.º 11
0
 public void Should_create_a_non_target_proxy_using_a_lambda_and_a_list_of_types_to_implement()
 {
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create<IFoo>(mi => "ack", new[] { typeof(IDisposable), typeof(ICloneable) });
     Assert.Equal("ack", proxy.Go());
     Assert.True(typeof(IDisposable).IsAssignableFrom(proxy.GetType()));
     Assert.True(typeof(ICloneable).IsAssignableFrom(proxy.GetType()));
 }
Exemplo n.º 12
0
 public void Should_create_a_proxy_using_a_target_object_and_an_interceptor()
 {
     var interceptor = new ForwardExecutionInterceptor();
     var target = new Goo();
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create(target, interceptor);
     Assert.Equal("ack", proxy.Go());
 }
        public void TargetImplementsAnInterface()
        {
            ProxyFactory advisedSupport = new ProxyFactory(new TestObject());
            IAopProxy aopProxy = CreateAopProxy(advisedSupport);
            Assert.IsNotNull(aopProxy);

            Assert.IsTrue(AopUtils.IsCompositionAopProxy(aopProxy));
        }
		public void LazyFieldInterceptorIsBinarySerializable()
		{
			var pf = new ProxyFactory();
			var propertyInfo = typeof(MyClass).GetProperty("Id");
			pf.PostInstantiate("MyClass", typeof(MyClass), new HashedSet<System.Type>(), propertyInfo.GetGetMethod(), propertyInfo.GetSetMethod(), null);
			var fieldInterceptionProxy = (IFieldInterceptorAccessor)pf.GetFieldInterceptionProxy(new MyClass());
			fieldInterceptionProxy.FieldInterceptor = new DefaultFieldInterceptor(null, null, null, "MyClass", typeof(MyClass));

			fieldInterceptionProxy.Should().Be.BinarySerializable();
		}
Exemplo n.º 15
0
 public void Should_catch_an_exception_and_run_a_callback_before_and_after_the_exception_is_rethrown()
 {
     int ack = 0;
     var target = new Foo();
     var interceptor = new OnCatchAndOnFinallyInterceptor{ Action = ()=> { Assert.True(target.Executed); ++ack; } };
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create<IFoo>(target, interceptor);
     Assert.Throws<InvalidOperationException>(() => proxy.Fail());
     Assert.Equal(2, ack);
 }
Exemplo n.º 16
0
 public void Should_replace_target_execution_result()
 {
     var target = new Foo();
     var interceptor = new OnReturnInterceptor("ack");
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create<IFoo>(target, interceptor);
     proxy.Go();
     Assert.Equal("ack", proxy.Go());
     Assert.True(target.Executed);
 }
Exemplo n.º 17
0
 public void Should_run_a_callback_after_target_execution()
 {
     bool ack = false;
     var target = new Foo();
     var interceptor = new OnAfterInterceptor{ Action = ()=> { Assert.True(target.Executed); ack = true; } };
     var factory = new ProxyFactory(AppConfig.ProxyBehavior);
     var proxy = factory.Create<IFoo>(target, interceptor);
     proxy.Go();
     Assert.True(ack);
 }
Exemplo n.º 18
0
        public void IsDecoratorProxy()
        {
            var pf = new ProxyFactory(new DebugAdvice());
            pf.Target = _target;
            pf.ProxyTargetType = true;

            var proxy = (TestObject)pf.GetProxy();
            Assert.True(AopUtils.IsDecoratorAopProxy(proxy));
            Assert.True(AopUtils.IsAopProxy(proxy));
        }
        public void TargetImplementsAnInterfaceWithProxyTargetTypeSetToTrue()
        {
            ProxyFactory advisedSupport = new ProxyFactory();
            advisedSupport.ProxyTargetType = true;
            advisedSupport.Target = new TestObject();

            IAopProxy aopProxy = CreateAopProxy(advisedSupport);
            Assert.IsNotNull(aopProxy);
            Assert.IsTrue(AopUtils.IsDecoratorAopProxy(aopProxy));
        }
        public void DoesNotCacheWithDifferentTargetType()
        {
            ProxyFactory advisedSupport = new ProxyFactory(new BadCommand());
            CreateAopProxy(advisedSupport);

            advisedSupport = new ProxyFactory(new GoodCommand());
            CreateAopProxy(advisedSupport);

            AssertAopProxyTypeCacheCount(2);
        }
Exemplo n.º 21
0
        public void when_proxy_factory_invoked_then_gets_implementation_of_interface()
        {
            var factory = new ProxyFactory();
            var mock = new TestMock();

            var proxy = factory.CreateProxy(mock, typeof(ICalculator));

            Assert.NotNull(proxy);
            Assert.True(proxy is ICalculator);
        }
Exemplo n.º 22
0
        public void Spring_behavior_does_not_support_non_target_proxies_on_types_without_a_default_constructor()
        {
            var expected = "ack";
            var spring = new ProxyFactory(ProxyBehavior.Spring);
            Assert.Throws<InvalidOperationException>(()=> spring.Create<Hoo>(mi => expected).Name);

            // linfu does...
            var linfu = new ProxyFactory(ProxyBehavior.LinFu);
            Assert.Same(expected, linfu.Create<Hoo>(mi => expected).Name);
        }
Exemplo n.º 23
0
        public void Example_of_how_to_create_an_interface_proxy_implementign_IInterceptor()
        {
            var target = new Foo();
            var interceptor = new IInterceptorImpl();
            var factory = new ProxyFactory(ProxyBehavior.Castle);
            var foo = factory.Create<IFoo>(target, interceptor);

            foo.Go("SLC");
            foo.Go("SLC", "MEX");
            Assert.Throws<ArgumentNullException>(() => foo.Go("SLC", null));
        }
        private object InitExternalContext()
        {
            string providerDirectory = GetProviderDirectory();
            _request.Verbose("Loading Zero Install OneGet provider from {0}", providerDirectory);

            var assembly = Assembly.LoadFrom(Path.Combine(providerDirectory, "ZeroInstall.OneGet.dll"));
            var requestType = assembly.GetType("PackageManagement.Sdk.Request", throwOnError: true);
            object requestProxy = new ProxyFactory().CreateProxy(requestType, new RequestInterceptor(_request));
            var contextType = assembly.GetType("ZeroInstall.OneGet.OneGetContext", throwOnError: true);
            return Activator.CreateInstance(contextType, requestProxy);
        }
Exemplo n.º 25
0
        public void when_proxy_instance_called_then_can_retrieve_mock_from_invocation()
        {
            var factory = new ProxyFactory();
            var mock = new TestMock(defaultValue: 15);

            var proxy = (ICalculator)factory.CreateProxy(mock, typeof(ICalculator));

            proxy.Add(5, 10);

            Assert.Same(mock, mock.LastCall.Mock);
        }
Exemplo n.º 26
0
        public void when_proxy_instance_called_then_can_retrieve_invocation_method()
        {
            var factory = new ProxyFactory();
            var mock = new TestMock(defaultValue: 10);

            var proxy = (ICalculator)factory.CreateProxy(mock, typeof(ICalculator));

            proxy.Add(5, 5);

            Assert.Equal(typeof(ICalculator).GetMethod("Add"), mock.LastCall.Method);
        }
Exemplo n.º 27
0
        public void when_proxy_instance_called_then_calls_back_into_mock_behavior()
        {
            var factory = new ProxyFactory();
            var mock = new TestMock(defaultValue: 10);

            var proxy = (ICalculator)factory.CreateProxy(mock, typeof(ICalculator));

            proxy.Add(5, 5);

            Assert.NotNull(mock.LastCall);
        }
 public void TargetDoesNotImplementAnyInterfaces()
 {
     ProxyFactory advisedSupport = new ProxyFactory();
     advisedSupport.AopProxyFactory = new DefaultAopProxyFactory();
     advisedSupport.ProxyTargetType = false;
     advisedSupport.Target = new DoesNotImplementAnyInterfacesTestObject();
     
     IAopProxy aopProxy = CreateAopProxy(advisedSupport);
     Assert.IsNotNull(aopProxy);
     Assert.IsTrue(AopUtils.IsDecoratorAopProxy(aopProxy));
 }
        public void DoesNotCacheWithDifferentProxyTargetAttributes()
        {
            ProxyFactory advisedSupport = new ProxyFactory(new GoodCommand());
            advisedSupport.ProxyTargetAttributes = true;
            CreateAopProxy(advisedSupport);

            advisedSupport = new ProxyFactory(new GoodCommand());
            advisedSupport.ProxyTargetAttributes = false;
            CreateAopProxy(advisedSupport);

            AssertAopProxyTypeCacheCount(2);
        }
Exemplo n.º 30
0
        public void when_proxy_instance_called_then_can_retrieve_invocation_arguments()
        {
            var factory = new ProxyFactory();
            var mock = new TestMock(defaultValue: 15);

            var proxy = (ICalculator)factory.CreateProxy(mock, typeof(ICalculator));

            proxy.Add(5, 10);

            Assert.Equal(5, (int)mock.LastCall.Arguments[0]);
            Assert.Equal(10, (int)mock.LastCall.Arguments[1]);
        }
Exemplo n.º 31
0
        public void AdviceShouldBeCalledWhenPointcutSaysSo()
        {
            //Arrange
            var config       = new TestBaseConfiguration();
            var mockedAdvice = new Mock <IAdvice>();

            config.Add(mockedAdvice.Object, new AlwaysApplyAdvice());
            var proxied = ProxyFactory.Create <ITestInterface>(new TestClass(), config);

            //Act
            proxied.Foo();

            //Assert
            mockedAdvice.Verify(x => x.ApplyAdvice(It.IsAny <IInvocation>()), Times.Once());
        }
Exemplo n.º 32
0
        public void DontCreateProxyWhenNoAdvicesCanBeApplied()
        {
            //Arrange
            var instance = new TestClass();
            var config   = new TestBaseConfiguration();
            var advice   = new TestAdvice();

            config.Add(advice, new NeverApplyAdvice());

            //Act
            var proxied = ProxyFactory.Create(instance, config);

            //Assert
            Assert.AreEqual(instance, proxied);
        }
Exemplo n.º 33
0
        public void DoesNotCacheWithDifferentBaseType()
        {
            // Decorated-based proxy (BaseType == TargetType)
            ProxyFactory advisedSupport = new ProxyFactory(new TestObject());

            advisedSupport.ProxyTargetType = true;
            CreateAopProxy(advisedSupport);

            // Composition-based proxy (BaseType = BaseCompositionAopProxy)
            advisedSupport = new ProxyFactory(new TestObject());
            advisedSupport.ProxyTargetType = false;
            CreateAopProxy(advisedSupport);

            AssertAopProxyTypeCacheCount(2);
        }
Exemplo n.º 34
0
        private static void Around()
        {
            ProxyFactory factory = new ProxyFactory(new OrderService()
            {
                UserName = "******"
            });

            factory.AddAdvice(new AroundAdvise());
            IOrderService service = (IOrderService)factory.GetProxy();
            object        result  = service.Save(1);

            Console.WriteLine(result);

            Console.ReadLine();
        }
Exemplo n.º 35
0
 /// <summary>
 /// Gets the proxy by applying throw advices.
 ///
 /// </summary>
 /// <param name="target"></param>
 /// <returns></returns>
 public static object GetProxy(object target)
 {
     try
     {
         ProxyFactory           proxyFactory             = new ProxyFactory(target);
         DefaultPointcutAdvisor exceptionHandlingAdvisor =
             new DefaultPointcutAdvisor(aASAExceptionAdvice);
         proxyFactory.AddAdvisor(exceptionHandlingAdvisor);
         return(proxyFactory.GetProxy());
     }
     catch (Exception ex)
     {
         return(new ASAException("ASAExceptionAdvice failed  " + ex.Message));
     }
 }
Exemplo n.º 36
0
 /// <summary>Creates a clone of this proxy, with a new identity and optionally other options. The clone
 /// is identical to this proxy except for its identity and other options set through parameters.</summary>
 /// <param name="prx">The source proxy.</param>
 /// <param name="identity">The identity of the clone.</param>
 /// <param name="factory">The proxy factory used to manufacture the clone.</param>
 /// <param name="adapterId">The adapter ID of the clone (optional).</param>
 /// <param name="cacheConnection">Determines whether or not the clone caches its connection (optional).</param>
 /// <param name="clearLocator">When set to true, the clone does not have an associated locator proxy (optional).
 /// </param>
 /// <param name="clearRouter">When set to true, the clone does not have an associated router proxy (optional).
 /// </param>
 /// <param name="compress">Determines whether or not the clone compresses requests (optional).</param>
 /// <param name="connectionId">The connection ID of the clone (optional).</param>
 /// <param name="connectionTimeout">The connection timeout of the clone (optional).</param>
 /// <param name="context">The context of the clone (optional).</param>
 /// <param name="encoding">The encoding of the clone (optional).</param>
 /// <param name="endpointSelection">The encoding selection policy of the clone (optional).</param>
 /// <param name="endpoints">The endpoints of the clone (optional).</param>
 /// <param name="facet">The facet of the clone (optional).</param>
 /// <param name="fixedConnection">The connection of the clone (optional). When specified, the clone is a fixed
 /// proxy. You can clone a non-fixed proxy into a fixed proxy but not vice-versa.</param>
 /// <param name="invocationMode">The invocation mode of the clone (optional).</param>
 /// <param name="invocationTimeout">The invocation timeout of the clone (optional).</param>
 /// <param name="locator">The locator proxy of the clone (optional).</param>
 /// <param name="locatorCacheTimeout">The locator cache timeout of the clone (optional).</param>
 /// <param name="oneway">Determines whether the clone is oneway or twoway (optional). This is a simplified
 /// version of the invocationMode parameter.</param>
 /// <param name="preferNonSecure">Determines whether the clone prefers non-secure connections over secure
 /// connections (optional).</param>
 /// <param name="protocol">The Ice protocol of the clone (optional).</param>
 /// <param name="router">The router proxy of the clone (optional).</param>
 /// <returns>A new proxy manufactured by the proxy factory (see factory parameter).</returns>
 public static T Clone <T>(this IObjectPrx prx,
                           Identity identity,
                           ProxyFactory <T> factory,
                           string?adapterId      = null,
                           bool?cacheConnection  = null,
                           bool clearLocator     = false,
                           bool clearRouter      = false,
                           bool?compress         = null,
                           string?connectionId   = null,
                           int?connectionTimeout = null,
                           IReadOnlyDictionary <string, string>?context = null,
                           Encoding?encoding = null,
                           EndpointSelectionType?endpointSelection = null,
                           IEnumerable <Endpoint>?endpoints        = null,
                           string?facet = null,
                           Connection?fixedConnection    = null,
                           InvocationMode?invocationMode = null,
                           int?invocationTimeout         = null,
                           ILocatorPrx?locator           = null,
                           TimeSpan?locatorCacheTimeout  = null,
                           bool?oneway          = null,
                           bool?preferNonSecure = null,
                           Protocol?protocol    = null,
                           IRouterPrx?router    = null) where T : class, IObjectPrx
 {
     return(factory(prx.IceReference.Clone(adapterId,
                                           cacheConnection,
                                           clearLocator,
                                           clearRouter,
                                           compress,
                                           connectionId,
                                           connectionTimeout,
                                           context,
                                           encoding,
                                           endpointSelection,
                                           endpoints,
                                           facet,
                                           fixedConnection,
                                           identity,
                                           invocationMode,
                                           invocationTimeout,
                                           locator,
                                           locatorCacheTimeout,
                                           oneway,
                                           preferNonSecure,
                                           protocol,
                                           router)));
 }
Exemplo n.º 37
0
        public bool Open(string registrationServerNameOrAddress, int registrationServerPort, int listenerPort)
        {
            if (_host == null)
            {
                try
                {
                    //Open a connection to the registration server
                    var       addressList = Dns.GetHostEntry(registrationServerNameOrAddress).AddressList;
                    IPAddress address     = null;
                    foreach (var a in addressList)
                    {
                        if (a.AddressFamily == AddressFamily.InterNetwork)
                        {
                            address = a;
                            break;
                        }
                    }

                    var registrationServerEndPoint = new IPEndPoint(address, registrationServerPort);
                    _registrationServerProxy =
                        ProxyFactory.CreateProxy <IRegistrationServer>(registrationServerEndPoint);

                    //get node hosts that are already registered
                    _remoteHosts.Clear();
                    var remoteHostEndPoints = _registrationServerProxy.GetAllHostEndPoints();
                    foreach (var remoteHostEndPoint in remoteHostEndPoints)
                    {
                        INodeHost remoteHost = ProxyFactory.CreateProxy <INodeHost>(remoteHostEndPoint);
                        _remoteHosts.Add(remoteHost.GetId(), remoteHost);
                    }

                    //open the host that contains this node
                    _host = new ServiceHost(this, listenerPort);
                    _host.Open();

                    //Register the host with the registration server. This causes all other registered nodes to connect to this one
                    _registrationServerProxy.RegisterHost(_host.EndPoint);
                    return(true);
                }
                catch (Exception ex)
                {
                    string msg = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                    Log.Error("Could not connect to registration server. Message reads : {0}", msg);
                }
            }

            return(false);
        }
Exemplo n.º 38
0
        public void ShouldCacheProxyTypes()
        {
            var  factory  = new ProxyFactory();
            Type baseType = typeof(ISampleService);

            Type proxyType = factory.CreateProxyType(baseType, new Type[0]);
            int  runCount  = 10;

            // All subsequent results must return the same proxy type
            for (int i = 0; i < runCount; i++)
            {
                Type currentType = factory.CreateProxyType(baseType, new Type[0]);
                Assert.AreEqual(proxyType, currentType);
                Assert.AreSame(proxyType, currentType);
            }
        }
        public UnitTestRunReportingListener(string testReportHost, int port = 80, ILogger logger = null)
        {
            Logger = logger ?? Log.Default;
            ProxyFactory       proxyFactory = new ProxyFactory();
            HashSet <Assembly> reference    = new HashSet <Assembly>()
            {
                typeof(TestMethod).Assembly, typeof(ConsoleMethod).Assembly
            };

            TestReportService = proxyFactory.GetProxy <TestReportService>(testReportHost, port, reference);
            TestReportHost    = testReportHost;
            _testSuiteExecutionLookupByTitle  = new ConcurrentDictionary <string, TestSuiteExecutionSummary>();
            _testSuiteDefinitionLookupByTitle = new ConcurrentDictionary <string, TestSuiteDefinition>();
            _testDefinitionLookupByTitle      = new ConcurrentDictionary <string, TestDefinition>();
            _testExecutionLookupByMethodInfo  = new ConcurrentDictionary <MethodInfo, TestExecution>();
        }
Exemplo n.º 40
0
        protected override IInventorRepository CreateInventorStore()
        {
            Region region = CreateRegion();

            cache = new GemFireCache(region);

            context.ObjectFactory.RegisterSingleton("inventors", cache);


            ProxyFactory pf = new ProxyFactory(new InventorRepository());

            pf.AddAdvisors(cacheAspect);

            Repository = (IInventorRepository)pf.GetProxy();
            return(Repository);
        }
Exemplo n.º 41
0
        public void UriOverride_Basic()
        {
            string uri = "http://localhost/urioverride";

            using (var host = new ServiceHost(typeof(UriOverride), new Uri(uri)))
            {
                host.AddServiceEndpoint(typeof(IUriOverride), new WS2007HttpBinding(SecurityMode.None), uri);
                host.Open();

                var factory = new ProxyFactory();
                factory.AddEndpointAddressOverride <IUriOverride>(new Uri(uri));

                var proxy = factory.Proxy <IUriOverride>();
                Assert.AreEqual("test", proxy.TestMe("test"));
            }
        }
Exemplo n.º 42
0
        public void TimeoutTest()
        {
            string uri = "http://localhost:9595/timeouttest";

            using (var host = new ServiceHost(typeof(TimeoutTest), new Uri(uri)))
            {
                host.AddServiceEndpoint(typeof(ITimeoutTest), new WS2007HttpBinding(SecurityMode.None), uri);
                host.Open();

                var factory = new ProxyFactory();

                var proxy = factory.Proxy <ITimeoutTest>();

                Assert.AreEqual("hi", proxy.TestMe());
            }
        }
Exemplo n.º 43
0
        private void Dispatch <RECORD, REPORT>(RecordType type, ProxyFactory <REPORT> factory, RECORD record, RecordCheck <RECORD, REPORT> checker) where RECORD : Org.Neo4j.Kernel.impl.store.record.AbstractBaseRecord where REPORT : ConsistencyReport
        {
            ReportInvocationHandler <RECORD, REPORT> handler = new ReportHandler <RECORD, REPORT>(_report, factory, type, _records, record, _monitor);

            try
            {
                checker.Check(record, handler, _records);
            }
            catch (Exception e)
            {
                // This is a rare event and exposing the stack trace is a good idea, otherwise we
                // can only see that something went wrong, not at all what.
                handler.ReportConflict.error(type, record, "Failed to check record: " + stringify(e), new object[0]);
            }
            handler.UpdateSummary();
        }
Exemplo n.º 44
0
    public static object GetProxy(object target)
    {
        ProxyFactory factory = GetFactory(target);

        object proxy = factory.GetProxy();

        if (target is ProxyTypeObject)
        {
            // step 2:
            // hack: hook handlers ...
            var targetAsProxyTypeObject = (ProxyTypeObject)target;
            var proxyAsProxyTypeObject  = (ProxyTypeObject)proxy;
            HookHandlers(targetAsProxyTypeObject, proxyAsProxyTypeObject);
        }
        return(proxy);
    }
Exemplo n.º 45
0
        public void Test()
        {
            ICommand     target  = new BusinessCommand();
            ProxyFactory factory = new ProxyFactory(target);

            factory.AddAdvice(new ConsoleLoggingAroundAdvice());
            object obj = factory.GetProxy();


            ICommand business = (ICommand)obj;

            Console.WriteLine(obj.GetType().ToString());
            //ICommand command = (ICommand)factory.GetProxy();
            business.Execute("tyb");
            target.Execute("This is the argument");
        }
Exemplo n.º 46
0
        public void Hosted_HTTP()
        {
            string uri = "http://localhost/servicehelpers";

            using (var host = new ServiceHost(typeof(ExternalService), new Uri(uri)))
            {
                host.AddServiceEndpoint(typeof(IExternalService), new WS2007HttpBinding(), uri);
                host.Open();

                var factory = new ProxyFactory();
                factory.Call <IExternalService>(call =>
                {
                    Assert.AreEqual("hi", call.TestMe("hi"));
                });
            }
        }
Exemplo n.º 47
0
        public void Hosted_TCP()
        {
            string uri = "net.tcp://localhost:10095/servicehelpersTCP";

            using (var host = new ServiceHost(typeof(ExternalServiceTcp), new Uri(uri)))
            {
                host.AddServiceEndpoint(typeof(IExternalServiceTcp), new NetTcpBinding(), uri);
                host.Open();

                var factory = new ProxyFactory();
                factory.Call <IExternalServiceTcp>(call =>
                {
                    Assert.AreEqual("hi", call.TestMe("hi"));
                });
            }
        }
Exemplo n.º 48
0
        async void OnCancelReservation()
        {
            var proxy    = ProxyFactory.GetProxyInstace();
            var response = await proxy.ExecuteAsync(API.Endpoints.ReservationsEndpoints.CancelReservation(reservation.Id));

            if (response.Successful)
            {
                OnCancelled?.Invoke(this, reservation);
                Toast.MakeText(this, "Reservation cancelled successfully!", ToastLength.Short).Show();
                Finish();
            }
            else
            {
                Toast.MakeText(this, "Failed cancelling reservation", ToastLength.Short).Show();
            }
        }
Exemplo n.º 49
0
        static void Main(string[] args)
        {
            //Person p=new Person();
            //  p.Pen=new Pen();
            //  p.Write();

            ProxyFactory proxy = new ProxyFactory(new Pen());

            //proxy.AddAdvice(new BeforeAdvice());
            proxy.AddAdvice(new AroundAdvice());
            IWrite p = proxy.GetProxy() as IWrite;

            p.Write();

            Console.ReadKey();
        }
Exemplo n.º 50
0
        static void Main()
        {
            TestInterceptor interceptor = new TestInterceptor(new TestClass());
            ProxyFactory    factory     = new ProxyFactory();

            TestClass test = factory.CreateProxy <TestClass>(interceptor);

            // Turn it back on and replace
            // the method call with the one
            // in the interceptor
            Console.Write("Interception On: ");
            test.DoSomething();

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
        private void SubscribeOnEmailService()
        {
            ProxyFactory proxyFactory = new ProxyFactory();

            this.subscriberProxy = proxyFactory.CreateProxy <SubscriberProxy, ISubscriber>(callTracker, EndpointNames.SubscriberEndpoint);

            if (subscriberProxy == null)
            {
                string message = "SubscribeOnEmailService() => SubscriberProxy is null.";
                Logger.LogError(message);
                throw new NullReferenceException(message);
            }

            subscriberProxy.Subscribe(Topic.OUTAGE_EMAIL);
            Logger.LogDebug("Successfully subscribed to Email Service messages.");
        }
Exemplo n.º 52
0
        private static void Test(ProxyFactory <ITestInterface> factory)
        {
            var proxyOfTestClass = factory.GenerateProxy(new TestClass());

            Console.WriteLine(proxyOfTestClass.GetCalls()); // 0
            proxyOfTestClass.Sleep1s();
            proxyOfTestClass.Sleep2s();
            Console.WriteLine(proxyOfTestClass.GetCalls()); // 2
            proxyOfTestClass.Sleep1s();
            proxyOfTestClass.Sleep2s();
            Console.WriteLine(proxyOfTestClass.GetCalls()); // Still 2
            Thread.Sleep(5000);
            proxyOfTestClass.Sleep1s();
            proxyOfTestClass.Sleep2s();
            Console.WriteLine(proxyOfTestClass.GetCalls()); // 4
        }
Exemplo n.º 53
0
        public void InterceptInterfaceVirtualMethod()
        {
            ProxyFactory   factory     = new ProxyFactory();
            NopInterceptor interceptor = new NopInterceptor(new ProxyTestClass("test", 0));

            object proxy = factory.CreateProxy(typeof(ProxyTestClass), interceptor);

            Assert.IsTrue(proxy is IProxy);
            Assert.IsTrue(proxy is IProxyTest);
            Assert.IsTrue(proxy is ProxyTestClass);

            IProxyTest proxyTest = proxy as IProxyTest;

            Assert.AreEqual("test", proxyTest.GetName());
            Assert.AreEqual(1, interceptor.Count);
        }
        public void TestAutomaticInterfaceRecognitionInDelegate()
        {
            IIntroductionAdvisor ia = new DefaultIntroductionAdvisor(new Test(EXPECTED_TIMESTAMP));

            TestObject   target = new TestObject();
            ProxyFactory pf     = new ProxyFactory(target);

            pf.AddIntroduction(0, ia);

            ITimeStamped ts = (ITimeStamped)pf.GetProxy();

            Assert.IsTrue(ts.TimeStamp == EXPECTED_TIMESTAMP);
            ((ITest)ts).Foo();

            int age = ((ITestObject)ts).Age;
        }
Exemplo n.º 55
0
        /// <summary>
        /// Wraps an interface. The target argument must be an
        /// object capable of responding to the interface messages, or
        /// your interceptors must be capable of respoding to them.
        /// </summary>
        /// <param name="classType">Concrete class with a available constructor (public or protected) to be wrapped</param>
        /// <returns>A proxy</returns>
        public virtual object WrapClass(Type classType, params object[] constructorArgs)
        {
            AssertUtil.ArgumentNotNull(classType, "classType");
            AssertUtil.ArgumentNotInterface(classType, "classType");

            AspectDefinition[] aspects = AspectMatcher.Match(classType, Configuration.Aspects);

            if (aspects.Length == 0)
            {
                return(Activator.CreateInstance(classType, constructorArgs));
            }

            AspectDefinition aspectdef = Union(aspects);

            return(ProxyFactory.CreateClassProxy(classType, aspectdef, constructorArgs));
        }
Exemplo n.º 56
0
        public void Should_support_methods_that_return_null()
        {
            var interceptorSource = new TestInterceptorSource(new[] { _concatenateInterceptor.Object });
            var proxiedObj        = new Mock <ITest>();

            proxiedObj.Setup(i => i.Intercepted(1)).Returns(() => null);
            var proxyFactory = new ProxyFactory <ITest>(interceptorSource, _interceptorManager);
            var proxy        = proxyFactory.GenerateProxy(proxiedObj.Object);

            string returnedValue = proxy.Intercepted(1);

            proxiedObj.Verify(i => i.Intercepted(1));
            _concatenateInterceptor.Verify();
            Assert.True(interceptorSource.CalledFindMatchingInterceptors);
            Assert.Null(returnedValue);
        }
Exemplo n.º 57
0
 public IExecution GetExecution(int key)
 {
     try
     {
         var          item    = _executions[key];
         ProxyFactory factory = new ProxyFactory(item);
         factory.AddAdvice(new InterceptorAdvice());
         IExecution command = (IExecution)factory.GetProxy();
         //return command;
         return(item);
     }
     catch (KeyNotFoundException e)
     {
         return(new EmptyExecution());
     }
 }
        public FunctionExecutor(SCADAModel scadaModel)
        {
            this.modelUpdateQueue            = new ConcurrentQueue <IWriteModbusFunction>();
            this.writeCommandQueue           = new ConcurrentQueue <IWriteModbusFunction>();
            this.readCommandQueue            = new ConcurrentQueue <IReadModbusFunction>();
            this.commandEvent                = new AutoResetEvent(true);
            this.modelUpdateQueueEmptyEvent  = new AutoResetEvent(false);
            this.writeCommandQueueEmptyEvent = new AutoResetEvent(false);
            this.proxyFactory                = new ProxyFactory();

            SCADAModel = scadaModel;
            SCADAModel.SignalIncomingModelConfirmation += EnqueueModelUpdateCommands;

            ConfigData   = SCADAConfigData.Instance;
            ModbusClient = new ModbusClient(ConfigData.IpAddress.ToString(), ConfigData.TcpPort);
        }
Exemplo n.º 59
0
        public void GenericInProc_Raw()
        {
            string uri = "net.tcp://localhost:10095/genericContractTCP";

            using (var host = new ServiceHost(typeof(GenericService), new Uri(uri)))
            {
                host.AddServiceEndpoint(typeof(IGenericContract), new NetTcpBinding(), uri);
                host.Open();

                var factory = new ProxyFactory();
                factory.Call <IGenericContract>(call =>
                {
                    Assert.AreEqual(10, call.Find(10));
                });
            }
        }
        static void Main(string[] args)
        {
            ProxySetting setting = new ProxySetting();

            setting.TransferSetting = TransferSettingGetter.Get;

            ProxyFactory factory = new ProxyFactory(setting, typeof(JsonTransferSerializer), typeof(HttpTransmitter));

            var proxy = factory.CreateProxy <IExampleService>();

            ConsoleHelper.ShowTextInfo("Any key to continue:");
            Console.ReadLine();
            var info = proxy.GetPlayerInfo("John Wang");

            ConsoleHelper.ShowPlayerInfo(info);
        }