コード例 #1
0
        internal static void Check <T>(ProxyBuilder <T> proxyBuilder)
            where T : class, new()
        {
            PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            if (!properties.Any())
            {
                throw new ObjectCannotBeProxiedException("No public non-static properties available.");
            }

            if (properties.Any(x => (x.GetGetMethod() != null && !x.GetGetMethod().IsVirtual) ||
                               (x.GetSetMethod() != null && !x.GetSetMethod().IsVirtual)))
            {
                throw new ObjectCannotBeProxiedException("All public non-static properties must be declared as virtual.");
            }

            if (!IsSerializable(proxyBuilder.SourceReference))
            {
                throw new ObjectCannotBeProxiedException("Object is not serializable.");
            }

            if (proxyBuilder.Blueprint.Properties.Count != proxyBuilder.Blueprint.Properties.Select(x => x.Name).Distinct().Count())
            {
                throw new ObjectCannotBeProxiedException("You cannot declare two properties with the same name.");
            }
        }
コード例 #2
0
        public void TestReturn()
        {
            var p = (TestProxy)ProxyBuilder.GetProxyObject(typeof(TestProxy), new DebugProxyHandler());
            var r = p.TestReturn(1, 2);

            Assert.AreEqual(r, 3);
        }
コード例 #3
0
        public void BuildWithType()
        {
            this.Initialize();
            var generator = new AssemblyGenerator("BuildWithType", new Dictionary <string, ReadOnlyCollection <MethodGenerator> >()
            {
                { "Type1", new List <MethodGenerator>()
                  {
                      new MethodGenerator("Method1", true),
                      new MethodGenerator("Method2", false)
                  }.AsReadOnly() }
            });

            var assembly = generator.Generate();

            ProxyBuilder.Build(assembly.GetTypes()[0]);

            var proxyAssemblies = new HashSet <Assembly>();

            foreach (var type in assembly.GetTypes())
            {
                proxyAssemblies.Add(Activator.CreateInstance(type).CreateProxy(this).GetType().Assembly);
            }

            Assert.Equal(1, proxyAssemblies.Count);
        }
コード例 #4
0
 public void BuildWithNullContextOnCollection()
 {
     this.Initialize();
     Assert.Throws <ArgumentNullException>(() => ProxyBuilder.Build(new List <Type> {
         typeof(SimpleClass)
     }.AsReadOnly(), null));
 }
コード例 #5
0
        /// <summary>
        /// Start the type controller and build the type tree
        /// </summary>
        public void Start()
        {
            // Define module on first start
            ProxyBuilder.PrepareBuilder();

            BuildTypeTree();
        }
コード例 #6
0
 public void BuildWithCollectionThatImplementsIProxy()
 {
     this.Initialize();
     Assert.Throws <ArgumentException>(() => ProxyBuilder.Build(new List <Type> {
         typeof(BadProxyClassWithCorrectTarget)
     }.AsReadOnly()));
 }
コード例 #7
0
        public static T CreateProxy <T>(this ProxyDefinition definition)
        {
            var builder   = new ProxyBuilder();
            var proxyType = builder.GetProxyType(definition);

            return((T)Activator.CreateInstance(proxyType));
        }
コード例 #8
0
        private static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                ProfileToGenerate = args[0];
            }

            var profileDirectory = Path.Combine(ProfileDirectory, ProfileToGenerate);

            Console.WriteLine(string.Join(Environment.NewLine, new[] {
                "This program Copyright (C) 2009 Eugeny Grishul",
                "This program comes with ABSOLUTELY NO WARRANTY",
                "This is free software, and you are welcome to redistribute it under certain conditions",
                "", ""
            }));

            if (!Directory.Exists(profileDirectory))
            {
                Console.WriteLine("Profile directory {0} not exists!", profileDirectory);
                return;
            }

            RuntimeDumper.LoadSettings(ProfileToGenerate);

            if (ProfileToGenerate == RuntimeDumper.NativeProfile)
            {
                RuntimeDumper.Dump(ProfileToGenerate);
            }

            //HeaderAnalyzer.Analyze( ProfileToGenerate );

            ProxyBuilder.GenerateProfile(ProfileToGenerate);
        }
