public object CreateObject(ResolutionContext context) { var typeMap = context.TypeMap; var destinationType = context.DestinationType; if (typeMap != null) if (typeMap.DestinationCtor != null) return typeMap.DestinationCtor(context); else if (typeMap.ConstructDestinationUsingServiceLocator) return context.Options.ServiceCtor(destinationType); else if (typeMap.ConstructorMap != null && typeMap.ConstructorMap.CtorParams.All(p => p.CanResolve)) return typeMap.ConstructorMap.ResolveValue(context); if (context.DestinationValue != null) return context.DestinationValue; if (destinationType.IsInterface()) #if PORTABLE throw new PlatformNotSupportedException("Mapping to interfaces through proxies not supported."); #else destinationType = new ProxyGenerator().GetProxyType(destinationType); #endif return !ConfigurationProvider.AllowNullDestinationValues ? ObjectCreator.CreateNonNullValue(destinationType) : ObjectCreator.CreateObject(destinationType); }
public void CreateInterfaceProxyWithTargetInterface() { ProxyGenerator generator = new ProxyGenerator(); IFooExtended proxiedFoo = (IFooExtended)generator.CreateInterfaceProxyWithTargetInterface( typeof(IFooExtended), new ImplementedFoo(), new StandardInterceptor()); proxiedFoo.FooExtended(); }
public void TypeIsRequiredWhenGeneratingProxy() { //Arrange var generator = new ProxyGenerator(); //Act + Assert Expect.ArgumentNullException(() => generator.Generate(null)); }
public void VoidIsNotAValidTypeWhenGeneratingProxy() { //Arrange var generator = new ProxyGenerator(); //Act + Assert Expect.ArgumentOutOfRangeException(() => generator.Generate(typeof(void))); }
static DynamicProxyMockFactory() { #if DEBUG generator = new ProxyGenerator(new DefaultProxyBuilder(new ModuleScope(savePhysicalAssembly: true))); #else generator = new ProxyGenerator(); #endif }
public void ProxyAnAbstractClass() { ProxyGenerator generator = new ProxyGenerator(); LoginInterceptor interceptor = new LoginInterceptor(); AbsCls ac = (AbsCls)generator.CreateClassProxy(typeof(AbsCls),interceptor, false); ac.Method(); Assert.AreEqual("Method", interceptor.Methods[0]); }
public void On_interfaces() { ProxyGenerationOptions options = new ProxyGenerationOptions(); options.AttributesToAddToGeneratedTypes.Add(new __Protect()); object proxy = new ProxyGenerator().CreateInterfaceProxyWithoutTarget(typeof(IDisposable), new Type[0], options); Assert.IsTrue(proxy.GetType().IsDefined(typeof(__Protect), false)); }
public void CreateProxyOfTypeWithMixinCausingDiamondWhenMethodIsNonVirtual() { ProxyGenerator generator = new ProxyGenerator(); object proxy = generator.CreateClassProxy(typeof(FirstImpl), new Type[]{typeof(ISecond)}, new StandardInterceptor(), false); Assert.IsTrue(proxy is FirstImpl); Assert.IsTrue(proxy is IFirst); Assert.IsTrue(proxy is ISecond); }
public void On_class() { ProxyGenerationOptions options = new ProxyGenerationOptions(); options.AttributesToAddToGeneratedTypes.Add(new __Protect()); object proxy = new ProxyGenerator().CreateClassProxy(typeof(CanDefineAdditionalCustomAttributes), options); Assert.IsTrue(proxy.GetType().IsDefined(typeof(__Protect), false)); }
public void ResetGeneratorAndBuilder() { #if SILVERLIGHT // no PersistentProxyBuilder in Silverlight builder = new DefaultProxyBuilder(); #else builder = new PersistentProxyBuilder(); #endif generator = new ProxyGenerator(builder); }
public DynamicProxyCreationBenchmark() { var proxyBuilder = new ProxyBuilder(); var proxyGenerator = new ProxyGenerator(); var proxyFactory = new ProxyFactory(); _proxyType = proxyBuilder.GetProxyType(new ProxyDefinition(typeof(TestClass), true).Implement(() => new LightInjectInterceptor())); _dynamicProxyType = proxyGenerator.ProxyBuilder.CreateClassProxyType(typeof(TestClass), Type.EmptyTypes, ProxyGenerationOptions.Default); _nProxyInterceptor = new NProxyInterceptor(); _nproxyTemplate = proxyFactory.GetProxyTemplate(typeof(TestClass), Enumerable.Empty<Type>()); }
public void CreateSerializable() { MySerializableClass myClass = new MySerializableClass(); ProxyGenerator generator = new ProxyGenerator(); MySerializableClass proxy = (MySerializableClass) generator.CreateClassProxy( typeof(MySerializableClass), new StandardInvocationHandler(myClass) ); Assert.IsTrue( proxy.GetType().IsSerializable ); }
private void TryLoggingViaProxy() { var generator = new ProxyGenerator(); var testLogger2 = generator.CreateClassProxy<TestLogger2>( ServiceLocator.Current.GetInstance<IInterceptor>("LogInterceptor")); testLogger2.GetMessage("message1"); testLogger2.GetMessageVirtual("message2"); testLogger2.GetMessageNotLogged("message3"); }
public void ProxyImplementsIDynamicProxy() { //Arrange var generator = new ProxyGenerator(); //Act var result = generator.Generate(typeof(ITestInterfaceExtended)); //Assert Assert.IsTrue(result.Code.Contains("BaseConfiguration IHaveConfiguration.Configuration")); }
public void CanGetParameterAttributeFromProxiedObject() { ProxyGenerator pg = new ProxyGenerator(); ClassWithAttributesOnMethodParameters requiredObj = (ClassWithAttributesOnMethodParameters) pg.CreateClassProxy( typeof(ClassWithAttributesOnMethodParameters), new RequiredParamInterceptor()); requiredObj.MethodTwo(null); }
public void ParametersAreCopiedToProxiedObject() { ProxyGenerator pg = new ProxyGenerator(); ClassWithAttributesOnMethodParameters requiredObj = (ClassWithAttributesOnMethodParameters) pg.CreateClassProxy( typeof(ClassWithAttributesOnMethodParameters), new RequiredParamInterceptor()); requiredObj.MethodOne(-1); }
public static IDataReader NewInstance(IDataReader reader) { object proxyCommand = null; IInterceptor handler = new IDataReaderProxy(reader); ProxyGenerator proxyGenerator = new ProxyGenerator(); proxyCommand = proxyGenerator.CreateProxy(typeof(IDataReader), handler, reader); return (IDataReader) proxyCommand; }
public void WithNullableDynamicProxyObject() { ProxyGenerator generator = new ProxyGenerator(); SimpleProxy proxy = (SimpleProxy)generator.CreateClassProxy(typeof(SimpleProxy), new StandardInterceptor()); PropertyBag["src"] = proxy; ProcessView_StripRailsExtension("home/WithNullableDynamicProxyObject.rails"); string expected = @"BarBaz foo what? there"; AssertReplyEqualTo(expected); }
public void MethodsFromDerivedInterfacesShouldAlsoBeProxied() { //Arrange var generator = new ProxyGenerator(); //Act var result = generator.Generate(typeof(ITestInterfaceExtended)); //Assert Assert.IsTrue(result.Code.Contains("public System.Boolean Baz()")); Assert.IsTrue(result.Code.Contains("public System.Int32 get_Bar()")); Assert.IsTrue(result.Code.Contains("public void Foo()")); }
public void CacheMiss() { // Arrange CollectingLogger logger = new CollectingLogger(); ProxyGenerator generator = new ProxyGenerator { Logger = logger }; // Act generator.CreateClassProxy<EmptyClass>(); // Assert Assert.That(logger.RecordedMessage(LoggerLevel.Debug, "No cached proxy type was found for target type " + "CastleTests.DynamicProxy.Tests.Classes.EmptyClass.")); }
public void ProtectedConstructor() { ProxyGenerator generator = new ProxyGenerator(); NonPublicConstructorClass proxy = generator.CreateClassProxy( typeof(NonPublicConstructorClass), new StandardInterceptor() ) as NonPublicConstructorClass; Assert.IsNotNull(proxy); proxy.DoSomething(); }
public void CacheHitInterfaceProxy() { // Arrange CollectingLogger logger = new CollectingLogger(); ProxyGenerator generator = new ProxyGenerator { Logger = logger }; // Act generator.CreateInterfaceProxyWithoutTarget<IEmptyInterface>(); generator.CreateInterfaceProxyWithoutTarget<IEmptyInterface>(); // Assert Assert.That(logger.RecordedMessage(LoggerLevel.Debug, "Found cached proxy type Castle.Proxies.IEmptyInterfaceProxy " + "for target type Castle.DynamicProxy.Tests.LoggingTestCase+IEmptyInterface.")); }
public void CacheHitClassProxy() { // Arrange CollectingLogger logger = new CollectingLogger(); ProxyGenerator generator = new ProxyGenerator { Logger = logger }; // Act generator.CreateClassProxy<EmptyClass>(); generator.CreateClassProxy<EmptyClass>(); // Assert Assert.That(logger.RecordedMessage(LoggerLevel.Debug, "Found cached proxy type Castle.Proxies.EmptyClassProxy " + "for target type Castle.DynamicProxy.Tests.LoggingTestCase+EmptyClass.")); }
public void EnsureProxyHasAttributesOnClassAndMethods() { ProxyGenerator generator = new ProxyGenerator(); AttributedClass instance = (AttributedClass) generator.CreateClassProxy(typeof(AttributedClass), new StandardInterceptor()); object[] attributes = instance.GetType().GetCustomAttributes(typeof(NonInheritableAttribute), false); Assert.AreEqual(1, attributes.Length); Assert.IsInstanceOfType(typeof(NonInheritableAttribute), attributes[0]); attributes = instance.GetType().GetMethod("Do1").GetCustomAttributes(typeof(NonInheritableAttribute), false); Assert.AreEqual(1, attributes.Length); Assert.IsInstanceOfType(typeof(NonInheritableAttribute), attributes[0]); }
public void ProtectedMethods() { ProxyGenerator generator = new ProxyGenerator(); LogInvocationInterceptor logger = new LogInvocationInterceptor(); NonPublicMethodsClass proxy = (NonPublicMethodsClass) generator.CreateClassProxy( typeof(NonPublicMethodsClass), logger ); proxy.DoSomething(); Assert.AreEqual( 2, logger.Invocations.Length ); Assert.AreEqual( "DoSomething", logger.Invocations[0] ); Assert.AreEqual( "DoOtherThing", logger.Invocations[1] ); }
public void ProxyGenerationOptionsEqualsAndGetHashCodeNotOverriden() { // Arrange CollectingLogger logger = new CollectingLogger(); ProxyGenerator generator = new ProxyGenerator { Logger = logger }; // Act ProxyGenerationOptions options = new ProxyGenerationOptions { Hook = new EmptyHook() }; generator.CreateClassProxy(typeof(EmptyClass), options); // Assert Assert.That(logger.RecordedMessage(LoggerLevel.Warn, "The IProxyGenerationHook type " + "Castle.DynamicProxy.Tests.LoggingTestCase+EmptyHook does not override both Equals and GetHashCode. " + "If these are not correctly overridden caching will fail to work causing performance problems.")); }
public void ProxyIsXmlSerializable() { ProxyGenerator gen = new ProxyGenerator(); ClassToSerialize proxy = (ClassToSerialize) gen.CreateClassProxy(typeof(ClassToSerialize), new StandardInterceptor()); XmlSerializer serializer = new XmlSerializer(proxy.GetType()); StringWriter writer = new StringWriter(); serializer.Serialize(writer, proxy); StringReader reader = new StringReader(writer.GetStringBuilder().ToString()); object newObj = serializer.Deserialize(reader); Assert.IsNotNull(newObj); Assert.IsInstanceOfType(typeof(ClassToSerialize), newObj); }
public void CanHandleDynamicProxyObjects() { ProxyGenerator generator = new ProxyGenerator(); object o = generator.CreateClassProxy(typeof(HomeController.SimpleProxy), new StandardInterceptor()); try { o.GetType().GetProperty("Text"); } catch(AmbiguousMatchException) { } PropertyBag["src"] = o; string expected = "<?xml version=\"1.0\" ?>\r\n" + @"<html> <h1>BarBaz</h1> </html>"; // should not raise ambigious match exception ProcessView_StripRailsExtension("Home/withDynamicProxyObject.rails"); AssertReplyEqualTo(expected); }
public void AttributesOnTargetClassesWithInterfaceProxy() { ProxyGenerator _generator = new ProxyGenerator(); AttributeCheckerInterceptor interceptor = new AttributeCheckerInterceptor(); object proxy = _generator.CreateProxy(typeof (IMyInterface), interceptor, new MyInterfaceImpl()); IMyInterface inter = (IMyInterface) proxy; Assert.AreEqual(45, inter.Calc(20, 25)); Assert.IsTrue(interceptor.LastMethodHasAttribute); Assert.IsTrue(interceptor.LastTargethasAttribute); Assert.AreEqual(48, inter.Calc(20, 25, 1, 2)); Assert.IsTrue(interceptor.LastMethodHasAttribute); Assert.IsTrue(interceptor.LastTargethasAttribute); inter.Name = "hammett"; Assert.IsFalse(interceptor.LastMethodHasAttribute); Assert.IsTrue(interceptor.LastTargethasAttribute); }
public void EnsureProxyHasAttributesOnClassAndMethods_ComplexAttributes() { ProxyGenerator generator = new ProxyGenerator(); AttributedClass2 instance = (AttributedClass2) generator.CreateClassProxy(typeof(AttributedClass2), new StandardInterceptor()); object[] attributes = instance.GetType().GetCustomAttributes(typeof(ComplexNonInheritableAttribute), false); Assert.AreEqual(1, attributes.Length); Assert.IsInstanceOfType(typeof(ComplexNonInheritableAttribute), attributes[0]); ComplexNonInheritableAttribute att = (ComplexNonInheritableAttribute) attributes[0]; // (1, 2, true, "class", FileAccess.Write) Assert.AreEqual(1, att.Id); Assert.AreEqual(2, att.Num); Assert.AreEqual(true, att.IsSomething); Assert.AreEqual("class", att.Name); Assert.AreEqual(FileAccess.Write, att.Access); attributes = instance.GetType().GetMethod("Do1").GetCustomAttributes(typeof(ComplexNonInheritableAttribute), false); Assert.AreEqual(1, attributes.Length); Assert.IsInstanceOfType(typeof(ComplexNonInheritableAttribute), attributes[0]); att = (ComplexNonInheritableAttribute) attributes[0]; // (2, 3, "Do1", Access = FileAccess.ReadWrite) Assert.AreEqual(2, att.Id); Assert.AreEqual(3, att.Num); Assert.AreEqual(false, att.IsSomething); Assert.AreEqual("Do1", att.Name); Assert.AreEqual(FileAccess.ReadWrite, att.Access); attributes = instance.GetType().GetMethod("Do2").GetCustomAttributes(typeof(ComplexNonInheritableAttribute), false); Assert.AreEqual(1, attributes.Length); Assert.IsInstanceOfType(typeof(ComplexNonInheritableAttribute), attributes[0]); att = (ComplexNonInheritableAttribute) attributes[0]; // (3, 4, "Do2", IsSomething=true) Assert.AreEqual(3, att.Id); Assert.AreEqual(4, att.Num); Assert.AreEqual(true, att.IsSomething); Assert.AreEqual("Do2", att.Name); }
public void Cache_With_AOP() { ProxyGenerator proxyGenerator = new ProxyGenerator(); IRepository repository = new Repository(); IRepository repositoryProxy = proxyGenerator.CreateInterfaceProxyWithTargetInterface <IRepository>(repository, new CacheInterceptor()); Debug.WriteLine("First run..."); IList <string> languages = repositoryProxy.GetLanguages(); Assert.AreEqual <string>("English", languages[0]); Assert.AreEqual <string>("Japanese", languages[1]); Assert.AreEqual <string>("Simplified Chinese", languages[2]); Assert.AreEqual <string>("Traditional Chinese", languages[3]); Debug.WriteLine("Second run..."); IList <string> cachedLanguages = repositoryProxy.GetLanguages(); Assert.AreEqual <string>("English", cachedLanguages[0]); Assert.AreEqual <string>("Japanese", cachedLanguages[1]); Assert.AreEqual <string>("Simplified Chinese", cachedLanguages[2]); Assert.AreEqual <string>("Traditional Chinese", cachedLanguages[3]); Debug.WriteLine("First run..."); IList <Setting> settings = repositoryProxy.GetSettings(); Assert.AreEqual <string>("Domain", settings[0].Name); Assert.AreEqual <string>("dev.pete.tw", settings[0].Value); Assert.AreEqual <string>("Administrator", settings[1].Name); Assert.AreEqual <string>("Pete", settings[1].Value); Debug.WriteLine("Second run..."); IList <Setting> cachedSettings = repositoryProxy.GetSettings(); Assert.AreEqual <string>("Domain", cachedSettings[0].Name); Assert.AreEqual <string>("dev.pete.tw", cachedSettings[0].Value); Assert.AreEqual <string>("Administrator", cachedSettings[1].Name); Assert.AreEqual <string>("Pete", cachedSettings[1].Value); }
public void UpdateProxyTemplate() { if (SelectedItem == null) { return; } var properties = StoredProxyProperties.Where(x => x.Name != null).ToDictionary(x => x.Name, x => x.Value); //this stuff generates the real proxy image, maybe we'll need to keep it in for more accurate image var proxy = ProxyGenerator.GenerateProxy(_proxydef.BlockManager, _proxydef.RootPath, SelectedItem._def, properties, null); using (var ms = new MemoryStream()) { proxy.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Position = 0; ProxyImage = new BitmapImage(); ProxyImage.BeginInit(); ProxyImage.CacheOption = BitmapCacheOption.OnLoad; ProxyImage.StreamSource = ms; ProxyImage.EndInit(); } proxy.Dispose(); BaseImage = new BitmapImage(new Uri(Path.Combine(SelectedItem._def.rootPath, SelectedItem._def.src))); ActiveOverlayLayers = new ObservableCollection <ProxyOverlayItemModel>( SelectedItem._def.GetOverLayBlocks(properties).Select( x => OverlayBlocks.First(y => y.Name == x.Block))); ActiveTextLayers = new ObservableCollection <ProxyTextLinkItemModel>( SelectedItem._def.GetTextBlocks(properties).Select( x => new ProxyTextLinkItemModel(x))); RaisePropertyChanged("BaseImage"); RaisePropertyChanged("BaseWidth"); RaisePropertyChanged("BaseHeight"); RaisePropertyChanged(""); }
public void Should_Intercept_And_Commit_Transaction_On_Sync_Method_That_Return_Void() { var services = new ServiceCollection(); var proxyGenerator = new ProxyGenerator(); services.AddDNTFrameworkCore(); var transactionMock = new Mock <ITransaction>(); transactionMock.Setup(transaction => transaction.Commit()); transactionMock.Setup(transaction => transaction.Rollback()); var transactionProviderMock = new Mock <ITransactionProvider>(); transactionProviderMock.Setup(transactionProvider => transactionProvider.BeginTransaction(IsolationLevel.ReadCommitted)) .Returns(() => transactionMock.Object).Callback(() => { transactionProviderMock.SetupGet(transactionProvider => transactionProvider.CurrentTransaction).Returns(transactionMock.Object); }); services.Replace(ServiceDescriptor.Scoped(provider => transactionProviderMock.Object)); services.AddScoped <IPartyService, PartyService>(); services.Decorate <IPartyService>((target, provider) => (IPartyService)proxyGenerator.CreateInterfaceProxyWithTarget(typeof(IPartyService), target, provider.GetService <TransactionInterceptorBase>())); var service = services.BuildServiceProvider().GetRequiredService <IPartyService>(); service.VoidSyncMethod(); transactionProviderMock.Verify(transaction => transaction.BeginTransaction(IsolationLevel.ReadCommitted)); transactionProviderMock.Verify(transaction => transaction.CurrentTransaction); transactionMock.Verify(transaction => transaction.Commit()); }
/// <summary> /// Returns a list of entites from table "Ts". /// Id of T must be marked with [Key] attribute. /// Entities created from interfaces are tracked/intercepted for changes and used by the Update() extension /// for optimal performance. /// </summary> /// <typeparam name="T">Interface or type to create and populate</typeparam> /// <param name="connection">Open SqlConnection</param> /// <param name="transaction">The transaction to run under, null (the defualt) if none</param> /// <param name="commandTimeout">Number of seconds before command execution timeout</param> /// <returns>Entity of T</returns> public static async Task <IEnumerable <T> > GetAllAsync <T>(this IDbConnection connection, IDbTransaction transaction = null, int?commandTimeout = null) where T : class { var type = typeof(T); var cacheType = typeof(List <T>); string sql; if (!GetQueries.TryGetValue(cacheType.TypeHandle, out sql)) { GetSingleKey <T>(nameof(GetAll)); var name = GetTableName(type); sql = "SELECT * FROM " + name; GetQueries[cacheType.TypeHandle] = sql; } if (!type.IsInterface()) { return(await connection.QueryAsync <T>(sql, null, transaction, commandTimeout)); } var result = await connection.QueryAsync(sql); var list = new List <T>(); foreach (IDictionary <string, object> res in result) { var obj = ProxyGenerator.GetInterfaceProxy <T>(); foreach (var property in TypePropertiesCache(type)) { var val = res[property.Name]; property.SetValue(obj, Convert.ChangeType(val, property.PropertyType), null); } ((IProxy)obj).IsDirty = false; //reset change tracking and return list.Add(obj); } return(list); }
public void DictionaryDeserializationWithProxyTest() { ProxyGenerator generator = new ProxyGenerator(); Dictionary <ClassOverridingEqualsAndGetHashCode, string> theInstances = new Dictionary <ClassOverridingEqualsAndGetHashCode, string>(); for (int i = 0; i < 50; i++) { ClassOverridingEqualsAndGetHashCode c = (ClassOverridingEqualsAndGetHashCode)generator.CreateClassProxy( typeof(ClassOverridingEqualsAndGetHashCode) ); c.Id = Guid.NewGuid(); c.Name = DateTime.Now.ToString("yyyyMMddHHmmss"); theInstances.Add(c, c.Name); } #pragma warning disable 219 Dictionary <ClassOverridingEqualsAndGetHashCode, string> theInstancesBis = SerializeAndDeserialize <Dictionary <ClassOverridingEqualsAndGetHashCode, string> >( theInstances ); #pragma warning restore 219 }
// ReSharper disable once UnusedMember.Local private static object CreateCallbackProxy( ProxyGenerator proxyGenerator , Action <IComponentRegistry> callback , // ReSharper disable once UnusedParameter.Global // ReSharper disable once UnusedParameter.Local DeferredCallback defer ) { Logger.Info("Creating deffered callback proxy"); var x = proxyGenerator.CreateClassProxy( typeof(DeferredCallback) , new ProxyGenerationOptions( new CallBackHook( ) ) , new object[] { callback } , new CallbackInterceptor(proxyGenerator) ); return(x); }
static void Main(string[] args) { //var srv=new InvoiceService(); var proxyGenerator = new ProxyGenerator(); //使用被拦截的类和自定义的切面类创建动态代理 var srv = proxyGenerator.CreateClassProxy <InvoiceService>(new TransactionWithRetries(3)); var invoice = new Invoice { Id = Guid.NewGuid(), Date = DateTime.Now, Items = new List <string>() { "1", "2", "3" } }; //srv.Save(invoice);//使用这个Save方法来测试一下 srv.SaveRetry(invoice); // srv.SaveFail(invoice); Console.WriteLine("执行结束"); Console.Read(); }
public static TInterface CreateInterfaceProxy <TInterface>(Usr usr) where TInterface : class { ProxyGenerator generator = new ProxyGenerator(); string tname = typeof(TInterface).Name; NameValueCollection mgrs = (NameValueCollection)ConfigurationManager.GetSection("ManagerGroup/Interface"); string implName = mgrs[tname]; if (StringUtil.isEmpty(implName)) { implName = tname.Substring(1); } string nms = ConfigurationManager.AppSettings["mgrImplNamespace"]; string implFullName = nms + "." + implName; int? connId = ConnectorFactory.GenConnector(); if (null == connId) { return(null); } TInterface target = (TInterface)Activator.CreateInstance(Type.GetType(implFullName), new object[] { connId }); return(generator.CreateInterfaceProxyWithTarget <TInterface>(target, new MgrInterceptor(connId, implFullName))); }
public static IServiceCollection AddTransientWithInstrumentation <T, TImplementation>(this IServiceCollection services) where T : class where TImplementation : class, T { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.TryAddTransient <LogInterceptor>(); services.TryAddTransient <TImplementation>(); services.AddTransient(sp => { var logInterceptor = sp.GetRequiredService <LogInterceptor>(); var implementation = sp.GetRequiredService <TImplementation>(); var proxyFactory = new ProxyGenerator(); return(proxyFactory.CreateInterfaceProxyWithTarget <T>(implementation, logInterceptor)); }); return(services); }
public void can_resolve_through_registry() { var controllerTypeConstraint = new ControllerTypeConstraint <TestController>(); var method = typeof(TestController).GetMethods().First(x => x.Name.Equals("ReturnNull") && x.GetParameters().Count() == 0); var actionDescriptor = new ReflectedActionDescriptor(method, "ReturnNull", new ReflectedControllerDescriptor(typeof(TestController))); var registry = new ActionFilterRegistry(new FluentMvcObjectFactory()); registry.Add(new ControllerActionRegistryItem(typeof(TestFilter), controllerTypeConstraint, actionDescriptor, actionDescriptor.ControllerDescriptor)); var proxyGenerator = new ProxyGenerator(); var interfaceProxyWithTarget = proxyGenerator.CreateClassProxy <TestController>(); var controllerType = interfaceProxyWithTarget.GetType(); var methodInfos = controllerType.GetMethods(); var proxyActionDescriptor = new ReflectedActionDescriptor(methodInfos.First(x => x.Name.Equals("ReturnNull") && x.GetParameters().Count() == 0), "ReturnNull", new ReflectedControllerDescriptor(controllerType)); registry .CanSatisfy(new ControllerActionFilterSelector(null, proxyActionDescriptor, proxyActionDescriptor.ControllerDescriptor)) .ShouldBeTrue(); }
public void Setup() { // It's hard to hand construct a proxy - so we'll go via the proxy generator. _fakeDriver = new Mock <IDriverBindings>(); _fakeDriver.Setup(x => x.Substitutes).Returns(new List <DriverBindings.TypeSubstitution> { new DriverBindings.TypeSubstitution(typeof(InterceptedType.SubbedType), () => new InterceptedType.SubbedType { Val = "Hi" }) }); _fakeDriver.Setup(x => x.NavigationHandlers).Returns(new List <DriverBindings.IHandle> { new DriverBindings.Handle <IdAttribute>((s, d) => "an id string"), new DriverBindings.Handle <LinkTextAttribute>((s, d) => "a text string"), new DriverBindings.Handle <CssSelectorAttribute>((s, d) => new FakeWebElement(s)) }); _cfg = new PassengerConfiguration { Driver = _fakeDriver.Object }; _proxy = ProxyGenerator.Generate <InterceptedType>(_cfg); }
public void CanHandleDynamicProxyObjects() { var generator = new ProxyGenerator(); var o = generator.CreateClassProxy(typeof(HomeController.SimpleProxy), new StandardInterceptor()); try { o.GetType().GetProperty("Text"); } catch (AmbiguousMatchException) { } PropertyBag["src"] = o; var expected = "<?xml version=\"1.0\" ?>\r\n" + @"<html> <h1>BarBaz</h1> </html>"; // should not raise ambigious match exception ProcessView_StripRailsExtension("Home/withDynamicProxyObject.rails"); AssertReplyEqualTo(expected); }
private ServiceClientFactoryImpl CreateServiceClientFactory(params PofContext[] pofContexts) { var proxyGenerator = new ProxyGenerator(); ICollectionFactory collectionFactory = new CollectionFactory(); IThreadingFactory threadingFactory = new ThreadingFactory(); ISynchronizationFactory synchronizationFactory = new SynchronizationFactory(); IThreadingProxy threadingProxy = new ThreadingProxy(threadingFactory, synchronizationFactory); IDnsProxy dnsProxy = new DnsProxy(); ITcpEndPointFactory tcpEndPointFactory = new TcpEndPointFactory(dnsProxy); IStreamFactory streamFactory = new StreamFactory(); INetworkingInternalFactory networkingInternalFactory = new NetworkingInternalFactory(threadingProxy, streamFactory); ISocketFactory socketFactory = new SocketFactory(tcpEndPointFactory, networkingInternalFactory); INetworkingProxy networkingProxy = new NetworkingProxy(socketFactory, tcpEndPointFactory); PofContext pofContext = new DspPofContext(); pofContexts.ForEach(pofContext.MergeContext); IPofSerializer pofSerializer = new PofSerializer(pofContext); PofStreamsFactory pofStreamsFactory = new PofStreamsFactoryImpl(threadingProxy, streamFactory, pofSerializer); PortableObjectBoxConverter portableObjectBoxConverter = new PortableObjectBoxConverter(streamFactory, pofSerializer); InvokableServiceContextFactory invokableServiceContextFactory = new InvokableServiceContextFactoryImpl(collectionFactory, portableObjectBoxConverter); return(new ServiceClientFactoryImpl(proxyGenerator, streamFactory, collectionFactory, threadingProxy, networkingProxy, pofSerializer, pofStreamsFactory)); }
public void RemoveCountInterceptorAtRuntime_byInstance_Test() { var counter = new CounterInterceptor(); Person per = new ProxyGenerator().CreateClassProxy <Person>(counter); per.FirstName = "Foo"; per.LastName = "Bar"; Assert.AreEqual(1, ProxyHelper.GetInterceptorsField(per).Count()); Assert.AreEqual(per.FirstName, "Foo"); ProxyHelper.ExcudeInterceptors(per, counter); Assert.AreEqual(3, counter.CallsCount); Assert.AreEqual(per.LastName, "Bar"); Assert.AreEqual(3, counter.CallsCount); Assert.AreEqual(0, ProxyHelper.GetInterceptorsField(per).Count()); }
public ProxyFactory(ProxyGenerator proxyGenerator, Type type, ProxyGenerationOptions options) { this.originalType = type; var classGenerator = new CustomClassProxyGenerator(proxyGenerator.ProxyBuilder.ModuleScope, type) { Logger = proxyGenerator.ProxyBuilder.Logger }; this.proxyType = classGenerator.GenerateCode(Type.EmptyTypes, options); this.constructors = new ConcurrentDictionary <string, Func <object[], object> >(); foreach (var ctor in proxyType.GetConstructors()) { var ctorArgs = ctor.GetParameters(); if (ctorArgs.Length == 0) { continue; } var tuple = MakeCreateExpression(proxyType, options.Selector, options.MixinData, ctor, ctorArgs); constructors.TryAdd(tuple.Item1, tuple.Item2.Compile()); } this.init = MakeInitExpression(proxyType, options.Selector, options.MixinData).Compile(); }
static void Run(string[] args) { if (args.Length != 2) { throw new PrettyException(@"Please call the tool like this: d60.Cirqus.TsClient <path-to-DLL> <output-directory> where <path-to-DLL> should point to an assembly containing all of your commands, and <output-directory> should be the directory in which you want the generated 'commands.ts' and 'commandProcessor.ts' to be put."); } var sourceDll = args[0]; var destinationDirectory = args[1]; if (!File.Exists(sourceDll)) { throw new FileNotFoundException(string.Format("Could not find source DLL {0}", sourceDll)); } if (!Directory.Exists(destinationDirectory)) { Writer.Print("Creating directory {0}", destinationDirectory); Directory.CreateDirectory(destinationDirectory); } var proxyGenerator = new ProxyGenerator(sourceDll, Writer); var results = proxyGenerator.Generate().ToList(); Writer.Print("Writing files"); foreach (var result in results) { result.WriteTo(destinationDirectory); } }
public void ProxyGenerator_Create_Interface_Proxy_ByOrder(IRpcProxyService proxyService, ProxyGenerator proxyGenerator, Fixture fixture) { byte[] bytes = new byte[0]; proxyService.MakeCallWithReturn <int>(typeof(IIntMathService).Namespace, typeof(IIntMathService).Name, nameof(IIntMathService.Add), Arg.Any <byte[]>(), false, false) .Returns(c => { bytes = c.Arg <byte[]>(); return(15); }); var proxyType = proxyGenerator.GenerateProxyType(typeof(IIntMathService), false); var instance = (IIntMathService)fixture.Locate(proxyType); var value = instance.Add(5, 10); Assert.Equal(15, value); var request = bytes.Deserialize <RpcRequestMessage>(); Assert.NotNull(request); Assert.Equal("2.0", request.Version); Assert.Equal("Add", request.Method); Assert.False(string.IsNullOrEmpty(request.Id)); var objectArray = ((JArray)request.Parameters).ToObject <object[]>(); Assert.NotNull(objectArray); Assert.Equal(2, objectArray.Length); Assert.Equal(5, Convert.ToInt32(objectArray[0])); Assert.Equal(10, Convert.ToInt32(objectArray[1])); }
public object Invoke(object instance, object[] inputs, out object[] outputs) { outputs = null; var request = System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest; var endpointUrl = RewriteUri(this.Endpoint.Address.Uri, request.Headers["HOST"]).AbsoluteUri; var requestUrl = RewriteUri(OperationContext.Current.IncomingMessageProperties.Via, request.Headers["HOST"]).AbsoluteUri; var scriptUrl = endpointUrl + (endpointUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase) ? WfWebScriptBehavior.METADATA_ENDPOINT_SUFFIX : "/" + WfWebScriptBehavior.METADATA_ENDPOINT_SUFFIX); var scriptDebugUrl = endpointUrl + (endpointUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase) ? WfWebScriptBehavior.DEBUG_METADATA_ENDPOINT_SUFFIX : "/" + WfWebScriptBehavior.DEBUG_METADATA_ENDPOINT_SUFFIX); if (requestUrl == scriptUrl || requestUrl == scriptDebugUrl) { Message replyMsg = null; if (IsServiceUnChanged()) { replyMsg = CreateNotModifiedMessage(); } else { string scriptContent = ProxyGenerator.GetClientProxyScript(this.Endpoint.Contract.ContractType, endpointUrl, false, this.Endpoint); replyMsg = CreateMetadataMessage(scriptContent); } return(replyMsg); } if (inputs == null) { inputs = new object[1]; } inputs[0] = OperationContext.Current.RequestContext.RequestMessage;; return(this.DefaultUnhandledDispatchOperation.Invoker.Invoke(instance, inputs, out outputs)); }
object IMappingEngineRunner.CreateObject(ResolutionContext context) { var typeMap = context.TypeMap; var destinationType = context.DestinationType; if (typeMap != null) { if (typeMap.DestinationCtor != null) { return(typeMap.DestinationCtor(context)); } else if (typeMap.ConstructDestinationUsingServiceLocator && context.Options.ServiceCtor != null) { return(context.Options.ServiceCtor(destinationType)); } else if (typeMap.ConstructDestinationUsingServiceLocator) { return(_configurationProvider.ServiceCtor(destinationType)); } else if (typeMap.ConstructorMap != null) { return(typeMap.ConstructorMap.ResolveValue(context, this)); } } if (context.DestinationValue != null) { return(context.DestinationValue); } if (destinationType.IsInterface) { destinationType = ProxyGenerator.GetProxyType(destinationType); } return(ObjectCreator.CreateObject(destinationType)); }
public void AsyncAggregatedPropertyValidationTest() { var mockModule = new Mock <IMyAsyncModule>(MockBehavior.Loose); var mockInjector = new Mock <IInjector>(MockBehavior.Strict); mockInjector .Setup(i => i.TryGet(typeof(IRequestContext), null)) .Returns <Type, string>((iface, name) => null); Type proxyType = ProxyGenerator <IMyAsyncModule, ParameterValidator <IMyAsyncModule> > .GetGeneratedType(); IMyAsyncModule module = (IMyAsyncModule)Activator.CreateInstance(proxyType, mockModule.Object, mockInjector.Object, true) !; Assert.DoesNotThrowAsync(() => module.Foo(new MyArg { Value = "cica" })); var ex = Assert.ThrowsAsync <AggregateException>(() => module.Foo(new MyArg())); Assert.That(ex.InnerExceptions.Count, Is.EqualTo(1)); Assert.That(ex.InnerExceptions[0], Is.InstanceOf <ValidationException>()); }
public void Should_Intercept_IApplicationService_Sync_Method_Return_Void() { var services = new ServiceCollection(); var proxyGenerator = new ProxyGenerator(); services.AddLogging(); services.AddOptions(); services.AddFramework() .WithModelValidation(); services.AddScoped <IPartyService, PartyService>(); services.Decorate <IPartyService>((target, provider) => (IPartyService)proxyGenerator.CreateInterfaceProxyWithTarget(typeof(IPartyService), target, provider.GetRequiredService <ValidationInterceptor>())); var service = services.BuildServiceProvider().GetRequiredService <IPartyService>(); var exception = Assert.Throws <ValidationException>(() => service.VoidSyncMethod(new PartyModel())); exception.ShouldNotBeNull(); exception.Failures.Any(validationResult => validationResult.MemberName == nameof(PartyModel.DisplayName)); }
public async Task Should_Intercept_IApplicationService_Async_Method_Return_TaskResult() { var services = new ServiceCollection(); var proxyGenerator = new ProxyGenerator(); services.AddLogging(); services.AddOptions(); services.AddFramework() .WithModelValidation(); services.AddScoped <IPartyService, PartyService>(); services.Decorate <IPartyService>((target, provider) => (IPartyService)proxyGenerator.CreateInterfaceProxyWithTarget(typeof(IPartyService), target, provider.GetRequiredService <ValidationInterceptor>())); var service = services.BuildServiceProvider().GetRequiredService <IPartyService>(); var result = await service.AsyncMethod(new PartyModel()); result.Failed.ShouldBeTrue(); result.Failures.Any(validationResult => validationResult.MemberName == nameof(PartyModel.DisplayName)); }
public void Mixin_With_ClassProxy() { var generator = new ProxyGenerator(); var options = new ProxyGeneratorOptions(); options.AddMixinInstance(new PropertyChangedNotifier()); var proxy = generator.CreateClassProxy <MyClass>(options); Assert.AreEqual(0, MyClass.States.Count); proxy.Title = "New title"; Assert.AreEqual(1, MyClass.States.Count); Assert.AreEqual(StateTypes.Notify, MyClass.States[0]); MyClass.States.Clear(); proxy.UpdateTitle(); Assert.AreEqual(1, MyClass.States.Count); Assert.AreEqual(StateTypes.Notify, MyClass.States[0]); }
public void DefineMethod_Adds_MethodBuilder() { var moduleScope = new ModuleScope(); var generator = new ProxyGenerator(moduleScope); var typeDefinition = generator.GetTypeDefinition(typeof(EmpyType), null, null); TypeBuilder typeBulder = moduleScope.Module.DefineType(typeDefinition.FullName, typeDefinition.TypeAttributes); var proxyScope = new ProxyScope(moduleScope, typeBulder, typeDefinition); proxyScope.DefineTypeAndMembers(); Assert.AreEqual(0, proxyScope.Methods.Count); var m = proxyScope.DefineMethod("M", MethodAttributes.Public, typeof(string), new Type[] { typeof(string) }); Assert.AreEqual(1, proxyScope.Methods.Count); Assert.AreEqual("M", proxyScope.Methods[0].Name); var m2 = proxyScope.DefineMethod("M2", MethodAttributes.Public); Assert.AreEqual(2, proxyScope.Methods.Count); Assert.AreEqual("M2", proxyScope.Methods[1].Name); }
public void DefineField_Adds_FieldBuilder() { var moduleScope = new ModuleScope(); var generator = new ProxyGenerator(moduleScope); var typeDefinition = generator.GetTypeDefinition(typeof(EmpyType), null, null); TypeBuilder typeBulder = moduleScope.Module.DefineType(typeDefinition.FullName, typeDefinition.TypeAttributes); var proxyScope = new ProxyScope(moduleScope, typeBulder, typeDefinition); proxyScope.DefineTypeAndMembers(); Assert.AreEqual(1, proxyScope.ConstructorFields.Length); Assert.AreEqual("__interceptors", proxyScope.ConstructorFields[0].Name); Assert.AreEqual(1, proxyScope.Fields.Count); Assert.AreEqual("__interceptors", proxyScope.Fields[0].Name); var field = proxyScope.DefineField("A", typeof(string), FieldAttributes.Private); Assert.AreEqual(1, proxyScope.ConstructorFields.Length); Assert.AreEqual(2, proxyScope.Fields.Count); Assert.AreEqual("A", proxyScope.Fields[1].Name); Assert.AreEqual(field, proxyScope.Fields[1]); }
private static void RunCompleteSample(ProxyGenerator generator) { Console.WriteLine("---------------------- Property, method, event ----------------------"); var proxy = generator.CreateClassProxy <MyClass>(); // property proxy.MyProperty = "New value"; Console.WriteLine($"Property: '{proxy.MyProperty}'"); // method proxy.MyMethod("A"); Console.WriteLine($"Property: '{proxy.MyProperty}'"); // event EventHandler handler = null; handler = (s, e) => { Console.WriteLine("Event raised"); }; proxy.MyEvent += handler; proxy.MyEvent -= handler; }
public void TestIfItFailsWhenItCantFindEquivalent() { // Arrange var generator = new ProxyGenerator(); InterfaceMap map = new InterfaceMap() { Subject = new Properties() }; MatchingInterceptor <IMoreProperties> interceptor; IMoreProperties proxy; // Act interceptor = new MatchingInterceptor <IMoreProperties>(map); proxy = generator.CreateInterfaceProxyWithoutTarget <IMoreProperties>(interceptor); Func <int> getter = () => { return(proxy.ExtraGetProperty); }; // Assert Verify.That(proxy).IsNotNull().Now(); Verify.That(getter).ThrowsException("The property ExtraProperty should fail to be found!"); }
public void Methods_With_Mutliple_Signatures() { var proxyGenerator = new ProxyGenerator(); var proxy = proxyGenerator.CreateClassProxy <MyClassMultiSignatures>(new InterceptorPrivate1()); Assert.AreEqual(0, MyClassMultiSignatures.States.Count); proxy.Method(); Assert.AreEqual(3, MyClassMultiSignatures.States.Count); Assert.AreEqual(StateTypes.Interceptor1_IsCalledBefore, MyClassMultiSignatures.States[0]); Assert.AreEqual(StateTypes.Class_Method, MyClassMultiSignatures.States[1]); Assert.AreEqual(StateTypes.Interceptor1_IsCalledAfter, MyClassMultiSignatures.States[2]); MyClassMultiSignatures.States.Clear(); proxy.Method("A"); Assert.AreEqual(3, MyClassMultiSignatures.States.Count); Assert.AreEqual(StateTypes.Interceptor1_IsCalledBefore, MyClassMultiSignatures.States[0]); Assert.AreEqual(StateTypes.Class_Method_2, MyClassMultiSignatures.States[1]); Assert.AreEqual(StateTypes.Interceptor1_IsCalledAfter, MyClassMultiSignatures.States[2]); }
public Action <IServiceCollection> InnerCreateInterceptedWiring() { var func = new Func <IServiceProvider, TService>( sp => { var implementation = sp.GetService <TImplementation>(); var interceptors = _interceptorTypes.Select(it => sp.GetService(it) as IInterceptor).ToArray(); var intercepted = new ProxyGenerator().CreateInterfaceProxyWithTarget(typeof(TService), implementation, interceptors); return(intercepted as TService); } ); return(new Action <IServiceCollection>( sc => { switch (Scope) { case Scope.Scoped: sc.AddScoped <TImplementation>(); sc.AddScoped <TService>(func); break; case Scope.Singleton: sc.AddSingleton <TImplementation>(); sc.AddSingleton <TService>(func); break; case Scope.Transient: sc.AddTransient <TImplementation>(); sc.AddTransient <TService>(func); break; default: throw new ArgumentException($"Scope {Scope} not known."); } } )); }
public void Test__CacheSync() { var proxyGenerator = new ProxyGenerator(); var called = false; var fooMock = new Mock <IFoo>(); fooMock .Setup(x => x.Handle(It.IsAny <string>())) .Returns((string x) => x) .Callback((string _) => called = !called); var cachedFoo = CacheInterceptorBuilder.New <IFoo>() .WithProxyGenerator(proxyGenerator) .WithDefaultStore() .WithDefaultInvocationTypeResolver() .Build(fooMock.Object); cachedFoo.Handle("Hello world!"); cachedFoo.Handle("Hello world!"); Assert.True(called); }