public InvokationLoggingMock()
        {
            var proxyGen = new Castle.DynamicProxy.ProxyGenerator();

            _interceptor = new CallLoggingInterceptor();
            Object       = proxyGen.CreateInterfaceProxyWithoutTarget <T>(_interceptor);
        }
Esempio n. 2
0
        public void Castle()
        {
            var gen   = new Castle.DynamicProxy.ProxyGenerator();
            var proxy = gen.CreateClassProxy <ItExtendsAnAbstractClass>(new CastleInterceptor());

            Assert.Equal(-3, proxy.Return(string.Empty));
        }
Esempio n. 3
0
        public void WriteDynamicProxyObjectTest()
        {
            var list           = new List <TestClass>();
            var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();

            for (var i = 0; i < 1; i++)
            {
                var proxy = proxyGenerator.CreateClassProxy <TestClass>();
                proxy.Id   = i + 1;
                proxy.Name = "name" + proxy.Id;
                list.Add(proxy);
            }

            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var csv = new CsvWriter(writer))
                        {
                            csv.Configuration.Delimiter = ",";
                            csv.Configuration.RegisterClassMap <TestClassMap>();
                            csv.WriteRecords(list);
                            writer.Flush();
                            stream.Position = 0;

                            var data     = reader.ReadToEnd();
                            var expected = new StringBuilder();
                            expected.AppendLine("id,name");
                            expected.AppendLine("1,name1");

                            Assert.AreEqual(expected.ToString(), data);
                        }
        }
Esempio n. 4
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            WebApiConfig.Register(config);

            var builder = new ContainerBuilder();

            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.Register(ctx =>
            {
                IZombieCreator zombieCreator = new ZombieCreator();

                ProxyGenerator generator = new ProxyGenerator();
                IZombieCreator proxy     = (IZombieCreator)generator.CreateInterfaceProxyWithTarget(
                    typeof(IZombieCreator),
                    zombieCreator,
                    new MethodCallLogging(LogManager.GetLogger(typeof(ZombieCreator))));

                return(proxy);
            }).SingleInstance();

            var container = builder.Build();

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);
        }
Esempio n. 5
0
        /// <summary>
        /// The real constructor is private because C# won't run the static constructor (which loads Castle.Core)
        /// before trying to at least somewhat interpret this method body, which contains a Castle reference.
        ///
        /// By making sure that all public constructors are indirected to a "real" method body by one step, assembly
        /// loading appears to work.
        /// </summary>
        private Fake(bool autoStub, object dummy)
        {
            var gen = new Castle.DynamicProxy.ProxyGenerator();

            interceptor = new Interceptor(autoStub);

            Object = gen.CreateInterfaceProxyWithoutTarget <TObj>(interceptor);
        }
        protected SerializationHelperFirst(SerializationInfo info, StreamingContext context)
        {
            _info = info;
            _context = context;

            Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();
            _proxy = (SimpleHardcodedPlusHelperProxy)
                generator.CreateClassProxy(typeof(SimpleHardcodedPlusHelperProxy), new Castle.Core.Interceptor.IInterceptor[0]);
        }
        public void SerializeDoubleProxy()
        {
            Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();
            SimpleHardcodedPlusHelperProxy proxy = (SimpleHardcodedPlusHelperProxy)
                generator.CreateClassProxy(typeof(SimpleHardcodedPlusHelperProxy), new Castle.Core.Interceptor.IInterceptor[0]);

            proxy.Name = "test";
            SimpleHardcodedPlusHelperProxy deserialized = (SimpleHardcodedPlusHelperProxy)Cloner.GetSerializedClone(proxy);

            Assert.AreEqual(deserialized.Name, "test");
        }
Esempio n. 8
0
        public static object CreateInterfaceProxyWithTargetInterface(Type interfaceType, object concreteObject)
        {
            var dynamicProxy = new Castle.DynamicProxy.ProxyGenerator();

            var result = dynamicProxy.CreateInterfaceProxyWithTargetInterface(
                interfaceType,
                concreteObject,
                new[] { new MyExInterceptor() });

            return(result);
        }
