Exemple #1
0
        static void Main(string[] args)
        {
            #region 没有通过配置文件实现的aop
            Order order = new Order();
            order.Category = new Model.Category()
            {
                No = 2
            };

            IOrderRepository target = new OrderRepository()
            {
                Order = order
            };
            ProxyFactory factory = new ProxyFactory(target);//OrderRepository 必须实现接口 ,InterfaceMap = Count 1

            factory.AddAdvice(new AfterAdviseOrder());
            factory.AddAdvice(new AroundAdviseOrder());
            //  factory.AddAdvice(new BeforeAdviseOrder());

            IOrderRepository manager = (IOrderRepository)factory.GetProxy();
            manager.Save(order);

            #endregion

            Console.ReadLine();
        }
Exemple #2
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public static void Main(string[] args)
        {
            try
            {
                // Create AOP proxy programmatically.
                ProxyFactory factory = new ProxyFactory(new ServiceCommand());
                factory.AddAdvice(new ConsoleLoggingBeforeAdvice());
                factory.AddAdvice(new ConsoleLoggingAfterAdvice());
                factory.AddAdvice(new ConsoleLoggingThrowsAdvice());
                ICommand command = (ICommand)factory.GetProxy();

                command.Execute();
                if (command.IsUndoCapable)
                {
                    command.UnExecute();
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine();
                Console.Out.WriteLine(ex);
            }
            finally
            {
                Console.Out.WriteLine();
                Console.Out.WriteLine("--- hit <return> to quit ---");
                Console.ReadLine();
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            IApplicationContext ctx = ContextRegistry.GetContext();

            #region DI
            INumCheck nc  = (INumCheck)ctx.GetObject("NumCheck");
            int       rst = nc.NCheck(1, 3); // NCheck 함수만 사용, 객체 생성은 Spring의 몫

            //Console.WriteLine(smd.Low + ", " + smd.High);


            // Not DI
            NumCheck nc2  = new NumCheck();
            int      rst2 = nc2.NCheck(1, 3); // NumCheck 객체를 미리 생성

            //Console.WriteLine(smd2.Low + ", " + smd2.High);
            #endregion

            #region Property
            if (ctx.ContainsObject("PropService"))
            {
                object obj = ctx["PropService"];

                PropService         ps      = (PropService)obj;
                string              prop_SG = ps.SG;
                string              prop_JP = ps.JP["City"];
                List <string>       prop_KO = ps.KO;
                NameValueCollection prop_CN = ps.CN;
            }
            #endregion

            #region AOP Way (1) - Need Config object  / Dont Reference from 61 line / Reference App.config(AOP)
            ICommand command = (ICommand)ctx["MyCommand"];
            command.TargetMethod("Processing", "Going");
            #endregion

            #region AOP Way (2) - Dont Need Config object / Reference from 61 line
            ProxyFactory factory = new ProxyFactory(new ServiceCommandObject());
            factory.AddAdvice(new RunningTimeAroundAdvice());
            factory.AddAdvice(new RunningTimeBeforeAdvice());
            factory.AddAdvice(new AfterReturningAdvice());
            factory.AddAdvice(new RunningTimeThrowAdvice());
            ICommand cmd = (ICommand)factory.GetProxy();
            cmd.TargetMethod("Processing", "Going");
            #endregion

            //  AOP Result Txt
            //  1. RunningTimeAroundAdvice(Before) - Before AroundAdvice executing
            //  2. RunningTimeBeforeAdvice - BeforeAdvice executing
            //  3. TargetMethod - Changed(Processing -> Changed), Going
            //  4. AfterReturningAdvice - Running time end
            //  1. RunningTimeAroundAdvice(After) - After AroundAdvice executing
        }
        /// <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();
        }
Exemple #5
0
        //public TypeConverter TypeConverter {
        //    set {
        //        AssertUtils.ArgumentNotNull(value, "typeConverter must not be null");
        //        _typeConverter = value;
        //    }
        //}

        //public void setBeanClassLoader(ClassLoader beanClassLoader) {
        //    this.beanClassLoader = beanClassLoader;
        //}

        protected override void OnInit()
        {
            lock (_initializationMonitor) {
                if (_initialized)
                {
                    return;
                }
                if (_serviceInterface == null)
                {
                    throw new ArgumentException("'serviceInterface' must not be null");
                }
                MethodInfo[] methods = _serviceInterface.GetMethods();
                foreach (MethodInfo method in methods)
                {
                    IMessagingGateway gateway = CreateGatewayForMethod(method);
                    _gatewayMap.Add(method, gateway);
                }

                ProxyFactory pf = new ProxyFactory(new[] { _serviceInterface });
                pf.AddAdvice(this);
                _serviceProxy = pf.GetProxy();
                Start();
                _initialized = true;
            }
        }
        /// <summary>
        /// Registers interceptors on each method of a target DAO instance before and after execution, and even if exceptions occurs
        /// </summary>
        /// <typeparam name="TInterface">The interface implemented by the target DAO instance</typeparam>
        /// <param name="target">The target DAO instance</param>
        /// <returns>A new <typeparamref name="TInterface"/> instance, with method interception</returns>
        internal static TInterface GetWrappedInstance <TInterface>(DAO target)
        {
            ProxyFactory factory = new ProxyFactory(target);

            factory.AddAdvice(new DaoInterceptor());
            return((TInterface)factory.GetProxy());
        }
        public static TInterface WithTimeMeasure <TInterface>(TInterface target, ConsoleColor color = ConsoleColor.Blue)
        {
            var proxyFactory = new ProxyFactory(target);

            proxyFactory.AddAdvice(new TimeMeasureInterceptor(color));
            return((TInterface)proxyFactory.GetProxy());
        }
        public void ChainLogAndWrap()
        {
            string logHandlerText         = "on exception name ArithmeticException log 'My Message, Method Name ' + #method.Name";
            string translationHandlerText = "on exception name ArithmeticException wrap System.InvalidOperationException 'My Message'";

            exceptionHandlerAdvice.ExceptionHandlers.Add(logHandlerText);
            exceptionHandlerAdvice.ExceptionHandlers.Add(translationHandlerText);
            exceptionHandlerAdvice.AfterPropertiesSet();
            ProxyFactory pf = new ProxyFactory(new TestObject());

            pf.AddAdvice(exceptionHandlerAdvice);
            ITestObject to = (ITestObject)pf.GetProxy();

            try
            {
                to.Exceptional(new ArithmeticException("Bad Math"));
                Assert.Fail("Should have thrown exception");
            }
            catch (InvalidOperationException e)
            {
                Assert.IsNotNull(e.InnerException);
                Exception innerEx = e.InnerException;
                Assert.AreEqual("My Message", e.Message);
                Assert.AreEqual("Bad Math", innerEx.Message);
            }
            catch (Exception e)
            {
                Assert.That(e, Is.InstanceOf(typeof(InvalidOperationException)));
            }
        }
        private ITestObject CreateProxy()
        {
            exceptionHandlerAdvice.AfterPropertiesSet();
            ProxyFactory pf = new ProxyFactory(new TestObject());

            pf.AddAdvice(exceptionHandlerAdvice);
            return((ITestObject)pf.GetProxy());
        }
        public Object CreateSecurityProxyInstance(string name)
        {
            ProxyFactory factory = new ProxyFactory(CreateInstance(name));

            factory.AddAdvice(new SecurityAdvice());

            return(factory.GetProxy());
        }
Exemple #11
0
        private static void Main(string[] args)
        {
            ProxyFactory factory = new ProxyFactory(new ServiceCommand());

            factory.AddAdvice(new ConsoleLoggingAroundAdvice());
            ICommand command = (ICommand)factory.GetProxy();

            command.Execute("This is the argument");
        }
Exemple #12
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ProxyFactory factory = new ProxyFactory(new testForm());

            factory.AddAdvice(new EventAdvise());
            IForm proxy = factory.GetProxy() as IForm;

            proxy.Show();
        }