コード例 #9
0
        public void EventEvaluationTest()
        {
            var mockInvoker = new Mock <IInvoker>();

            mockInvoker.Setup(mock => mock.Invoke(It.Is <MethodInfo>(m => m == typeof(IEventInterface).GetMethod("add_ValueEvent")), It.Is <object[]>(p => p.Length == 1 && p[0] is Func <int, int>)))
            .Verifiable();
            mockInvoker.Setup(mock => mock.Invoke(It.Is <MethodInfo>(m => m == typeof(IEventInterface).GetMethod("remove_ValueEvent")), It.Is <object[]>(p => p.Length == 1 && p[0] is Func <int, int>)))
            .Verifiable();
            mockInvoker.Setup(mock => mock.Invoke(It.Is <MethodInfo>(m => m == typeof(IEventInterface).GetMethod("add_ReferenceEvent")), It.Is <object[]>(p => p.Length == 1 && p[0] is Func <object, object>)))
            .Verifiable();
            mockInvoker.Setup(mock => mock.Invoke(It.Is <MethodInfo>(m => m == typeof(IEventInterface).GetMethod("remove_ReferenceEvent")), It.Is <object[]>(p => p.Length == 1 && p[0] is Func <object, object>)))
            .Verifiable();
            mockInvoker.Setup(mock => mock.Invoke(It.Is <MethodInfo>(m => m == typeof(IEventInterface).GetMethod("add_VoidEvent")), It.Is <object[]>(p => p.Length == 1 && p[0] is Action)))
            .Verifiable();
            mockInvoker.Setup(mock => mock.Invoke(It.Is <MethodInfo>(m => m == typeof(IEventInterface).GetMethod("remove_VoidEvent")), It.Is <object[]>(p => p.Length == 1 && p[0] is Action)))
            .Verifiable();
            var invoker = mockInvoker.Object;

            var proxy = ProxyBuilder.Create <IEventInterface>(invoker.Invoke);

            proxy.ValueEvent     += ValueMethod;
            proxy.ValueEvent     -= ValueMethod;
            proxy.ReferenceEvent += ReferenceMethod;
            proxy.ReferenceEvent -= ReferenceMethod;
            proxy.VoidEvent      += VoidMethod;
            proxy.VoidEvent      -= VoidMethod;

            mockInvoker.Verify();
        }
コード例 #10
0
        /// <summary>
        /// Make sure the <see cref="_proxyTypeCache"/> contains an entry for the given type
        /// </summary>
        private void ProvideProxyType(Type resourceType)
        {
            // Step 1: Find the least specific base type that offers the same amount of interfaces
            // ReSharper disable once AssignNullToNotNullAttribute -> FullName should be not null
            var targetType = _typeCache[resourceType.ResourceType()];
            var linker     = targetType;

            var interfaces = RelevantInterfaces(linker);

            // Move up the type tree until the parent offers less interfaces than the current linker
            while (linker.BaseType != null && interfaces.Count == RelevantInterfaces(linker.BaseType).Count)
            {
                linker = linker.BaseType;
            }

            // Step 2: Check if we already created a proxy for this type. If we already
            // did use this one for the requested type as well.
            if (_proxyTypeCache.ContainsKey(linker.Name))
            {
                _proxyTypeCache[targetType.Name] = _proxyTypeCache[linker.Name];
                return;
            }

            // Step 3: Build a proxy type for the least specific base type
            var proxyType = ProxyBuilder.Build(linker.ResourceType, interfaces);

            // Step 4: Assign the new proxy type to all derived types from the
            // match to the originally requested one
            _proxyTypeCache[linker.Name] = proxyType.ResourceType();
            while (targetType != null && targetType != linker)
            {
                _proxyTypeCache[targetType.Name] = proxyType.ResourceType();
                targetType = targetType.BaseType;
            }
        }
コード例 #11
0
        public Type CreateInterfaceProxy(Type @interface)
        {
            if ([email protected])
            {
                throw new ArgumentException($"InterfaceType_Must_Be_Interface, {@interface.FullName}", "T");
            }
            TypeBuilder  builder      = this._moduleBuilder.DefineType($"{@interface.Name}_Proxy", TypeAttributes.Public, typeof(object), new Type[] { @interface, typeof(IProxy) });
            ProxyBuilder proxyBuilder = new ProxyBuilder(builder, @interface);

            proxyBuilder.DefineClassConstructor();

            proxyBuilder.DefineProxyMethod();

            foreach (var method in @interface.GetMethods().Where(method => !method.IsSpecialName))
            {
                proxyBuilder.DefineInterceptorMethod(method);
            }

            foreach (var property in @interface.GetProperties())
            {
                proxyBuilder.DefineProperty(property);
            }

            return(builder.CreateTypeInfo());
        }
コード例 #12
0
        public void ProductsAreNotNull(string url)
        {
            FoxtrotParser rpd    = new FoxtrotParser();
            List <String> proxys = new ProxyBuilder().GenerateProxy().Build();

            Assert.NotNull(rpd.GetProduct(url, ref proxys));
        }
コード例 #13
0
        public override void Serialize(IDatabaseSettings settings, EntitySerializer serializer, Relation rel, object instanceEntity, PropertyAccessor pInfo, EntityMap entityMap, EntityAccessor entityAccessor, DbDataReader dbReader)
        {
            var relMap  = settings.Map.GetEntityMap(rel.ReferenceEntityName);
            var relCols = new List <string>();
            var session = serializer.SessionCreator();

            int iteration = 0;
            int recursion = 0;

            var relQueryMap = new TableQueryMap(relMap.FullName, ref recursion, ref iteration);

            QueryBuilder q = new QueryBuilder(session, relCols);

            relQueryMap.LoadColumns(relMap, session, q, relCols);
            var prop = entityMap.FirstOrDefault(c => c.ColumnName == rel.ColumnName);

            if (prop == null)
            {
                throw new GoliathDataException(string.Format("{0}: Reference {1} does not have matching property.", entityMap.FullName, rel.PropertyName));
            }

            var valAccessor = entityAccessor.GetPropertyAccessor(prop.PropertyName);
            var val         = valAccessor.GetMethod(instanceEntity);

            var queryBuilder = q.From(relMap.TableName, relQueryMap.Prefix)
                               .Where(rel.ReferenceColumn).EqualToValue(val);

            IProxyHydrator hydrator = new ProxyHydrator(queryBuilder as QueryBuilder, pInfo.PropertyType, relMap, serializer, session);

            ProxyBuilder pbuilder  = new ProxyBuilder();
            var          proxyType = pbuilder.CreateProxyType(pInfo.PropertyType, relMap);
            object       proxyobj  = Activator.CreateInstance(proxyType, new object[] { pInfo.PropertyType, hydrator });

            pInfo.SetMethod(instanceEntity, proxyobj);
        }