Esempio n. 9
0
        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            WarServices warServices = new WarServices();
            // Create an AOP proxy object that we can hang Castle.DynamicProxies upon. These are useful for operations across the whole
            //   of the service, or for when we need to fail a message in a reasonable way.
            var proxy = new Castle.DynamicProxy.ProxyGenerator()
                        .CreateClassProxyWithTarget <WarServices>(warServices, new Castle.DynamicProxy.IInterceptor[] {
                new UserQuotaInterceptor(), new AdminKeyRequiredInterceptor()
            });

            return(proxy);
        }
Esempio n. 10
0
        public void ProxiesAndHostsWCF()
        {
#if DEBUG
            // On release mode, castle is ILMerged into Moq.dll and this won't compile
            var generator = new Castle.DynamicProxy.ProxyGenerator();
            var proxy     = generator.CreateClassProxy <ServiceImplementation>();
            using (var host = new WebServiceHost(proxy, new Uri("http://localhost:7777")))
            {
                host.Open();
            }
#endif
        }
        private static void RunCastleDynamicProxy()
        {
            var proxy = new Castle.DynamicProxy.ProxyGenerator().CreateInterfaceProxyWithTarget <IProxyImplementInterface>(new TestProxyImplementInterface(), new ValidateInterceptor(), new LogInterceptor());

            CodeTimerAdvance.TimeByConsole("Castle.DynamicProxy.TestMethodWithRefAndOutParameter", COUNT, times =>
            {
                var a      = 1;
                var b      = new string[] { "2" };
                var c      = 0L;
                var result = proxy.TestMethodWithRefAndOutParameter(ref a, ref b, out c);
                if (result != c)
                {
                    throw new ApplicationException("Castle.DynamicProxy.TestMethodWithRefAndOutParameter fail");
                }
            });
            CodeTimerAdvance.TimeByConsole("Castle.DynamicProxy.TestNormalMethod", COUNT, times =>
            {
                var a      = 1;
                var b      = "2";
                var result = proxy.TestNormalMethod(a, b);
                if (result != (a + 1) + Convert.ToInt32(b))
                {
                    throw new ApplicationException($"Castle.DynamicProxy.TestNormalMethod fail, actual:{result}, expected:{(a + 1) + Convert.ToInt32(b)}");
                }
            });
            CodeTimerAdvance.TimeByConsole("Castle.DynamicProxy.TestMethodWithGenericParameter", COUNT, times =>
            {
                var a = 1;
                var b = "2";
                var c = new ValueA {
                    Value = 3
                };
                var result = proxy.TestMethodWithGenericParameter(a, b, new ValueA[] { c });
                if (result != (a + 1) + Convert.ToInt32(b) + c.Value)
                {
                    throw new ApplicationException($"Castle.DynamicProxy.TestMethodWithGenericParameter fail, actual:{result}, expected:{(a + 1) + Convert.ToInt32(b) + c.Value}");
                }
            });
            CodeTimerAdvance.TimeByConsole("Castle.DynamicProxy.TestMethodWithGenericParameterAndRefParameter", COUNT, times =>
            {
                var a = 1;
                var b = "2";
                var c = new ValueA {
                    Value = 3
                };
                var result = proxy.TestMethodWithGenericParameterAndRefParameter(a, b, ref c);
                if (result != c.Value)
                {
                    throw new ApplicationException("Castle.DynamicProxy.TestMethodWithGenericParameterAndRefParameter fail");
                }
            });
        }
        public override void Prepare()
        {
            var pg = new Castle.DynamicProxy.ProxyGenerator();

            this.container = new Container(r =>
            {
                r.For<ISingleton>().Singleton().Use<Singleton>();
                r.For<ITransient>().Transient().Use<Transient>();
                r.For<ICombined>().Transient().Use<Combined>();
                r.For<ICalculator>().Transient().Use<Calculator>()
                    .EnrichWith(c => pg.CreateInterfaceProxyWithTarget<ICalculator>(c, new StructureMapInterceptionLogger()));
            });
        }