Exemple #13
0
    private object CreateProxy()
    {
        var proxy = new ProxyFactory();

        proxy.AddInterface(this.ServiceInterface);
        proxy.AddAdvice(this);
        proxy.Target = this.Service;
        return(proxy.GetProxy());
    }
Exemple #14
0
        static void Main(string[] args)
        {
            ProxyFactory factory = new ProxyFactory(new OrderService());

            factory.AddAdvice(new AroundAdvise());
            factory.AddAdvice(new BeforeAdvise());
            factory.AddAdvice(new AfterReturningAdvise());
            factory.AddAdvice(new ThrowsAdvise());

            IOrderService service = (IOrderService)factory.GetProxy();

            object result = service.Save(1);

            Console.WriteLine();
            Console.WriteLine(string.Format("客户端返回值:{0}", result));

            Console.ReadLine();
        }
Exemple #15
0
 public static IXMLMailUtil GetEntity()
 {
     if (entity == null)
     {
         ProxyFactory factory = new ProxyFactory(new XMLMailUtil());
         factory.AddAdvice(new AroundAdvice());
         entity = (IXMLMailUtil)factory.GetProxy();
     }
     return(entity);
 }
Exemple #16
0
 protected override void AddPersistenceExceptionTranslation(ProxyFactory pf, IPersistenceExceptionTranslator pet)
 {
     if (AttributeUtils.FindAttribute(pf.TargetType, typeof(RepositoryAttribute)) != null)
     {
         DefaultListableObjectFactory of = new DefaultListableObjectFactory();
         of.RegisterObjectDefinition("peti", new RootObjectDefinition(typeof(PersistenceExceptionTranslationInterceptor)));
         of.RegisterSingleton("pet", pet);
         pf.AddAdvice((PersistenceExceptionTranslationInterceptor)of.GetObject("peti"));
     }
 }