コード例 #14
0
        public static void Intercept(this IRegistrator registrator,
                                     Type serviceType, ParameterSelector interceptorsParameterSelector, object serviceKey = null)
        {
            Type proxyType;

            if (serviceType.IsInterface())
            {
                proxyType = ProxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else if (serviceType.IsClass())
            {
                proxyType = ProxyBuilder.CreateClassProxyTypeWithTarget(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else
            {
                throw new ArgumentException(
                          $"Intercepted service type {serviceType} is not a supported, cause it is nor a class nor an interface");
            }

            registrator.Register(serviceType, proxyType,
                                 made: Made.Of(
                                     pt => pt.PublicConstructors().FindFirst(ctor => ctor.GetParameters().Length != 0),
                                     interceptorsParameterSelector),
                                 setup: Setup.DecoratorOf(useDecorateeReuse: true, decorateeServiceKey: serviceKey));
        }
コード例 #15
0
        private static void Main(string[] args)
        {
            // Web Service Proxy
            var webServiceAssembly = typeof(SportsWebService.Global).Assembly;

            foreach (var definedType in webServiceAssembly.DefinedTypes)
            {
                var attrData = definedType.CustomAttributes.Where(elem => elem.AttributeType.Name.Equals("ServiceContractAttribute")).FirstOrDefault();
                if (attrData != null)
                {
                    string       serviceName  = (string)attrData.NamedArguments[0].TypedValue.Value;
                    ProxyBuilder proxyBuilder = new ProxyBuilder(definedType, serviceName, "PosePacket.Proxy");
                    proxyBuilder.AddFields();
                    proxyBuilder.AddProperties();
                    proxyBuilder.GenerateCSharpCode();
                }
            }

            // ErrorCode Message
            ErrorCodeDescriptionBuilder errorCodeBuilder = new ErrorCodeDescriptionBuilder(webServiceAssembly);

            errorCodeBuilder.ParseErrorCode();
            errorCodeBuilder.GenerateJsonFile();

            Console.WriteLine("Complete!!!");
            Console.ReadLine();
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: zhyzhy782/ClownFish.net
        private static void Execute(string entityDllFile)
        {
            string currentPath = Path.GetDirectoryName(entityDllFile);

            if (string.IsNullOrEmpty(currentPath))
            {
                currentPath = AppDomain.CurrentDomain.BaseDirectory;
            }


            string newName = Path.GetFileNameWithoutExtension(entityDllFile) + ".EntityProxy.dll";
            string outFile = Path.Combine(currentPath, newName);

            if (File.Exists(outFile))
            {
                File.Delete(outFile);
            }

            // 设置当前路径
            Environment.CurrentDirectory = currentPath;

            Assembly asm = Assembly.LoadFile(entityDllFile);

            Type[] entityTypes = ProxyBuilder.GetAssemblyEntityTypes(asm);

            ProxyBuilder.Compile(entityTypes, outFile);
        }
コード例 #17
0
        /// <summary>
        /// Generates a proxy implementing all the specified interfaces and
        /// redirecting method invocations to the specifed interceptor.
        /// </summary>
        /// <param name="interfaces">Array of interfaces to be implemented</param>
        /// <param name="interceptor">instance of <see cref="IInterceptor"/></param>
        /// <param name="target">The target object.</param>
        /// <returns>Proxy instance</returns>
        public override object CreateProxy(Type[] interfaces, IInterceptor interceptor, object target)
        {
            try
            {
                System.Type proxyType  = null;
                System.Type targetType = target.GetType();

                lock (_cachedProxyTypes.SyncRoot)
                {
                    proxyType = _cachedProxyTypes[targetType] as System.Type;

                    if (proxyType == null)
                    {
                        proxyType = ProxyBuilder.CreateInterfaceProxy(interfaces, targetType);
                        _cachedProxyTypes[targetType] = proxyType;
                    }
                }
                return(base.CreateProxyInstance(proxyType, interceptor, target));
            }
            catch (Exception e)
            {
                _log.Error("Castle Dynamic Proxy Generator failed", e);
                throw new IBatisException("Castle Proxy Generator failed", e);
            }
        }
コード例 #18
0
        /// <summary>
        /// oxana
        /// Returns a new instance for a client proxy over the specified interface with the specified config name used for initialization. And callback!!
        /// This instance of the proxy can be reused as it will always "clean" itself
        /// if the dual channel is faulted.
        /// The class will also unwrap any FaultException and throw the original Exception.
        /// </summary>
        public static TInterface GetReusableFaultUnwrappingInstance2(object callbackObject, string configName)
        {
            TInterface pooledInstance = ProxyConnectionPool.RequestFromPool <TInterface>();

            if (pooledInstance != null)
            {
                return(pooledInstance);
            }

            if (_reusableFaultUnwrappingInstance == null)
            {
                // no need to lock as the ProxyBuilder is thread safe and will always return the same stuff
                // Build the type
                _reusableFaultUnwrappingInstance = ProxyBuilder.BuildType <TInterface, WCFReusableFaultWrapperProxyClassBuilder <TInterface> >();
            }

            // Create new instance
            //TInterface instance = (TInterface)Activator.CreateInstance(_reusableFaultUnwrappingInstance, new object[] { (InstanceContext)callbackObject, configName });
            TInterface instance = (TInterface)Activator.CreateInstance(_reusableFaultUnwrappingInstance, new object[] { configName });

            //((DuplexClientRuntimeChannel)instance).CallbackInstance = callbackObject;



            ProxyConnectionPool.Register(instance);

            return(instance);
        }
コード例 #19
0
        /// <summary>
        /// Intercept interface or abstract
        /// </summary>
        /// <typeparam name="TService"></typeparam>
        /// <typeparam name="TInterceptor"></typeparam>
        /// <param name="block"></param>
        /// <returns></returns>
        public static IFluentDecoratorStrategyConfiguration Intercept <TService, TInterceptor>(
            this IExportRegistrationBlock block) where TInterceptor : IInterceptor
        {
            Type decoratorType;

            var tService = typeof(TService);

            if (tService.GetTypeInfo().IsInterface)
            {
                decoratorType = ProxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(tService, new Type[0],
                                                                                         ProxyGenerationOptions.Default);
            }
            else if (tService.GetTypeInfo().IsClass)
            {
                decoratorType = ProxyBuilder.CreateClassProxyTypeWithTarget(tService, new Type[0],
                                                                            ProxyGenerationOptions.Default);
            }
            else
            {
                throw new Exception("Service type must be interface or class");
            }

            return
                (block.ExportDecorator(decoratorType)
                 .As(tService)
                 .WithCtorParam <TInterceptor, IInterceptor[]>(i => new IInterceptor[] { i }));
        }
コード例 #20
0
        /// <summary>
        /// Returns the type of class that represents a proxy over the specified interface with the specified config name used for initialization.
        /// This is a simple instance of a ClientBase derived class.
        /// </summary>
        public static Type GetInstanceType()
        {
            // Build the type
            Type type = ProxyBuilder.BuildType <TInterface, WCFProxyClassBuilder <TInterface> >();

            return(type);
        }
コード例 #21
0
        public Type CreateInterfaceProxy(Type @interface)
        {
            if ([email protected])
            {
                throw new ArgumentException($"InterfaceType_Must_Be_Interface, {@interface.FullName}", "T");
            }
            var          attributes   = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final;
            TypeBuilder  builder      = this._moduleBuilder.DefineType($"{@interface.Name}_Proxy", TypeAttributes.Public, typeof(object), new Type[] { @interface });
            ProxyBuilder proxyBuilder = new ProxyBuilder(builder, @interface);

            proxyBuilder.DefineClassConstructor();
            foreach (var method in @interface.GetMethods().Where(method => !method.IsSpecialName))
            {
                proxyBuilder.DefineInterceptorMethod(method, attributes);
            }
            foreach (var property in @interface.GetProperties())
            {
                var parameterTypes  = property.GetIndexParameters().Select(it => it.ParameterType).ToArray();
                var propertyBuilder = builder.DefineProperty(property.Name, property.Attributes, property.PropertyType, parameterTypes);
                var getMethod       = property.GetMethod;
                if (null != getMethod)
                {
                    propertyBuilder.SetGetMethod(proxyBuilder.DefineInterceptorMethod(getMethod, attributes));
                }
                var setMethod = property.SetMethod;
                if (null != setMethod)
                {
                    propertyBuilder.SetSetMethod(proxyBuilder.DefineInterceptorMethod(setMethod, attributes));
                }
            }
            return(builder.CreateTypeInfo());
        }
コード例 #22
0
        public Type CreateClassProxy(Type @class)
        {
            if (@class.IsSealed)
            {
                throw new ArgumentException($"BaseType_Cannot_Be_Sealed, {@class.FullName}", "TProxy");
            }
            var          builder      = _moduleBuilder.DefineType($"{@class.Name}_Proxy", TypeAttributes.Public | TypeAttributes.Sealed, @class, new Type[] { typeof(IProxy) });
            ProxyBuilder proxyBuilder = new ProxyBuilder(builder, @class);

            proxyBuilder.DefineSubClassConstructor();

            proxyBuilder.DefineProxyMethod();

            foreach (var methodInfo in @class.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(method => method.DeclaringType != typeof(object)))
            {
                if (!methodInfo.IsSpecialName && !methodInfo.IsFinal && methodInfo.IsVirtual)
                {
                    proxyBuilder.DefineInterceptorMethod(methodInfo);
                }
            }

            foreach (var property in @class.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.GetProperty))
            {
                proxyBuilder.DefineProperty(property);
            }

            return(builder.CreateTypeInfo());
        }
コード例 #23
0
        public void ProductAreNotNull()
        {
            ComfyParser   cp     = new ComfyParser();
            List <String> proxys = new ProxyBuilder().GenerateProxy().Build();

            Assert.NotNull(cp.GetProduct("https://comfy.ua/stiral-naja-mashina-lg-fh0b8nd1.html", ref proxys));
        }
コード例 #24
0
        public void Test_生成实体代理类程序集()
        {
            Type[] entityTypes = new Type[] { typeof(Product), typeof(Customer) };
            string dllFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test.EntityProxy.dll");

            if (File.Exists(dllFilePath))
            {
                File.Delete(dllFilePath);
            }

            var result = ProxyBuilder.Compile(entityTypes, dllFilePath);

            Assert.IsTrue(File.Exists(dllFilePath));

            // 加载程序集并确认结果
            Assembly asm = Assembly.LoadFrom(dllFilePath);

            Type[] types = asm.GetExportedTypes();

            var t1 = (from x in types
                      where x.Name.StartsWith("Customer_") && x.Name.EndsWith("_Loader")
                      select x).First();

            var t2 = (from x in types
                      where x.Name.StartsWith("Customer_") && x.Name.EndsWith("_Proxy")
                      select x).First();

            var t3 = (from x in types
                      where x.Name.StartsWith("Product_") && x.Name.EndsWith("_Loader")
                      select x).First();

            var t4 = (from x in types
                      where x.Name.StartsWith("Product_") && x.Name.EndsWith("_Proxy")
                      select x).First();
        }
コード例 #25
0
        private static void Execute(string dllFile, Assembly asm = null)
        {
            string currentPath = Path.GetDirectoryName(dllFile);

            string newName = Path.GetFileNameWithoutExtension(dllFile) + ".EntityProxy.dll";
            string outFile = Path.Combine(currentPath, newName);

            if (File.Exists(outFile))
            {
                File.Delete(outFile);
            }

            if (asm == null)
            {
                asm = Assembly.LoadFrom(dllFile);
            }

            Type[] entityTypes = ProxyBuilder.GetAssemblyEntityTypes(asm);
            if (entityTypes == null || entityTypes.Length == 0)
            {
                return;
            }

            ProxyBuilder.Compile(entityTypes, outFile);

            Console.WriteLine("成功生成实体代理程序集:" + outFile);
        }
コード例 #26
0
ファイル: DryIocInterception.cs プロジェクト: rootzhou/DryIoc
        public static void Intercept <TService, TInterceptor>(this IRegistrator registrator, object serviceKey = null)
            where TInterceptor : class, IInterceptor
        {
            var serviceType = typeof(TService);

            Type proxyType;

            if (serviceType.IsInterface())
            {
                proxyType = ProxyBuilder.CreateInterfaceProxyTypeWithTargetInterface(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else if (serviceType.IsClass())
            {
                proxyType = ProxyBuilder.CreateClassProxyType(
                    serviceType, ArrayTools.Empty <Type>(), ProxyGenerationOptions.Default);
            }
            else
            {
                throw new ArgumentException(string.Format(
                                                "Intercepted service type {0} is not a supported: it is nor class nor interface", serviceType));
            }

            var decoratorSetup = serviceKey == null
                ? Setup.DecoratorWith(useDecorateeReuse : true)
                : Setup.DecoratorWith(r => serviceKey.Equals(r.ServiceKey), useDecorateeReuse: true);

            registrator.Register(serviceType, proxyType,
                                 made: Made.Of(type => type.PublicConstructors().SingleOrDefault(c => c.GetParameters().Length != 0),
                                               Parameters.Of.Type <IInterceptor[]>(typeof(TInterceptor[]))),
                                 setup: decoratorSetup);
        }
コード例 #27
0
		public void SetPropertyWithNoPropertyChangedSubscriptionNotThrowException()
		{
			var customer = new ProxyBuilder().MakeNotifyPropertyChanged<Customer>();

			Executing
				.This(() => customer.Name = KnownName)
				.Should().NotThrow();
		}
コード例 #28
0
        /// <summary>
        /// Gets a proxy type that implements the <paramref name="serviceType"/>.
        /// </summary>
        /// <param name="serviceType">The type of service for which to create a service proxy type.</param>
        /// <returns>A proxy type that implements the <paramref name="serviceType"/>.</returns>
        public Type GetProxyType(Type serviceType)
        {
            var proxyDefinition = CreateProxyDefinition(serviceType);

            IProxyBuilder proxyBuilder = new ProxyBuilder();

            return(proxyBuilder.GetProxyType(proxyDefinition));
        }
コード例 #29
0
        public void GivenClassToProxyWithNoProperties_WhenBuildingProxy_ReturnAnNSubstituteProxyOfThatClass()
        {
            var proxyBuilder = new ProxyBuilder<Customer>(new Dictionary<string, Func<object>>());

            var proxy = proxyBuilder.Build();

            proxy.DidNotReceive().CustomerForHowManyYears(Arg.Any<DateTime>());
        }
コード例 #30
0
        public void GivenClassToProxyWithNoProperties_WhenBuildingProxy_ReturnAnNSubstituteProxyOfThatClass()
        {
            var proxyBuilder = new ProxyBuilder <Customer>(new Dictionary <string, Func <object> >());

            var proxy = proxyBuilder.Build();

            proxy.DidNotReceive().CustomerForHowManyYears(Arg.Any <DateTime>());
        }
コード例 #31
0
        private static Type CreateServiceProxyType(Type serviceType)
        {
            var proxyBuilder    = new ProxyBuilder();
            var proxyDefinition = CreateProxyDefinition(serviceType);

            ImplementServiceInterface(serviceType, proxyDefinition);
            return(proxyBuilder.GetProxyType(proxyDefinition));
        }
コード例 #32
0
        /// <summary>
        /// Instantiate proxy object for a given resource type name
        /// </summary>
        private ResourceProxy InstantiateProxy(string typeName, Resource instance)
        {
            var proxyType     = ProxyBuilder.GetType(_proxyTypeCache[typeName]);
            var proxyInstance = (ResourceProxy)Activator.CreateInstance(proxyType, instance, this);

            proxyInstance.Attach();
            return(proxyInstance);
        }
 internal override IProxyBuilder CreateProxyBuilder()
 {
     var proxyBuilder = new ProxyBuilder();
     var field = typeof(ProxyBuilder).GetField(
         "typeBuilderFactory", BindingFlags.Instance | BindingFlags.NonPublic);
     field.SetValue(proxyBuilder, new VerifiableTypeBuilderFactory());
     return proxyBuilder;
 }
コード例 #34
0
        public void GivenClassToProxyWithNoProperties_WhenBuildingProxy_ReturnAClassWithNoReturnsValuesSet()
        {
            var proxyBuilder = new ProxyBuilder<Customer>(new Dictionary<string, Func<object>>());

            var proxy = proxyBuilder.Build();

            proxy.FirstName.ShouldBe(string.Empty);
            proxy.LastName.ShouldBe(string.Empty);
            proxy.YearJoined.ShouldBe(0);
        }
コード例 #35
0
 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>());
 }
コード例 #36
0
        public void GivenClassToProxyWithSinglePropertyValue_WhenBuildingProxy_ReturnAClassWithReturnValueSetFromFunction()
        {
            int nonce = new Random().Next(0, 100);
            var proxyBuilder = new ProxyBuilder<Customer>(new Dictionary<string, Func<object>> {{"FirstName", () => "FirstName" + nonce}});

            var proxy = proxyBuilder.Build();

            proxy.FirstName.ShouldBe("FirstName" + nonce);
            proxy.LastName.ShouldBe(string.Empty);
            proxy.YearJoined.ShouldBe(0);
        }
        /// <summary>
        /// Erstellen eines einfachen HREF Links für window.location.href
        /// </summary>
        public string BuildHrefLink(ProxyMethodInfos methodInfo, ProxyBuilder proxyBuilder)
        {
            //z.B.: window.location.href = window.siteRoot + 'Auftragsabrechnung/ExportData' + '?allEntries=' + encodeURIComponent(allEntries) + '&' + jQuery.param($scope.FilterData);
            //Wir bauen hier aber nur den Link Teil zusammen: 'Auftragsabrechnung/ExportData' + '?allEntries=' + encodeURIComponent(allEntries) + '&' + jQuery.param($scope.FilterData);

            StringBuilder builder = new StringBuilder();
            builder.Append(string.Format("'{0}/{1}'", ProxyBuilderHelper.GetClearControllerName(methodInfo.Controller), methodInfo.MethodInfo.Name));
            builder.Append(ProxyBuilderHelper.BuildUrlParameterId(methodInfo.ProxyMethodParameterInfos));
            //Da wir die Komplexen Parameter nicht als Post mit übergeben können bei einem Link, müssen wird diese entsprechend in Url Parametern abbilden.
            builder.Append(ProxyBuilderHelper.BuildComplexUrlParameter(methodInfo.ProxyMethodParameterInfos));
            return builder.ToString();
        }
コード例 #38
0
        public void GivenClassWithSomeVirtualProperties_WhenBuildingProxy_ThenOnlyVirtualMembersAreProxied()
        {
            var proxyBuilder = new ProxyBuilder<Company>(new Dictionary<string, Func<object>>()
            {
                {"Name", () => "Vandelay Industries"},
                {"EmployeeCount", () => 100}
            });

            var proxy = proxyBuilder.Build();

            proxy.Name.ShouldBe("Vandelay Industries");
            proxy.EmployeeCount.ShouldBe(0);
        }
コード例 #39
0
		public void SetPropertyAndCheckPropertyChangedEventIsRaised()
		{
			var customer =
				new ProxyBuilder()
					.MakeNotifyPropertyChanged<Customer>();

			var propertyChangedRaised = false;

			customer.PropertyChanged += (s, e) => { CheckPropertyChanged(s, e); propertyChangedRaised = true; };
			customer.Name = KnownName;

			propertyChangedRaised
				.Should()
				.Be
				.True();
		}
コード例 #40
0
        public void GivenClassToProxyWithMultiplePropertyValues_WhenBuildingProxy_ReturnAClassWithReturnValueSet()
        {
            var proxyBuilder = new ProxyBuilder<Customer>(new Dictionary<string, Func<object>>
                {
                    { "FirstName", () => "FirstName" },
                    { "LastName", () => "LastName" },
                    { "YearJoined", () => 1 },
                }
            );

            var proxy = proxyBuilder.Build();

            proxy.FirstName.ShouldBe("FirstName");
            proxy.LastName.ShouldBe("LastName");
            proxy.YearJoined.ShouldBe(1);
        }
コード例 #41
0
ファイル: ProxyTest.cs プロジェクト: Reen/protobuf-remote
        public void Init()
        {
            proxyBuilder = new ProxyBuilder();
            client = new Mock<RpcClient>(new Mock<RpcController>().Object);

            Type proxyType = proxyBuilder.Build(typeof(ISampleService));
            service = (ISampleService)Activator.CreateInstance(proxyType, client.Object);

            pendingCall = new PendingCall(0, null, null, null, null);
            resultMessage = new RpcMessage.Result();
            resultMessage.CallResult = new RpcMessage.Parameter();
            pendingCall.ReceiveResult(resultMessage);

            client.Setup(c => c.Call(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<RpcMessage.Parameter[]>(),
                It.IsAny<AsyncCallback>(), It.IsAny<object>()))
                .Returns(pendingCall);
        }
コード例 #42
0
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            if (serviceType == null)
                throw new ArgumentNullException("serviceType");

            var attribute = serviceType.GetCustomAttributes(typeof(ServiceContractAttribute), true)
                                       .Cast<ServiceContractAttribute>()
                                       .FirstOrDefault();

            if (!serviceType.IsInterface || attribute == null)
                throw new NotSupportedException("Only interfaces with [ServiceContract] attribute are supported with LightInjectServiceHostFactory.");

            var container = new ServiceContainer();
            var proxyBuilder = new ProxyBuilder();
            var proxyDefinition = new ProxyDefinition(serviceType, () => container.GetInstance(serviceType));
            var proxyType = proxyBuilder.GetProxyType(proxyDefinition);

            return base.CreateServiceHost(proxyType, baseAddresses);
        }
        /// <summary>
        /// Den passenden HttpCall zusammenbauen und prüfen ob Post oder Get verwendet werden soll
        /// Erstellt wird: post("/Home/LoadAll", data) oder get("/Home/LoadAll?userId=" + id)
        /// </summary>
        public string BuildHttpCall(ProxyMethodInfos methodInfo, ProxyBuilder proxyBuilder)
        {
            //Wie genau das Post oder Geht aussieht, hängt von den gewünschten Parametern ab.
            //Aktuell gehen wir von einer StandardRoute aus und wenn ein "id" in den Parametern ist, dann
            //Handelt es sich z.B. um den Letzten Parameter in der StandardRoute.
            //Beispiele:
            //.post("/Home/GetAutosByHerstellerId/" + id, message)
            //.post("/ControllerName/GetAutosByHerstellerId/", message)
            //get("/Home/GetSuccessMessage")
            //get("/Home/GetSuccessMessage/" + id + "?name=" + urlencodestring + "&test=2")

            //Prüfen ob ein complexer Typ verwendet wird.
            if (methodInfo.ProxyMethodParameterInfos.Count(p => p.IsComplexeType) == 0)
            {
                //Wenn über der Controller Action Post angegeben wurde, dann auch Post verwenden
                //obwohl kein komplexer Typ enthalten ist.
                if (ProxyBuilderHelper.HasAttribute(typeof(HttpPostAttribute), methodInfo.MethodInfo))
                {
                    if (proxyBuilder == ProxyBuilder.jQueryTypeScript || proxyBuilder == ProxyBuilder.jQueryJavaScript)
                    {
                        return BuildPostjQuery(methodInfo);
                    }

                    return BuildPostAngular(methodInfo, proxyBuilder);
                }

                //Kein Komplexer Typ also Get verwenden.
                return BuildGet(methodInfo);
            }

            if (proxyBuilder == ProxyBuilder.jQueryTypeScript || proxyBuilder == ProxyBuilder.jQueryJavaScript)
            {
                return BuildPostjQuery(methodInfo);
            }

            return BuildPostAngular(methodInfo, proxyBuilder);
        }
コード例 #44
0
        private TypeDefinition CreateProxy(ProxyBuilder proxyBuilder,
            Action<TypeCodeGenInfo, TypeDefinition> onTypeGenerated,
            TypeCodeGenInfo typeInfo,
            Dictionary<TypeCodeGenInfo, TypeDefinition> generatedTypeDict)
        {
            var targetType = typeInfo.TransformedType;
            var name = targetType.Name;

            TypeDefinition baseTypeDef = null;
            var tt = typeInfo.TransformedType;
            var rt = typeInfo.TransformedType as ResourceType;
            if (rt != null && rt.UriBaseType != null && rt.UriBaseType != rt)
            {
                var baseTypeInfo = this.clientTypeInfoDict[tt.BaseType];
                baseTypeDef = generatedTypeDict.GetOrCreate(baseTypeInfo,
                    () =>
                        CreateProxy(proxyBuilder,
                            onTypeGenerated,
                            baseTypeInfo,
                            generatedTypeDict));
            }
            var proxyType = proxyBuilder.CreateProxyType(name, typeInfo.InterfaceType.WrapAsEnumerable(), baseTypeDef);

            if (onTypeGenerated != null)
                onTypeGenerated(typeInfo, proxyType);

            return proxyType;
        }
        /// <summary>
        /// Rückgabe für Post erstellen für Angular Calls
        /// </summary>
        /// <returns>Gibt den passenden POST Aufruf zurück</returns>
        private string BuildPostAngular(ProxyMethodInfos infos, ProxyBuilder proxyBuilder)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(string.Format("post('{0}/{1}'", ProxyBuilderHelper.GetClearControllerName(infos.Controller), infos.MethodInfo.Name));

            builder.Append(ProxyBuilderHelper.BuildUrlParameterId(infos.ProxyMethodParameterInfos));
            builder.Append(ProxyBuilderHelper.BuildUrlParameter(infos.ProxyMethodParameterInfos));

            //Da auch ein Post ohne komplexen Typ aufgerufen werden kann über das "HttpPost" Attribut hier prüfen
            //ob ein komplexer Typ enthalten ist.
            if (infos.ProxyMethodParameterInfos.Any(p => p.IsComplexeType))
            {
                //Da es nur einen Complexen Typ geben darf pro Methodenaufruf, hier prüfen ob ein FileUpload dabei ist.
                if (infos.ProxyMethodParameterInfos.Any(p => p.IsFileUpload))
                {
                    if (proxyBuilder != ProxyBuilder.Angular2TypeScript)
                    {
                        //Achtung die "formData" Variable wird bei "#FunctionContent#" eingefügt
                        builder.Append(",formData, { transformRequest: angular.identity, headers: { 'Content-Type': undefined }})");
                    }
                    else
                    {
                        //für angular 2 muss hier nur FormData übergeben werden.
                        builder.Append(",formData)");
                    }
                }
                else
                {
                    //Standard Post
                    builder.Append(string.Format(",{0})", infos.ProxyMethodParameterInfos.First(p => p.IsComplexeType).ParameterName));
                }
            }
            else
            {
                builder.Append(")");
            }

            return builder.ToString();
        }
        public void Execute_AbstractMethod_InvokeInterceptor()
        {
            var interceptorMock = new Mock<IInterceptor>();
            var proxyBuilder = new ProxyBuilder();
            var proxyDefinition = new ProxyDefinition(typeof(ClassWithAbstractMethod), () => null);
            proxyDefinition.Implement(() => interceptorMock.Object);            
            var proxyType = proxyBuilder.GetProxyType(proxyDefinition);
            var instance = (ClassWithAbstractMethod)Activator.CreateInstance(proxyType);
            instance.Execute();
            interceptorMock.Verify(interceptor => interceptor.Invoke(It.IsAny<IInvocationInfo>()), Times.Once);

        }
コード例 #47
0
ファイル: ProxyTest.cs プロジェクト: Reen/protobuf-remote
        public void Init()
        {
            proxyBuilder = new ProxyBuilder();
            client = new Mock<RpcClient>(new Mock<RpcController>().Object);

            pendingSquareCall = new PendingCall(0, null, null, null, null);
            var squareResultMessage = new RpcMessage.Result();
            squareResultMessage.CallResult = new RpcMessage.Parameter();
            squareResultMessage.CallResult.IntParam = 42;
            pendingSquareCall.ReceiveResult(squareResultMessage);

            client.Setup(c => c.Call("ISampleService", "GetSquare", It.IsAny<RpcMessage.Parameter[]>(),
                It.IsAny<AsyncCallback>(), It.IsAny<object>()))
                .Returns(pendingSquareCall);
        }
コード例 #48
0
        private void CreateProxies(
            ProxyBuilder proxyBuilder,
            Action<TypeCodeGenInfo, TypeDefinition> onTypeGenerated,
            Func<TypeCodeGenInfo, bool> typeIsGeneratedPredicate = null)
        {
            typeIsGeneratedPredicate = typeIsGeneratedPredicate ?? (x => true);
            var generatedTypeDict = new Dictionary<TypeCodeGenInfo, TypeDefinition>();

            foreach (var typeInfo in this.clientTypeInfoDict.Values.Where(typeIsGeneratedPredicate))
            {
                generatedTypeDict.GetOrCreate(typeInfo,
                    () =>
                        CreateProxy(proxyBuilder, onTypeGenerated, typeInfo, generatedTypeDict));
            }
        }