Esempio n. 13
0
        public void Prepare()
        {
            var pg = new Castle.DynamicProxy.ProxyGenerator();

            this.container = new Container(r =>
            {
                r.For <ISingleton>().Singleton().Use <Singleton>();
                r.For <ITransient>().Transient().Use <Transient>();
                r.For <ICombined>().Transient().Use <Combined>();
                r.For <ICalculator>().Transient().Use <Calculator>()
                .EnrichWith(c => pg.CreateInterfaceProxyWithTarget <ICalculator>(c, new StructureMapInterceptionLogger()));
            });
        }
Esempio n. 14
0
        public static object GetBSO(Type type)
        {
            object result;

            if (!bsos.ContainsKey(type))
            {
                result = new Castle.DynamicProxy.ProxyGenerator().CreateClassProxy(type, txInterceptor);
                bsos.TryAdd(type, result);
            }
            else
            {
                result = bsos[type];
            }
            return(result);
        }
        protected override object VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
        {
            object[] parameterValues = new object[constructorCallSite.ParameterCallSites.Length];
            for (var index = 0; index < parameterValues.Length; index++)
            {
                parameterValues[index] = VisitCallSite(constructorCallSite.ParameterCallSites[index], scope);
            }

            try
            {
                var obj           = constructorCallSite.ConstructorInfo.Invoke(parameterValues);
                var interceptors  = InterceptorRuntimeCreate.CreatedInterceptors;
                var implementName = constructorCallSite.ImplementationType.FullName;
                if (interceptors != null && interceptors.Count > 0 &&
                    InterceptorRuntimeCreate.CanIntercept(implementName))
                {
                    Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();

                    if (constructorCallSite.ServiceType.IsInterface)
                    {
                        try
                        {
                            obj = generator.CreateInterfaceProxyWithTarget(constructorCallSite.ServiceType,
                                                                           obj,
                                                                           interceptors.ToArray());
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }
                    else if (constructorCallSite.ServiceType.IsClass &&
                             !constructorCallSite.ServiceType.IsAbstract &&
                             !constructorCallSite.ServiceType.IsSealed)
                    {
                        obj = generator.CreateClassProxyWithTarget(constructorCallSite.ServiceType, obj,
                                                                   parameterValues, interceptors.ToArray());
                    }
                }
                return(obj);
            }
            catch (Exception ex) when(ex.InnerException != null)
            {
                ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                // The above line will always throw, but the compiler requires we throw explicitly.
                throw;
            }
        }
Esempio n. 16
0
        /// <summary>
        /// 创建一个实例方式的拦截器
        /// </summary>
        /// <param name="proxyType"></param>
        /// <param name="target"></param>
        /// <param name="interceptors"></param>
        /// <returns></returns>
        public static object CreateProxy(Type proxyType, object target, params Castle.DynamicProxy.IInterceptor[] interceptors)
        {
            //如果拦截器为0
            if (interceptors.Length == 0)
            {
                return(target);
            }

            Castle.DynamicProxy.ProxyGenerator         proxy   = new Castle.DynamicProxy.ProxyGenerator();
            Castle.DynamicProxy.ProxyGenerationOptions options = new Castle.DynamicProxy.ProxyGenerationOptions(new ProxyGenerationHook())
            {
                Selector = new InterceptorSelector()
            };

            return(proxy.CreateInterfaceProxyWithTargetInterface(proxyType, target, options, interceptors));
        }
Esempio n. 17
0
        public void Test_MapTo_CastleProxy()
        {
            Castle.DynamicProxy.ProxyGenerator proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();
            var proxy = proxyGenerator.CreateClassProxy <DtoSample>();

            proxy.Name = "a";
            EntitySample sample = proxy.MapTo <EntitySample>();

            Assert.Equal("a", sample.Name);

            var proxy2 = proxyGenerator.CreateClassProxy <DtoSample>();

            proxy2.Name = "b";
            sample      = proxy2.MapTo <EntitySample>();
            Assert.Equal("b", sample.Name);
        }
        protected override object VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)
        {
            var obj           = factoryCallSite.Factory(scope);
            var interceptors  = InterceptorRuntimeCreate.CreatedInterceptors;
            var implementName = obj.GetType().FullName;

            if (interceptors != null && interceptors.Count > 0 &&
                factoryCallSite.ServiceType.IsInterface &&
                InterceptorRuntimeCreate.CanIntercept(implementName))
            {
                Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();
                obj = generator.CreateInterfaceProxyWithTarget(factoryCallSite.ServiceType,
                                                               obj,
                                                               interceptors.ToArray());
            }
            return(obj);
        }
    private static void Main(string[] args)
    {
        var msg = Message.CreateMessage(MessageVersion.Soap11, "*");

        msg.Headers.Clear();
        var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();
        var proxiedMessage = proxyGenerator.CreateClassProxyWithTarget(msg, new ProxyGenerationOptions(),
                                                                       new ToStringInterceptor());
        var initialResult = msg.ToString();
        var proxiedResult = proxiedMessage.ToString();

        Console.WriteLine("Initial result");
        Console.WriteLine(initialResult);
        Console.WriteLine();
        Console.WriteLine("Proxied result");
        Console.WriteLine(proxiedResult);
        Console.ReadLine();
    }
