Generates a Java style proxy. This overrides the .Net proxy requirements that forces one to extend MarshalByRefObject or (for a different purpose) ContextBoundObject to have a Proxiable class.
The ProxyGenerator should be used to generate a class implementing the specified interfaces. The dynamic implementation will only calls the internal IInterceptor instance. Please note that this proxy implementation currently doesn't not supports ref and out arguments in methods. Also note that only virtual methods can be proxied in a class.
 public void InitializeProxy()
 {
     IBar bar = new Bar();
     var pg = new ProxyGenerator();
     this.BarInterfaceProxy = pg.CreateInterfaceProxyWithTarget(bar, new CacheInterceptor());
     this.FooBarProxy = pg.CreateClassProxy<FooBar>(new CacheInterceptor());
 }
Ejemplo n.º 2
0
 public void Parallel()
 {
     var generator = new ProxyGenerator();
     var t = generator.CreateClassProxy<SomethingToIntercept>(new ProcessInterceptor());
     var r = Enumerable.Range(0, 100).AsParallel().Sum(i => t.Add(i, i));
     Assert.AreEqual(9900, r);
 }
 private object CreateProxy(Type type, object settings)
 {
     var proxyGenerator = new ProxyGenerator();
     var settingsInterceptor = SetInterceptor(type, settings);
     var proxy = proxyGenerator.CreateClassProxy(type, settingsInterceptor);
     return proxy;
 }
Ejemplo n.º 4
0
 public void NullReturn()
 {
     var generator = new ProxyGenerator();
     var t = generator.CreateClassProxy<SomethingToIntercept>(new ProcessInterceptor());
     var r = t.NullReturn();
     Assert.IsNull(r);
 }
Ejemplo n.º 5
0
        public SpotiFireRegistry()
        {
            var pg = new ProxyGenerator();

            //For<ISpotiFireService>().EnrichAllWith((context, z) => pg.CreateInterfaceProxyWithTarget(z, new SpotiFireServiceInterceptor(context.GetInstance<ILibraryValidator>()))).OnCreationForAll((context, x) => x.ConfigureSpotiFire());
            For<ISpotiFireService>().HybridHttpOrThreadLocalScoped().Use<SpotiFireService>().OnCreation(x => x.ConfigureSpotiFire());
        }
        public override void Proceed()
        {
            var expectation = stubMessageBus.GetExpectationFor(Request.GetType());

            if (expectation == null)
            {
                var response = (Response)Activator.CreateInstance(Request.GetResponseType());
                response.CorrelationGuid = Request.CorrelationGuid;
                Response = GetSerializedVersion(response);
            }
            else
            {
                Response = GetSerializedVersion(expectation.Execute(Request));
            }

            if(Request.IsSideEffectFree)
            {
                try
                {
                    var options = new ProxyGenerationOptions(new NonVirtualCheckProxyGenerationHook());
                    var proxyGen = new ProxyGenerator();
                    proxyGen.CreateClassProxy(Request.GetResponseType(), options);
                }
                catch (Exception ex)
                {
                    throw new ColomboTestSupportException(string.Format("Response {0} cannot be proxied, probably because one or several of its members are not virtual.", Request.GetResponseType()), ex);
                }
            }
        }
        public DynamicProxyHelper(SerializationInfo info, StreamingContext context)
        {
            _info = info;
            _context = context;

            _argumentsForConstructor = (Type[])info.GetValue(DynamicPropertyChangedProxy.ARGUMENTS_TYPES4CONSTRUCTOR, typeof(Type[]));
            _valuesForConstructor = (object[])info.GetValue(DynamicPropertyChangedProxy.VALUES4CONSTRUCTOR, typeof(object[]));
            _baseTypeName = (string)info.GetValue(DynamicPropertyChangedProxy.OBJECT_BASE_TYPE, typeof(string));
            bool isBusinessObj = (bool)info.GetValue(DynamicPropertyChangedProxy.IS_BUSINESS_OBJECT, typeof(bool));
            _baseT = Type.GetType(_baseTypeName, true, false);
            Type firstProxyType;
            object[] baseMemberData = (object[])_info.GetValue(DynamicPropertyChangedProxy.SERIALIZED_DATA, typeof(object[]));
            ProxyGenerator generator = new ProxyGenerator();

            if (isBusinessObj)
            {
                // the business objects have to have a default constructor
                firstProxyType = DynamicPropertyChangedProxy.CreateBusinessObjectProxy(_baseT, _argumentsForConstructor);
                _proxy = generator.CreateClassProxy(firstProxyType, (IInterceptor[])baseMemberData[0]);
            }
            else
            {
                // if it is not a business object then it has to be a BindableFields class which constructor has always an interceptor
                firstProxyType = DynamicPropertyChangedProxy.CreateBindableWrapperProxy(_baseT, _argumentsForConstructor, _valuesForConstructor);
                _proxy = generator.CreateClassProxy(firstProxyType, (IInterceptor[])baseMemberData[0], _valuesForConstructor);
            }
        }
