/// <summary> /// Build a proxy using the Castle.DynamicProxy library. /// </summary> /// <param name="id">The value for the Id.</param> /// <param name="session">The Session the proxy is in.</param> /// <returns>A fully built <c>INHibernateProxy</c>.</returns> public INHibernateProxy GetProxy(object id, ISessionImplementor session) { try { CastleLazyInitializer initializer = new CastleLazyInitializer(_persistentClass, id, _getIdentifierMethod, _setIdentifierMethod, session); object generatedProxy = null; if (IsClassProxy) { generatedProxy = _proxyGenerator.CreateClassProxy(_persistentClass, _interfaces, initializer, false); } else { generatedProxy = _proxyGenerator.CreateProxy(_interfaces, initializer, new object()); } initializer._constructed = true; return(( INHibernateProxy )generatedProxy); } catch (Exception e) { log.Error("Creating a proxy instance failed", e); throw new HibernateException("Creating a proxy instance failed", e); } }
/// <summary> /// /// </summary> /// <param name="dao"></param> /// <returns></returns> public static IDao NewInstance(Dao dao) { ProxyGenerator proxyGenerator = new ProxyGenerator(); IInterceptor handler = new DaoProxy(dao); Type[] interfaces = { dao.DaoInterface, typeof(IDao) }; return(proxyGenerator.CreateProxy(interfaces, handler, dao.DaoInstance) as IDao); }
public void ProxyGenericInterfaceWithTwoGenericParameters() { IDictionary <int, float> ints = new Dictionary <int, float>(); ProxyGenerator pg = new ProxyGenerator(); IDictionary <int, float> x = (IDictionary <int, float>)pg.CreateProxy(typeof(IDictionary <int, float>), new StandardInterceptor(), ints); Assert.AreEqual(0, x.Count); }
public void ProxyGenericInterface() { List <int> ints = new List <int>(); ProxyGenerator pg = new ProxyGenerator(); IList <int> x = (IList <int>)pg.CreateProxy(typeof(IList <int>), new StandardInterceptor(), ints); Assert.AreEqual(0, x.Count); }
public void TestMethod01() { var objTarget = new MockTarget(); var objProxy = ProxyGenerator.CreateProxy(objTarget) as MockTarget; Assert.IsNotNull(objProxy); Assert.AreEqual("Intercepted", objProxy.GetString(1, true, "3")); }
public void TestMethod02() { var objTarget = new MockTarget(); var objProxy = ProxyGenerator.CreateProxy(objTarget) as MockTarget; Assert.IsNotNull(objProxy); Assert.AreEqual("A", objProxy.Get("A")); Assert.AreEqual(12, objProxy.Get(12)); }
public object CreateClass(bool isLazy, bool inferType, Type type, Item item) { if (item == null) { return(null); } SitecoreClassConfig config = null; if (!inferType) { //this retrieves the class based on return type config = InstanceContext.GetSitecoreClass(type); } else { //this retrieves the class by inferring the type from the template ID //if ths return type can not be found then the system will try to create a type //base on the return type config = InstanceContext.GetSitecoreClass(item.TemplateID.Guid, type); if (config == null) { config = InstanceContext.GetSitecoreClass(type); } } if (isLazy || type.IsInterface) { return(ProxyGenerator.CreateProxy(config, this, item, inferType)); } else { if (item == null) { return(null); } //get the class information if (config.CreateObject == null) { Type objType = config.Type; var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + objType.Name, objType, null, objType); ILGenerator ilGen = dynMethod.GetILGenerator(); ilGen.Emit(OpCodes.Newobj, objType.GetConstructor(Type.EmptyTypes)); ilGen.Emit(OpCodes.Ret); config.CreateObject = (SitecoreClassConfig.Instantiator)dynMethod.CreateDelegate(typeof(SitecoreClassConfig.Instantiator)); } object t = config.CreateObject(); ReadFromItem(t, item, config); return(t); } }
/// <summary> /// Static constructor /// </summary> /// <param name="connection">The connection which been proxified.</param> /// <param name="provider">The provider used</param> /// <returns>A proxy</returns> internal static IDbConnection NewInstance(IDbConnection connection, Provider provider) { object proxyConnection = null; IInterceptor handler = new IDbConnectionProxy(connection, provider); ProxyGenerator proxyGenerator = new ProxyGenerator(); proxyConnection = proxyGenerator.CreateProxy(typeof(IDbConnection), handler, connection); return((IDbConnection)proxyConnection); }
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 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); }
private Object CreateProxy(Type[] interfaces, IPicoContainer container) { try { ProxyGenerator proxyGenerator = new ProxyGenerator(); object componentInstance = Delegate.GetComponentInstance(container); return(proxyGenerator.CreateProxy(interfaces, new PicoInterceptor(), componentInstance)); } catch (ArgumentException e) { throw new PicoIntrospectionException("Error creating a dynamic proxy for implementation hiding", e); } }
private static IServiceFactory GenerateFactoryProxy() { ProxyGenerator generator = new ProxyGenerator(); ServiceInterceptor interceptor = new ServiceInterceptor(); IServiceFactory factory = new ServiceFactory(); foreach (FieldInfo field in factory.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic)) { object service = field.GetValue(factory); field.SetValue(factory, generator.CreateProxy(field.FieldType, interceptor, service)); } return(factory); }
public void Create_CreatesProxyClassAndCorrectlyReplaces() { //Assign Item item = _db.GetItem(new ID(_itemId)); SitecoreClassConfig config = _context.GetSitecoreClass(typeof(ProxyClassGeneratorFixtureNS.SubClass)); //Act var result = ProxyGenerator.CreateProxy(config, _service, item, false) as ProxyClassGeneratorFixtureNS.SubClass; result.CallMe = "something"; //Assert Assert.AreEqual("something", result.CallMe); }
public void TestGenerationSimpleInterface() { IInvocationHandler handler = new StandardInvocationHandler(new MyInterfaceImpl()); object proxy = ProxyGenerator.CreateProxy(typeof(IMyInterface), handler); Assert.IsNotNull(proxy); Assert.IsTrue(typeof(IMyInterface).IsAssignableFrom(proxy.GetType())); IMyInterface inter = (IMyInterface)proxy; Assert.AreEqual(45, inter.Calc(20, 25)); inter.Name = "opa"; Assert.AreEqual("opa", inter.Name); inter.Started = true; Assert.AreEqual(true, inter.Started); }
public virtual object CreateClass(ISitecoreService service, bool isLazy, bool inferType, Type type, Item item, params object[] constructorParameters) { //check there is an item to create a class from if (item == null) { return(null); } //check that there are some constructor arguments SitecoreClassConfig config = null; if (!inferType) { //this retrieves the class based on return type config = Context.StaticContext.GetSitecoreClass(type); } else { //this retrieves the class by inferring the type from the template ID //if ths return type can not be found then the system will try to create a type //base on the return type config = TypeInferrer.InferrerType(item, type); } //if the class should be lazy loaded or is an interface then load using a proxy if (isLazy || type.IsInterface) { return(ProxyGenerator.CreateProxy(config, service, item, inferType)); } else { ConstructorInfo constructor = config.Type.GetConstructor(constructorParameters == null || constructorParameters.Count() == 0 ? Type.EmptyTypes : constructorParameters.Select(x => x.GetType()).ToArray()); if (constructor == null) { throw new MapperException("No constructor for class {0} with parameters {1}".Formatted(config.Type.FullName, string.Join(",", constructorParameters.Select(x => x.GetType().FullName).ToArray()))); } Delegate conMethod = config.CreateObjectMethods[constructor]; object t = conMethod.DynamicInvoke(constructorParameters); ReadFromItem(service, t, item, config); return(t); } }
public void TestGenerationSimpleInterface() { object proxy = _generator.CreateProxy( typeof(IMyInterface), new ResultModifiedInvocationHandler(), new MyInterfaceImpl()); Assert.IsNotNull(proxy); Assert.IsTrue(typeof(IMyInterface).IsAssignableFrom(proxy.GetType())); IMyInterface inter = (IMyInterface)proxy; Assert.AreEqual(44, inter.Calc(20, 25)); inter.Name = "opa"; Assert.AreEqual("opa", inter.Name); inter.Started = true; Assert.AreEqual(true, inter.Started); }
public void SimpleInterfaceProxy() { ProxyObjectReference.ResetScope(); object proxy = generator.CreateProxy( typeof(IMyInterface), new StandardInterceptor( ), new MyInterfaceImpl()); Assert.IsTrue(proxy.GetType().IsSerializable); IMyInterface inter = (IMyInterface)proxy; inter.Name = "opa"; Assert.AreEqual("opa", inter.Name); inter.Started = true; Assert.AreEqual(true, inter.Started); IMyInterface otherProxy = (IMyInterface)SerializeAndDeserialize(proxy); Assert.AreEqual(inter.Name, otherProxy.Name); Assert.AreEqual(inter.Started, otherProxy.Started); }
public void TestGenerationWithInterfaceHeritage() { IInvocationHandler handler = new StandardInvocationHandler(new MySecondInterfaceImpl()); object proxy = ProxyGenerator.CreateProxy(typeof(IMySecondInterface), handler); Assert.IsNotNull(proxy); Assert.IsTrue(typeof(IMyInterface).IsAssignableFrom(proxy.GetType())); Assert.IsTrue(typeof(IMySecondInterface).IsAssignableFrom(proxy.GetType())); IMySecondInterface inter = (IMySecondInterface)proxy; inter.Calc(1, 1); inter.Name = "hammett"; Assert.AreEqual("hammett", inter.Name); inter.Address = "pereira leite, 44"; Assert.AreEqual("pereira leite, 44", inter.Address); Assert.AreEqual(45, inter.Calc(20, 25)); }
public static object Cast(Type destinationType, object source) { if (destinationType == null) { throw new ArgumentNullException("destinationType"); } if (source == null) { throw new ArgumentNullException("source"); } if (source.GetType().GetInterface(destinationType.Name) != null) { return(source); } var generator = new ProxyGenerator(); return(generator.CreateProxy(destinationType, new DelegatingInterceptor(source.GetType()), source)); }
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 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 CreateArgumentExpressions_ParametersNullValueGiven_ShouldThrowArgumentNullException() { var expressionBuilder = ProxyGenerator.CreateProxy <ExpressionBuilder>(); expressionBuilder.CreateArgumentExpressions(null, Value.Create <bool>(), ProxyGenerator.CreateProxy <ParameterInfo>()); }
public static T CreateTransparent <T>(T obj) where T : class => ProxyGenerator <T> .CreateProxy(ReflectionProxyHandler.Instance.BindObject(obj), ReflectionProxyHandler.Instance);
public void Constructor_MethodNullValueGiven_ShouldThrowArgumentNullException() { new MethodSourceCodeGenerationRequest(null, Value.Create <bool>(), ProxyGenerator.CreateProxy <ParameterInfo>(), Value.Create <bool>()); }
public void Constructor_IdentifierValidatorNullValueGiven_ShouldThrowArgumentNullException() { new ExpressionBuilder(ProxyGenerator.CreateProxy <ITestMethodValueProvider>(), ProxyGenerator.CreateProxy <IMockExpressionProvider>(), ProxyGenerator.CreateProxy <IValueExpressionProvider>(), null); }
public void Constructor_TestMethodValueProviderNullValueGiven_ShouldThrowArgumentNullException() { new NullArgumentMethodTestMethodSourceCodeGenerator(ProxyGenerator.CreateProxy <IExpressionBuilder>(), null); }
public void BuildMethodName_RequestNullValueGiven_ShouldThrowArgumentNullException() { var nullArgumentMethodTestMethodSourceCodeGenerator = ProxyGenerator.CreateProxy <NullArgumentMethodTestMethodSourceCodeGenerator>(); nullArgumentMethodTestMethodSourceCodeGenerator.BuildMethodName(null); }
/// <summary> /// Create a transparent proxy factory for the specified interface type, /// recommended if you plan on making multiple proxies of the same type, as they reuse the same handler. /// /// The provided handler generates DynamicMethods to speed up the invocation of methods on the object, and reusing the handler /// prevents the need to regenerate the code for each proxy /// </summary> /// <typeparam name="T">The interface type to create proxies for</typeparam> /// <returns>A function that creates transparent proxies implementing the specified type</returns> public static Func <T, T> CreateTransparentFactory <T>() where T : class { DynamicProxyHandler handler = new DynamicProxyHandler(); return(obj => ProxyGenerator <T> .CreateProxy(handler.BindObject(obj), handler)); }
/// <summary> /// Creates a transparent proxy, can only create proxies for interfaces. Any attempts to create proxies for classes will result in an exception /// </summary> /// <typeparam name="T">The interface type to create a proxy of</typeparam> /// <param name="obj">The object to create a proxy of</param> /// <param name="perms">The permissions to pass to the proxy object</param> /// <returns>A proxy object representing of the interfaces on the object.</returns> public static T CreateTransparent <T>(T obj) where T : class { DynamicProxyHandler handler = new DynamicProxyHandler(); return(ProxyGenerator <T> .CreateProxy(handler.BindObject(obj), handler)); }
public void CreateProxy_IFooTypeGiven_ShouldCreateInstanceOfIFoo() { var result = ProxyGenerator.CreateProxy <TestAssembly.IFoo>(); result.Should().NotBeNull(); }
public void CreateProxy_StringTypeGiven_ShouldThrowProxyGeneratorException() { ((Action)(() => ProxyGenerator.CreateProxy <string>())) .ShouldThrow <ProxyGeneratorException>(); }
public void CreateProxy_ListTypeGiven_ShouldCreateInstanceOfList() { var result = ProxyGenerator.CreateProxy <List <string> >(); result.Should().NotBeNull(); }