Esempio n. 20
0
        private void RegisterInterceptor()
        {
            var pg = new Castle.DynamicProxy.ProxyGenerator();

            this.container.Configure(
                ioc => ioc.Export <Calculator1>()
                .As <ICalculator1>()
                .EnrichWith((scope, context, o) => pg.CreateInterfaceProxyWithTarget(o as ICalculator1, new StructureMapInterceptionLogger())));

            this.container.Configure(
                ioc => ioc.Export <Calculator2>()
                .As <ICalculator2>()
                .EnrichWith((scope, context, o) => pg.CreateInterfaceProxyWithTarget(o as ICalculator2, new StructureMapInterceptionLogger())));

            this.container.Configure(
                ioc => ioc.Export <Calculator3>()
                .As <ICalculator3>()
                .EnrichWith((scope, context, o) => pg.CreateInterfaceProxyWithTarget(o as ICalculator3, new StructureMapInterceptionLogger())));
        }
Esempio n. 21
0
        private void RegisterInterceptor()
        {
            var pg = new Castle.DynamicProxy.ProxyGenerator();

            container.Configure(c =>
            {
                c.Export <Calculator1>().As <ICalculator1>();
                c.Export <Calculator2>().As <ICalculator2>();
                c.Export <Calculator3>().As <ICalculator3>();

                c.ExportDecorator <ICalculator1>(
                    calculator => pg.CreateInterfaceProxyWithTarget(calculator, new StructureMapInterceptionLogger()));

                c.ExportDecorator <ICalculator2>(
                    calculator => pg.CreateInterfaceProxyWithTarget(calculator, new StructureMapInterceptionLogger()));

                c.ExportDecorator <ICalculator3>(
                    calculator => pg.CreateInterfaceProxyWithTarget(calculator, new StructureMapInterceptionLogger()));
            });
        }