Ejemplo n.º 8
0
 public void Call()
 {
     var generator = new ProxyGenerator();
     var t = generator.CreateClassProxy<SomethingToIntercept>(new ProcessInterceptor());
     var r = t.DoSomething("a", "b");
     Assert.AreEqual("ab", r);
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Decoration request
        /// </summary>
        /// <param name="context">Context info</param>
        /// <remarks>do not have to decorate, but may if it wants to. sorta..</remarks>
        public void Decorate(DecoratorContext context)
        {
            if (!CanDecorate(context))
                return;

            var options = new ProxyGenerationOptions();

            var services = context.Services;
            if (IgnoreClassAsService && services.Length > 1)
                services = services.Where(x => !x.IsClass).ToArray();

            var generator = new ProxyGenerator();
            if (services.Any(x => x.IsClass))
            {
                if (services.Length > 1)
                    throw new InvalidOperationException(
                        "A class that register itself as a service may not also be registered with interfaces. See the remarks in the IgnoreClassAsService property.");

                var clazz = context.Services.Single(x => x.IsClass);
                context.Instance = generator.CreateClassProxyWithTarget(clazz, context.Instance,
                                                                        CreateInterceptor(context));
            }
            else
            {
                var others = services.Where(x => x.IsInterface).Skip(1);
                var first = services.First();
                context.Instance = generator.CreateInterfaceProxyWithTarget
                    (first, others.ToArray(), context.Instance,
                     CreateInterceptor(context));
            }

        }
Ejemplo n.º 10
0
        internal static IController TrySetActionInvoker(this IController iController, IGlimpseLogger logger)
        {
            var controller = iController as Controller;
            if (controller == null)
            {
                //TODO: Add Logging
                return iController;
            }

            var actionInvoker = controller.ActionInvoker;

            if (actionInvoker.CanSupportDynamicProxy(logger))
            {
                var proxyConfig = new Dictionary<string, IInterceptor>
                                      {
                                          {"GetFilters", new GetFiltersInterceptor()},
                                          {"InvokeActionResult", new InvokeActionResultInterceptor()},
                                          {"InvokeActionMethod",new InvokeActionMethodInterceptor()}
                                      };

                var proxyGenerator = new ProxyGenerator();
                var proxyGenOptions = new ProxyGenerationOptions(new SimpleProxyGenerationHook(logger, proxyConfig.Keys.ToArray())) { Selector = new SimpleInterceptorSelector(proxyConfig) };
                var newInvoker = (ControllerActionInvoker)proxyGenerator.CreateClassProxy(actionInvoker.GetType(), proxyGenOptions, proxyConfig.Values.ToArray());
                controller.ActionInvoker = newInvoker;
            }

            return controller;
        }
Ejemplo n.º 11
0
        public static int Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            var dokanOptions = new DokanOptions
                          {
                              MountPoint = "r:\\",
                              DebugMode = true,
                              UseStdErr = true,
                              VolumeLabel = "TAGFS",
                              ThreadCount = 1
                          };

            var options = new TaggedFileSystemOptions { RootPath = "d:\\tmp" };
            options.Init();

            var databaseOriginal = new Database(options.ServicePath);
            var taggedFileStorage = new TaggedFileStorage(databaseOriginal);
            var target = new TaggedFileSystem(options, taggedFileStorage);

            var fileSystemPxy = new ProxyGenerator()
                .CreateInterfaceProxyWithTarget<DokanOperations>(
                target,
                new WrappingInterceptor(),
                new TransactionManagementInterceptor(databaseOriginal)
            );

            var status = DokanNet.DokanMain(
                dokanOptions,
                fileSystemPxy
                );

            return status;
        }
        public CastleDynamicProxyFactory()
        {
            ConfigureDynamicProxyToAvoidReplicatingProblematicAttributes();

            _proxyGenerator = new ProxyGenerator();
            _allMethodsExceptCallRouterCallsHook = new AllMethodsExceptCallRouterCallsHook();
        }