Exemple #17
0
        /// <summary>
        /// Add a service proxied and advised using the appropriate around AOP advice
        /// </summary>
        public static void AddAdvisedService <IServiceInterface>(IServiceInterface implementation,
                                                                 IMethodInterceptor interceptor)
        {
            CreateServicesTable();
            ProxyFactory proxyFactory = new ProxyFactory(implementation);

            proxyFactory.AddAdvice(interceptor);
            IServiceInterface service = (IServiceInterface)proxyFactory.GetProxy();

            _services.Add(typeof(IServiceInterface), service);
        }
Exemple #18
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            ProxyFactory proxy = new ProxyFactory(new Form1());

            proxy.AddAdvice(new EventAdvise());
            Application.Run(new Form1());
            //IFormAction i = (IFormAction)proxy.GetProxy();
            //var form = i as Form1;
            //Application.Run(form);
        }
    private static ProxyFactory GetFactory(object target)
    {
        var factory = new ProxyFactory(target);

        // I simply add the advice here, but you could useyour original
        //  factory.AddAdvisor( ... )
        factory.AddAdvice(new UnitValidationBeforeAdvice());
        // You don't need this:
        // factory.AddAdvice(new NotifyPropertyChangedAdvice());
        factory.ProxyTargetType = true;
        return(factory);
    }
Exemple #20
0
        public void Main()
        {
            var host = new Host();

            var mp = new SimplePlugin();
            var pf = new ProxyFactory(mp);

            pf.AddAdvice(new DelegateToHostExceptionHandlingAdvice(host));

            var proxy = (IPlugin)pf.GetProxy();

            proxy.DoWork();
        }