Esempio n. 22
0
        public void CompareEqualWithProxy()
        {
            var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();
            var decoratorUtil  = new DecoratorUtil();

            // Create the factory.
            var factory = new DebugMemoryContext.Factory();

            // Decorate the factory with a dummy aspect.
            var aspect           = new YetiCommon.Tests.CastleAspects.TestSupport.CallCountAspect();
            var factoryDecorator = decoratorUtil.CreateFactoryDecorator(proxyGenerator, aspect);
            var factoryWithProxy = factoryDecorator.Decorate(factory);

            var memoryContextWithProxy = factoryWithProxy.Create(TEST_PC, TEST_NAME);

            // Check all the combinations of comparing proxied and non-proxied memory context.
            uint matchIndex;

            Assert.AreEqual(VSConstants.S_OK, memoryContextWithProxy.Compare(
                                enum_CONTEXT_COMPARE.CONTEXT_EQUAL,
                                new IDebugMemoryContext2[1] {
                memoryContextWithProxy
            }, 1, out matchIndex));
            Assert.AreEqual(0, matchIndex);

            Assert.AreEqual(VSConstants.S_OK, memoryContext.Compare(
                                enum_CONTEXT_COMPARE.CONTEXT_EQUAL,
                                new IDebugMemoryContext2[1] {
                memoryContextWithProxy
            }, 1, out matchIndex));
            Assert.AreEqual(0, matchIndex);

            Assert.AreEqual(VSConstants.S_OK, memoryContextWithProxy.Compare(
                                enum_CONTEXT_COMPARE.CONTEXT_EQUAL,
                                new IDebugMemoryContext2[1] {
                memoryContext
            }, 1, out matchIndex));
            Assert.AreEqual(0, matchIndex);
        }
        protected override object VisitCreateInstance(CreateInstanceCallSite createInstanceCallSite, ServiceProviderEngineScope scope)
        {
            try
            {
                object obj;
                var    interceptors  = InterceptorRuntimeCreate.CreatedInterceptors;
                var    implementName = createInstanceCallSite.ImplementationType.FullName;
                if (interceptors != null && interceptors.Count > 0 &&
                    InterceptorRuntimeCreate.CanIntercept(implementName))
                {
                    Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();

                    if (createInstanceCallSite.ServiceType.IsInterface)
                    {
                        obj = generator.CreateClassProxy(createInstanceCallSite.ImplementationType,
                                                         new[] { createInstanceCallSite.ServiceType },
                                                         interceptors.ToArray());
                    }
                    else
                    {
                        obj = generator.CreateClassProxy(createInstanceCallSite.ImplementationType,
                                                         interceptors.ToArray());
                    }
                }
                else
                {
                    obj = Activator.CreateInstance(createInstanceCallSite.ImplementationType);
                }
                //return Activator.CreateInstance(createInstanceCallSite.ImplementationType);
                return(obj);
            }
            catch (Exception ex) when(ex.InnerException != null)
            {
                ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                // The above line will always throw, but the compiler requires we throw explicitly.
                throw;
            }
        }
Esempio n. 24
0
        /// <summary>
        /// 创建一个类型方式的拦截器(可传入参数)
        /// </summary>
        /// <param name="classType"></param>
        /// <param name="arguments"></param>
        /// <param name="interceptors"></param>
        /// <returns></returns>
        public static object CreateProxy(Type classType, object[] arguments, params Castle.DynamicProxy.IInterceptor[] interceptors)
        {
            //如果拦截器为0
            if (interceptors.Length == 0)
            {
                return(Activator.CreateInstance(classType, arguments));
            }

            Castle.DynamicProxy.ProxyGenerator         proxy   = new Castle.DynamicProxy.ProxyGenerator();
            Castle.DynamicProxy.ProxyGenerationOptions options = new Castle.DynamicProxy.ProxyGenerationOptions(new ProxyGenerationHook())
            {
                Selector = new InterceptorSelector()
            };

            if (arguments == null || arguments.Length == 0)
            {
                return(proxy.CreateClassProxy(classType, options, interceptors));
            }
            else
            {
                return(proxy.CreateClassProxy(classType, options, arguments, interceptors));
            }
        }
Esempio n. 25
0
        public void Test_MapTo_CastleProxy()
        {
            var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();
            var proxy          = proxyGenerator.CreateClassProxy <DtoSample>();

            proxy.Name = "a";
            var sample = proxy.MapTo <EntitySample>();

            Assert.Equal("a", sample.Name);

            var proxy2 = proxyGenerator.CreateClassProxy <DtoSample>();

            proxy2.Name = "b";
            sample      = proxy2.MapTo <EntitySample>();
            Assert.Equal("b", sample.Name);

            var sample2 = new DtoSample {
                Name = "c"
            };
            var proxy3 = proxyGenerator.CreateClassProxy <EntitySample>();

            sample2.MapTo(proxy3);
            Assert.Equal("c", proxy3.Name);
        }