Ejemplo n.º 13
0
 /// <summary>
 /// �����ʽʵ��������
 /// </summary>
 /// <param name="engine"></param>
 /// <returns></returns>
 public static object WrapInterface(Type engine)
 {
     ProxyInterceptor proxyInterceptor = new ProxyInterceptor();
     ProxyGenerator generator = new ProxyGenerator();
     object proxy = generator.CreateClassProxy(engine, proxyInterceptor);
     return proxy;
 }
Ejemplo n.º 14
0
        public TrinketProxyEgg()
        {
            streamFactory = new StreamFactory();
             processProxy = new ProcessProxy();
             var pofContext = new PofContext().With(x => {
            x.MergeContext(new DspPofContext());
            x.MergeContext(new TrinketsApiPofContext());
            x.MergeContext(new TrinketsImplPofContext());
             });
             ICollectionFactory collectionFactory = new CollectionFactory();
             IFileSystemProxy fileSystemProxy = new FileSystemProxy(streamFactory);
             IThreadingProxy threadingProxy = new ThreadingProxy(new ThreadingFactory(), new SynchronizationFactory());
             var dnsProxy = new DnsProxy();
             INetworkingProxy networkingProxy = new NetworkingProxy(new SocketFactory(new TcpEndPointFactory(dnsProxy), new NetworkingInternalFactory(threadingProxy, streamFactory)), new TcpEndPointFactory(dnsProxy));
             pofSerializer = new PofSerializer(pofContext);
             PofStreamsFactory pofStreamsFactory = new PofStreamsFactoryImpl(threadingProxy, streamFactory, pofSerializer);

             ProxyGenerator proxyGenerator = new ProxyGenerator();
             var serviceClientFactory = new ServiceClientFactoryImpl(proxyGenerator, streamFactory, collectionFactory, threadingProxy, networkingProxy, pofSerializer, pofStreamsFactory);

             // construct libdsp local service node
             ClusteringConfiguration clusteringConfiguration = new ClientClusteringConfiguration();
             ServiceClient localServiceClient = serviceClientFactory.Construct(clusteringConfiguration);
             keepaliveObjects.Add(localServiceClient);

             temporaryFileService = localServiceClient.GetService<TemporaryFileService>();

             var processInjector = new ProcessInjectorImpl();
             ProcessInjectionConfiguration processInjectionConfiguration = new ProcessInjectionConfigurationImpl(injectionAttempts: 10, injectionAttemptsDelay: 200);
             processInjectionService = new ProcessInjectionServiceImpl(processInjector, processInjectionConfiguration);
             IDtpNodeFactory transportNodeFactory = new DefaultDtpNodeFactory();
             BootstrapConfigurationGenerator bootstrapConfigurationGenerator = new BootstrapConfigurationGeneratorImpl();
             trinketInternalUtilities = new TrinketInternalUtilitiesImpl(fileSystemProxy);
             trinketDtpServerFactory = new TrinketDtpServerFactoryImpl(streamFactory, transportNodeFactory, bootstrapConfigurationGenerator);
        }