Exemple #21
0
        private IRunnable CreatePoller()
        {
            if (_adviceChain.Count == 0)
            {
                return(new Poller(this));
            }
            ProxyFactory proxyFactory = new ProxyFactory(new Poller(this));

            foreach (IAdvice advice in _adviceChain)
            {
                proxyFactory.AddAdvice(advice);
            }
            return((IRunnable)proxyFactory.GetProxy());
        }
        protected override object Advised(object target, IPlatformTransactionManager ptm,
                                          ITransactionAttributeSource tas)
        {
            TransactionInterceptor ti = new TransactionInterceptor();

            ti.TransactionManager = ptm;
            Assert.AreEqual(ptm, ti.TransactionManager);
            ti.TransactionAttributeSource = tas;
            Assert.AreEqual(tas, ti.TransactionAttributeSource);
            ProxyFactory pf = new ProxyFactory(target);

            pf.AddAdvice(0, ti);
            return(pf.GetProxy());
        }
Exemple #23
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();
        }
Exemple #24
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");
        }
 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());
     }
 }
Exemple #26
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();
        }
Exemple #27
0
        public static void AOPClientStart()
        {
            //factory 代理目标对象
            ProxyFactory factory = new ProxyFactory(
                //joinpoint  连接点
                new SystemManager()
            {
                Name = "yoolo aop"
            }
                );

            //MethodInterceptorAdvise  通知 ,拦截到joinpoint 之后,做的通知
            factory.AddAdvice(new MethodInterceptorAdvise());
            IUserManager Iuser = factory.GetProxy() as IUserManager;

            Iuser.Save();
        }
Exemple #28
0
        //环绕通知
        private static void AroundAdvice()
        {
            ICompanyManager target = new SpringNetAop.CompanyManager.CompanyManager()
            {
                Dao = new CompanyDao(), UserName = "******"
            };
            //target.Save();
            ProxyFactory factory = new ProxyFactory(target);

            factory.AddAdvice(new AroundAdvice());

            ICompanyManager manager = (ICompanyManager)factory.GetProxy();

            manager.Save();

            Console.ReadLine();
        }
Exemple #29
0
        private static void Main(string[] args)
        {
            var factoryNoData = new ProxyFactory(new ClassWithData());

            factoryNoData.AddAdvice(new PropertyInterceptor());
            var noDataWithInterceptor = (IClassWithData)factoryNoData.GetProxy();

            Console.Out.WriteLine(noDataWithInterceptor.Data);
            //Console.Out.WriteLine(noDataWithInterceptor.GetData());

            //Console.Out.WriteLine();

            //var factoryData = new ProxyFactory(new ClassWithData(Guid.NewGuid()));
            //factoryData.AddAdvice(new PropertyInterceptor());
            //var dataWithInterceptor = (IClassWithData)factoryData.GetProxy();
            //Console.Out.WriteLine(dataWithInterceptor.Data);
            //Console.Out.WriteLine(dataWithInterceptor.GetData());
        }
Exemple #30
0
        public void Example_of_how_to_use_Spring_programmatic_interception()
        {
            ProxyFactory factory = new ProxyFactory(new ServiceCommand());

            factory.AddAdvice(new ConsoleLoggingAroundAdvice());
            ICommand command = (ICommand)factory.GetProxy();

            command.DoExecute();
            // Console output:
            // Advice executing...
            // DoExecute()
            // Advice executed

            command.Execute();
            // Console output:
            // Advice executing...
            // Execute()
            // Advice executed
        }
Exemple #31
0
        public void IntegrationTest()
        {
            ProxyFactory pf = new ProxyFactory(new TestTarget());

            ILog log = A.Fake <ILog>();
            SimpleLoggingAdvice loggingAdvice = new SimpleLoggingAdvice(log);

            pf.AddAdvice(loggingAdvice);

            A.CallTo(() => log.IsTraceEnabled).Returns(true);

            object      proxy = pf.GetProxy();
            ITestTarget ptt   = (ITestTarget)proxy;

            ptt.DoSomething();

            A.CallTo(() => log.Trace("Entering DoSomething")).MustHaveHappened();
            A.CallTo(() => log.Trace("Exiting DoSomething")).MustHaveHappened();
        }