Esempio n. 26
0
        /// <summary>
        /// Enables logging of specific mock instance
        /// </summary>
        /// <param name="methodsToIgnore">Specifies method or property names to ignore when logging
        /// (e.g. utility functions about which we don't care)</param>
        public static Mock <T> Logged <T>(this Mock <T> mock, params string[] methodsToIgnore) where T : class
        {
            object mockedObject = mock.Object;
            object proxy;

            if (proxygenerator == null)
            {
                proxygenerator = new Castle.DynamicProxy.ProxyGenerator();
            }

            if (typeof(T).IsInterface)
            {
                proxy = proxygenerator.CreateInterfaceProxyWithTarget(typeof(T), mockedObject, new LoggedMockInterceptor(methodsToIgnore));
            }
            else
            {
                proxy = proxygenerator.CreateClassProxyWithTarget(typeof(T), mockedObject, new LoggedMockInterceptor(methodsToIgnore));
            }

            var field = mock.GetType().GetField("instance", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            field.SetValue(mock, proxy);
            return(mock);
        }
        private static IUnityContainer GetDecoratingProxy(IUnityContainer container)
        {
            var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();

            return(proxyGenerator.CreateInterfaceProxyWithoutTarget <IUnityContainer>(new DecoratingInterceptor(container)));
        }
 public void UndoChangesSGO_CastleDynProxy()
 {
     Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();
     SimpleGenericObject<string> proxy = (SimpleGenericObject<string>)
     generator.CreateClassProxy(typeof(SimpleGenericObject<string>), new Castle.Core.Interceptor.IInterceptor[0]);
     proxy.GenericArray = new string[] { "test1", "test2" };
     proxy.GenericArray[0] = "test3";
     proxy.Code = "code1";
     Assert.AreEqual(proxy.Code, "code1");
     Assert.AreEqual(proxy.GenericArray[0], "test3");
 }
 public void SerializationCastleDynamicProxy2()
 {
     Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();
     SimpleBusinessObject proxy = (SimpleBusinessObject)
     generator.CreateClassProxy(typeof(SimpleBusinessObject), new Castle.Core.Interceptor.IInterceptor[0]);
     MemoryStream stream = new MemoryStream();
     BinaryFormatter formatter = new BinaryFormatter();
     formatter.Serialize(stream, proxy);
     stream.Position = 0;
     object deserializedObject = formatter.Deserialize(stream);
     Assert.IsNotNull(deserializedObject);
 }
        private void RegisterInterceptor()
        {
            var pg = new Castle.DynamicProxy.ProxyGenerator();

            this.container.Configure(
                ioc => ioc.Export<Calculator1>()
                .As<ICalculator1>()
                .EnrichWith((scope, context, o) => pg.CreateInterfaceProxyWithTarget(o as ICalculator1, new StructureMapInterceptionLogger())));

            this.container.Configure(
                ioc => ioc.Export<Calculator2>()
                .As<ICalculator2>()
                .EnrichWith((scope, context, o) => pg.CreateInterfaceProxyWithTarget(o as ICalculator2, new StructureMapInterceptionLogger())));

            this.container.Configure(
                ioc => ioc.Export<Calculator3>()
                .As<ICalculator3>()
                .EnrichWith((scope, context, o) => pg.CreateInterfaceProxyWithTarget(o as ICalculator3, new StructureMapInterceptionLogger())));
        }
Esempio n. 31
0
        /*
         * Application that uses Windows Communications Foundation (WCF) to provide a RESTful API that allows persistence of Morphyum's WarTech.
         * If you're unfamiliar with WCF, checkout the following:
         *
         * http://dotnetmentors.com/wcf/overview-on-wcf-service-architecture.aspx
         * https://docs.microsoft.com/en-us/dotnet/framework/wcf/extending/extending-dispatchers
         *
         * The client is the PersistentMapClient, in this repository.
         * This PersistentMapServer is the server.
         *
         * Note that WCF is no longer the preferred solution for REST endpoints, which has become ASP.NET5 w/ MVC6.
         *  See https://blog.tonysneed.com/2016/01/06/wcf-is-dead-long-live-mvc-6/.
         */
        static void Main(string[] args)
        {
            try {
                // Start a heart-beat monitor to check the server status
                BackgroundWorker heartbeatWorker = new BackgroundWorker {
                    WorkerSupportsCancellation = true
                };
                heartbeatWorker.DoWork             += new DoWorkEventHandler(HeartBeatMonitor.DoWork);
                heartbeatWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(HeartBeatMonitor.RunWorkerCompleted);
                heartbeatWorker.RunWorkerAsync();

                SettingsFileMonitor monitor = new SettingsFileMonitor();
                monitor.enable();

                BackgroundWorker playerHistoryPruner = new BackgroundWorker {
                    WorkerSupportsCancellation = true
                };
                playerHistoryPruner.DoWork             += new DoWorkEventHandler(PlayerHistoryPruner.DoWork);
                playerHistoryPruner.RunWorkerCompleted += new RunWorkerCompletedEventHandler(PlayerHistoryPruner.RunWorkerCompleted);
                playerHistoryPruner.RunWorkerAsync();

                BackgroundWorker backupWorker = new BackgroundWorker {
                    WorkerSupportsCancellation = true
                };

                backupWorker.DoWork             += new DoWorkEventHandler(BackupWorker.DoWork);
                backupWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackupWorker.RunWorkerCompleted);
                backupWorker.RunWorkerAsync();

                // Preload the data to allow any necessary initialization to happen
                StarMapStateManager.Build();
                FactionInventoryStateManager.Build();
                PlayerStateManager.Build();

                WarServices warServices = new WarServices();
                // Create an AOP proxy object that we can hang Castle.DynamicProxies upon. These are useful for operations across the whole
                //   of the service, or for when we need to fail a message in a reasonable way.
                var proxy = new Castle.DynamicProxy.ProxyGenerator()
                            .CreateClassProxyWithTarget <WarServices>(warServices, new Castle.DynamicProxy.IInterceptor[] {
                    new UserQuotaInterceptor(), new AdminKeyRequiredInterceptor()
                });

                // Create a RESTful service host. The service instance is automatically, through
                //   the WarServiceInstanceProviderBehaviorAttribute. We create the singleton this way to give
                //   us the chance to customize the binding
                WebServiceHost _serviceHost = new WebServiceHost(typeof(WarServices), new Uri(ServiceUrl));
                AddServiceBehaviors(_serviceHost);

                // Create a binding that wraps the default WebMessageEncodingBindingElement with a BindingElement
                //   that can GZip compress responses when a client requests it.
                WebMessageEncodingBindingElement innerEncoding = new WebMessageEncodingBindingElement {
                    ContentTypeMapper = new ForceJsonWebContentMapper()
                };
                GZipMessageEncodingBindingElement encodingWrapper = new GZipMessageEncodingBindingElement(innerEncoding);

                var transport = new HttpTransportBindingElement {
                    ManualAddressing = true,
                    KeepAliveEnabled = false,
                    AllowCookies     = false
                };

                var customBinding = new CustomBinding(encodingWrapper, transport);

                // Create a default endpoint with the JSON/XML behaviors and the behavior to check the incoming headers for GZIP requests
                var endpoint = _serviceHost.AddServiceEndpoint(typeof(IWarServices), customBinding, "");
                endpoint.Behaviors.Add(new WebHttpBehavior());
                endpoint.Behaviors.Add(new GZipBehavior());

                _serviceHost.Open();

                Console.WriteLine("Open Press Key to close");
                Console.ReadKey();

                _serviceHost.Close();
                Console.WriteLine("Connection Closed");

                // Cleanup any outstanding processes
                monitor.disable();

                heartbeatWorker.CancelAsync();

                playerHistoryPruner.CancelAsync();
                PlayerHistoryPruner.PruneOnExit();

                backupWorker.CancelAsync();
                BackupWorker.BackupOnExit();
            } catch (Exception e) {
                Console.WriteLine(e);
                Console.ReadKey();
            }
        }