Ejemplo n.º 15
0
        public override object BuildProxy(ProxyGenerator generator, Type objType, CommonData data, object baseObj)
        {
            if (!objType.IsInterface)
            {
                throw new Exception("Set can only be created from ISet Interface");
            }

            object proxy;

            if (baseObj == null)
            {
                proxy = generator.CreateInterfaceProxyWithoutTarget(objType,
                    new ProxyGenerationOptions(new GeneralProxyGenerationHook())
                    {
                        Selector = _setSelector
                    },
                    new GeneralGetInterceptor(data), new SetAddInterceptor(data), new SetRemoveInterceptor(data));
            }
            else
            {
                proxy = generator.CreateInterfaceProxyWithTarget(objType, baseObj,
                    new ProxyGenerationOptions(new GeneralProxyGenerationHook())
                    {
                        Selector = _setSelector
                    },
                    new GeneralGetInterceptor(data), new SetAddInterceptor(data), new SetRemoveInterceptor(data));
            }
            return proxy;
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public static IDbCommand NewInstance(IDbCommand command)
        {
            IInterceptor handler = new IDbCommandProxy(command);

            object proxyCommand = new ProxyGenerator().CreateProxy(typeof(IDbCommand), handler, command);

            return (IDbCommand) proxyCommand;
        }
Ejemplo n.º 17
0
 public static object CreateEventInterfaceProxy(Type interfaceType)
 {
     if (ProxyGenerator == null)
     {
         ProxyGenerator = new ProxyGenerator();
     }
     return ProxyGenerator.CreateInterfaceProxyWithoutTarget(interfaceType, new[] { typeof(IEventProxy) }, new EventInterceptor());
 }
 public void Setup()
 {
     _fakeScenarioContext = A.Fake<IScenarioContext>();
     _fakeKeyGenerator = A.Fake<IKeyGenerator>();
     A.CallTo(() => _fakeKeyGenerator.GenerateKey(A<Type>.Ignored, A<MethodInfo>.Ignored)).Returns("testkey");
     _proxyInterceptor = new ProxyInterceptor(_fakeScenarioContext, _fakeKeyGenerator);
     _proxyGenerator = new ProxyGenerator();
 }
Ejemplo n.º 19
0
 static void Main(string[] args)
 {
     var proxyGenerator = new ProxyGenerator();
     var svc = proxyGenerator
         .CreateClassProxy<TwitterClient>(
             new MyInterceptorAspect());
     svc.Send("hi");
 }
Ejemplo n.º 20
0
 static void Main(string[] args)
 {
     System.Console.WriteLine("现在是Castle的代理在运行");
     ProxyGenerator generator = new ProxyGenerator();
     object proxy = generator.CreateClassProxy(typeof(RealA), new ProxyInterceptor());
     (proxy as RealA).DoSomething();
     System.Console.ReadLine();
 }
Ejemplo n.º 21
0
 public DynamicProxyActivator(IMachineContainer container, IProxyBuilder proxyBuilder, IActivator target, ServiceEntry entry)
 {
     _container = container;
       _entry = entry;
       _proxyBuilder = proxyBuilder;
       _target = target;
       _proxyGenerator = new ProxyGenerator(_proxyBuilder);
 }
Ejemplo n.º 22
0
 public void Foo1()
 {
     ProxyGenerator generator = new ProxyGenerator();
     Castle.DynamicProxy.IInterceptor[] interceptors = { new MyCastleInterceptor() };
     CastleUserProcessor userProcessor = generator.CreateClassProxy<CastleUserProcessor>(interceptors);
     User user = new User() { Name = "lee", PassWord = "******" };
     userProcessor.RegUser(user);
 }
Ejemplo n.º 23
0
 public override IMainWindow GetMainWindow(Application application)
 {
     var ieWindow = (InternetExplorerWindow)application.GetWindow("TestSilverlightApplication - Windows Internet Explorer");
     var mainWindowAdapter = new ProxyGenerator()
         .CreateInterfaceProxyWithoutTarget<IMainWindow>(new SilverlightAdditionalCallsInterceptor(ieWindow.SilverlightDocument),
                                                         new ForwardIfExistsInterceptor(ieWindow.SilverlightDocument));
     return mainWindowAdapter;
 }
Ejemplo n.º 24
0
 public static object CreateEventInterfaceProxy(Type interfaceType)
 {
     if (ProxyGenerator == null)
     {
         ProxyGenerator = new ProxyGenerator(disableSignedModule: !Configuration.Roque.Settings.SignDynamicProxyModule);
     }
     return ProxyGenerator.CreateInterfaceProxyWithoutTarget(interfaceType, new[] { typeof(IEventProxy) }, new EventInterceptor());
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Initializes the elements in the Page Object.
        /// </summary>
        /// <param name="driver">The driver used to find elements on the page.</param>
        /// <param name="page">The Page Object to be populated with elements.</param>
        public static void InitElements(ISearchContext driver, object page)
        {
            const BindingFlags BindingOptions = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
            if (page == null)
            {
                throw new ArgumentNullException("page", "page cannot be null");
            }

            var type = page.GetType();
            var fields = type.GetFields(BindingOptions);
            var properties = type.GetProperties(BindingOptions);
            var members = new List<MemberInfo>(fields);
            members.AddRange(properties);

            foreach (var member in members)
            {
                var attributes = member.GetCustomAttributes(typeof(FindsByAttribute), true);
                foreach (var attribute in attributes)
                {
                    var castedAttribute = (FindsByAttribute)attribute;
                    var generator = new ProxyGenerator();

                    var cacheAttributeType = typeof(CacheLookupAttribute);
                    var cache = member.GetCustomAttributes(cacheAttributeType, true).Length != 0 || member.DeclaringType.GetCustomAttributes(cacheAttributeType, true).Length != 0;

                    var interceptor = new ProxiedWebElementInterceptor(driver, castedAttribute.Bys, cache);

                    var options = new ProxyGenerationOptions
                        {
                            BaseTypeForInterfaceProxy = typeof(WebElementProxyComparer)
                        };

                    var field = member as FieldInfo;
                    var property = member as PropertyInfo;
                    if (field != null)
                    {
                        var proxyElement = generator.CreateInterfaceProxyWithoutTarget(
                            typeof(IWrapsElement),
                            new[] { field.FieldType },
                            options,
                            interceptor);

                        field.SetValue(page, proxyElement);
                    }
                    else if (property != null)
                    {
                        var proxyElement = generator.CreateInterfaceProxyWithoutTarget(
                            typeof(IWrapsElement),
                            new[] { property.PropertyType },
                            options,
                            interceptor);

                        property.SetValue(page, proxyElement, null);
                    }
                }
            }
        }
        /// <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>
        public override void Dispose( bool disposing )
        {
            if ( disposing && !IsDisposed )
            {
                this.generator = null;
            }

            base.Dispose( disposing );
        }
Ejemplo n.º 27
0
        public void InterfaceProxy()
        {
            var generator = new ProxyGenerator();

            var classProxy = generator.CreateInterfaceProxyWithoutTarget<ICollection>();

            var nonProxiedType = ProxyExtracter.GetNonProxiedType(classProxy.GetType());
            Assert.AreEqual(typeof(ICollection),nonProxiedType);
        }
 public TypedPageActivator()
 {
     _generator = new ProxyGenerator();
     _options = new ProxyGenerationOptions(new PageTypePropertiesProxyGenerationHook());
     _interceptors = new IInterceptor[] 
                        {
                            new PageTypePropertyInterceptor()
                        };
 }
        /// <summary>
        /// Creates a new DocumentProxyManager with a given <see cref="Castle.DynamicProxy.ProxyGenerator"/>.
        /// </summary>
        /// <param name="proxyGenerator"><see cref="Castle.DynamicProxy.ProxyGenerator"/> used to create proxies.</param>
        public DocumentProxyManager(ProxyGenerator proxyGenerator)
        {
            if (proxyGenerator == null)
            {
                throw new ArgumentNullException("proxyGenerator");
            }

            _proxyGenerator = proxyGenerator;
        }
Ejemplo n.º 30
0
        public void ClassProxy()
        {
            var generator = new ProxyGenerator();

            var classProxy = generator.CreateClassProxy<Hashtable>();

            var nonProxiedType = ProxyExtracter.GetNonProxiedType(classProxy.GetType());
            Assert.AreEqual(typeof(Hashtable), nonProxiedType);
        }
Ejemplo n.º 31
0
    public static Disposable <TDisposable> For <TDisposable>(TDisposable wrapAround)
        where TDisposable : class, IDisposable
    {
        Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();

        DisposeInterceptor interceptor = new DisposeInterceptor();
        TDisposable        disposable  = generator.CreateInterfaceProxyWithTarget(wrapAround, interceptor);

        return(new Disposable <TDisposable>(disposable, () => interceptor.IsDisposed));
    }
Ejemplo n.º 32
0
    public static object CreateInterfaceProxyWithTargetInterface(Type interfaceType, object concreteObject)
    {
        var dynamicProxy = new Castle.DynamicProxy.ProxyGenerator();

        var result = dynamicProxy.CreateInterfaceProxyWithTargetInterface(
            interfaceType,
            concreteObject,
            new Castle.DynamicProxy.IInterceptor[] { new Aspect1(), new Aspect2() });

        return(result);
    }
Ejemplo n.º 33
0
        public void castle_proxy_without_target()
        {
            int change = 0;

            var generator = new Castle.DynamicProxy.ProxyGenerator();
            var entity    = (ISimple)generator.CreateInterfaceProxyWithoutTarget <ISimple>(
                interceptors: new SimpleLogInterceptor(column => ++ change));

            entity.Name = "Richie";

            change.Should().Be(1);
        }
Ejemplo n.º 34
0
        public static void Show()
        {
            User user = new User()
            {
                Name     = "Richard",
                Password = "******"
            };

            Castle.DynamicProxy.ProxyGenerator generator = new Castle.DynamicProxy.ProxyGenerator();
            MyInterceptor interceptor   = new MyInterceptor();
            UserProcessor userprocessor = generator.CreateClassProxy <UserProcessor>(interceptor);

            userprocessor.RegUser(user);
        }
        public override void Prepare()
        {
            var pg = new Castle.DynamicProxy.ProxyGenerator();

            this.container = new Container(r =>
            {
                RegisterDummies(r);
                RegisterStandard(r);
                RegisterComplex(r);
                RegisterGeneric(r);
                RegisterMultiple(r);
                RegisterInterceptor(r, pg);
            });
        }
        public override void Prepare()
        {
            var pg = new Castle.DynamicProxy.ProxyGenerator();

            this.container = new Container(r =>
            {
                RegisterBasic(r);

                RegisterPropertyInjection(r);
                RegisterGeneric(r);
                RegisterMultiple(r);
                RegisterInterceptor(r, pg);
            });
        }
        public override void Prepare()
        {
            var pg = new Castle.DynamicProxy.ProxyGenerator();

            this.container = new Container(r =>
            {
                RegisterBasic(r);

                RegisterPropertyInjection(r);
                RegisterGeneric(r);
                RegisterMultiple(r);
                RegisterInterceptor(r, pg);

                ServiceCollection services = new ServiceCollection();
                this.RegisterAspNetCoreClasses(services);
                r.Populate(services);
            });
        }
Ejemplo n.º 38
0
        public void castle_proxy_with_target()
        {
            int change = 0;

            var obj = new SimpleSamepleEntity()
            {
            };

            var generator = new Castle.DynamicProxy.ProxyGenerator();
            var entity    = (SimpleSamepleEntity)generator.CreateClassProxyWithTarget(
                classToProxy: typeof(SimpleSamepleEntity),
                target: obj,
                interceptors: new SimpleLogInterceptor(column => ++ change));

            entity.Name = "Richie";
            entity.Age  = 50;

            change.Should().Be(2);
        }
        public void MyTestMethod()
        {
            var w         = Stopwatch.StartNew();
            var generator = new Castle.DynamicProxy.ProxyGenerator();
            var proxy     = generator.CreateInterfaceProxyWithoutTarget <Repository.Calls.TestRepository>(new Proxy());

            w.Stop();
            Console.WriteLine(w.Elapsed);
            w.Reset();
            int counter = counts;

            w.Start();
            while (true)
            {
                proxy.Read();
                if (counter-- == 0)
                {
                    break;
                }
            }
            w.Stop();
            Console.WriteLine(w.Elapsed);
        }