Esempio n. 32
0
 /// <summary>
 /// Creates the proxy for the target type.
 /// </summary>
 public object Create(Type targetType)
 {
     var proxy =  new Castle.DynamicProxy.ProxyGenerator();
     return proxy.CreateInterfaceProxyWithoutTarget(targetType, new ProxiedMethodInterceptor(interceptor));
 }
Esempio n. 33
0
        /// <summary>
        /// 创建一个类型方式的拦截器(可传入参数)
        /// </summary>
        /// <param name="classType"></param>
        /// <param name="arguments"></param>
        /// <param name="interceptors"></param>
        /// <returns></returns>
        public static object CreateProxy(Type classType, object[] arguments, params Castle.DynamicProxy.IInterceptor[] interceptors)
        {
            //如果拦截器为0
            if (interceptors.Length == 0)
            {
                return Activator.CreateInstance(classType, arguments);
            }

            Castle.DynamicProxy.ProxyGenerator proxy = new Castle.DynamicProxy.ProxyGenerator();
            Castle.DynamicProxy.ProxyGenerationOptions options = new Castle.DynamicProxy.ProxyGenerationOptions(new ProxyGenerationHook())
            {
                Selector = new InterceptorSelector()
            };

            if (arguments == null || arguments.Length == 0)
                return proxy.CreateClassProxy(classType, options, interceptors);
            else
                return proxy.CreateClassProxy(classType, options, arguments, interceptors);
        }
 static void Main(string[] args)
 {
     var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();
     var entity         = proxyGenerator.CreateClassProxy(typeof(Article), new object[0], new TestInterceptor()) as Article;;
     var json           = JsonConvert.SerializeObject(entity);
 }
 public void CastleDynamicProxy2Test()
 {
     Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();
     SimpleExplicitPropChanged proxy = (SimpleExplicitPropChanged)
     generator.CreateClassProxy(typeof(SimpleExplicitPropChanged), new Castle.Core.Interceptor.IInterceptor[0]);
 }
 public void DoubleProxyTest()
 {
     Type generatedType =
         DynamicPropertyChangedProxy.CreateBusinessObjectProxy(
             typeof(SimpleBusinessObject), new Type[0]);
     Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();
     SimpleBusinessObject proxy = (SimpleBusinessObject)
     generator.CreateClassProxy(generatedType, new Castle.Core.Interceptor.IInterceptor[0]);
 }
Esempio n. 37
0
 public ProxyGenerator(IMemberInvocationHandlerFactory memberInvocationHandlerFactory)
 {
     _memberInvocationHandlerFactory = memberInvocationHandlerFactory;
     _proxyGenerator = new Castle.DynamicProxy.ProxyGenerator();
 }
Esempio n. 38
0
        /// <summary>
        /// 创建一个实例方式的拦截器
        /// </summary>
        /// <param name="proxyType"></param>
        /// <param name="target"></param>
        /// <param name="interceptors"></param>
        /// <returns></returns>
        public static object CreateProxy(Type proxyType, object target, params Castle.DynamicProxy.IInterceptor[] interceptors)
        {
            //如果拦截器为0
            if (interceptors.Length == 0)
            {
                return target;
            }

            Castle.DynamicProxy.ProxyGenerator proxy = new Castle.DynamicProxy.ProxyGenerator();
            Castle.DynamicProxy.ProxyGenerationOptions options = new Castle.DynamicProxy.ProxyGenerationOptions(new ProxyGenerationHook())
            {
                Selector = new InterceptorSelector()
            };

            return proxy.CreateInterfaceProxyWithTargetInterface(proxyType, target, options, interceptors);
        }