private static ProxyGeneratorResult CreateProxyGeneratorResult(
            Type typeOfProxy,
            ProxyGenerationOptions options,
            IEnumerable <Type> additionalInterfacesToImplement,
            IEnumerable <object> argumentsForConstructor,
            IFakeCallProcessorProvider fakeCallProcessorProvider)
        {
            var    interceptor = new ProxyInterceptor(fakeCallProcessorProvider);
            object proxy;

            try
            {
                proxy = DoGenerateProxy(
                    typeOfProxy,
                    options,
                    additionalInterfacesToImplement,
                    argumentsForConstructor,
                    interceptor);
            }
            catch (Exception e)
            {
                return(GetResultForFailedProxyGeneration(typeOfProxy, argumentsForConstructor, e));
            }

            fakeCallProcessorProvider.EnsureInitialized(proxy);

            return(new ProxyGeneratorResult(generatedProxy: proxy));
        }
예제 #2
0
        private object CreateMockDelegate(Type type)
        {
            if (typeof(Delegate).Equals(type))
            {
                throw new InvalidOperationException("The base System.Delegate type cannot be mocked.");
            }

            var types = new List <Type>();

            types.Add(type);

            var interfaces = new List <Type>();

            interfaces.Add(typeof(IMockInstance));
            interfaces.Add(typeof(IMockExpectationContainer));

            var instance         = new MockInstance(types.ToArray());
            var mockInterceptor  = new MockInterceptor(instance);
            var proxyInterceptor = new ProxyInterceptor(instance);
            var dynamicType      = delegateRepository.CreateTargetInterface(type);
            var generator        = IdentifyGenerator(type);

            var target = generator.CreateInterfaceProxyWithoutTarget(dynamicType, interfaces.ToArray(),
                                                                     generatorOptions, mockInterceptor, proxyInterceptor, objectInterceptor);

            var proxy = Delegate.CreateDelegate(type, target, "Invoke");

            instance.ProxyInstance = proxy;
            return(proxy);
        }
예제 #3
0
 public override void X()
 {
     //var items = new[] { t, value, va, sd, sdsd, asda };
     var items             = new object[0];
     var task              = new Task <object>(executeTest, items);
     var interceptorValues = new InterceptionInformation(this, null, "X", items, task);
     var result            = ProxyInterceptor.Invoke(interceptorValues);
 }
예제 #4
0
            public override int TestX()
            {
                var items             = new object[0];
                var task              = Task.FromResult <object>(default(int));
                var interceptorValues = new InterceptionInformation(this, null, "Test", items, task);
                var result            = ProxyInterceptor.Invoke(interceptorValues);

                return((int)result);
            }
예제 #5
0
        private object CreateMockRemoted(Type type)
        {
            var instance         = new MockInstance(new Type[0]);
            var proxyInterceptor = new ProxyInterceptor(instance);

            var generator = new RepositoryForRemoting();
            var proxy     = generator.CreateMockRemoting(type, proxyInterceptor, instance);

            instance.ProxyInstance = proxy;
            return(proxy);
        }
예제 #6
0
        public virtual ProxyInterceptor Antipod()
        {
            //类库配置
            ProteinConfig pconfig = ProteinConfig.GetInstance();
            //代理拦截器
            ProxyInterceptor pri = new ProxyInterceptor();
            ProxyDefaul      pd  = new ProxyDefaul();

            //对拦截器的机制进行初始化
            pd.SetProxy(pri);
            return(pri);
        }
예제 #7
0
        private object CreateMockClass(Type type, Type[] extraTypes, object[] arguments, bool isPartial)
        {
            if (type.IsSealed)
            {
                throw new InvalidOperationException("Sealed classes cannot be mocked.");
            }

            var types = new List <Type>(extraTypes);

            types.Add(type);

            var interfaces = new List <Type>(extraTypes);

            interfaces.Add(typeof(IMockInstance));
            interfaces.Add(typeof(IMockExpectationContainer));

            var instance         = new MockInstance(types.ToArray());
            var mockInterceptor  = new MockInterceptor(instance);
            var proxyInterceptor = new ProxyInterceptor(instance);
            var generator        = IdentifyGenerator(type);

            try
            {
                var proxy = generator.CreateClassProxy(type, interfaces.ToArray(),
                                                       defaultOptions, arguments, mockInterceptor, proxyInterceptor, objectInterceptor);

                var mocked = (IMockInstance)proxy;
                mocked.IsPartialInstance    = isPartial;
                mocked.ConstructorArguments = arguments;

                GC.SuppressFinalize(proxy);

                instance.ProxyInstance = proxy;
                return(proxy);
            }
            catch (MissingMethodException ex)
            {
                var message = string.Format("No constructor taking {0} arguments found.", arguments.Length);
                throw new MissingMethodException(message, ex);
            }
            catch (TargetInvocationException ex)
            {
                var message = string.Format("Exception was thrown in constructor: {0}", ex.InnerException);
                throw new Exception(message, ex.InnerException);
            }
        }
예제 #8
0
            //public Test3()
            //{
            //    Value = new Test3();
            //}

            //public Test3(Test2 value) : this()
            //{
            //    Value = value;
            //}

            public override string Test(string t, object value, object va, object sd, object sdsd, object asda)
            {
                //var items = new[] { t, value, va, sd, sdsd, asda };
                var items = new object[6];

                items[0] = t;
                items[1] = value;
                items[2] = va;
                items[3] = sd;
                items[4] = sdsd;
                items[5] = asda;
                var task = new Task <object>(executeTest, items);
                var interceptorValues = new InterceptionInformation(this, null, "Test", items, task);
                var result            = ProxyInterceptor.Invoke(interceptorValues);

                return((string)result);
            }
        private static ProxyGeneratorResult CreateProxyGeneratorResult(Type typeOfProxy, IEnumerable <Type> additionalInterfacesToImplement, IEnumerable <object> argumentsForConstructor)
        {
            var interceptor = new ProxyInterceptor();

            try
            {
                var proxy = DoGenerateProxy(
                    typeOfProxy,
                    additionalInterfacesToImplement,
                    argumentsForConstructor,
                    interceptor);

                return(new ProxyGeneratorResult(
                           generatedProxy: proxy,
                           callInterceptedEventRaiser: interceptor));
            }
            catch (Exception)
            {
                return(GetResultForFailedProxyGeneration(typeOfProxy, argumentsForConstructor));
            }
        }
예제 #10
0
        private static ProxyGeneratorResult CreateProxyGeneratorResult(Type typeOfProxy, IEnumerable <Type> additionalInterfacesToImplement, IEnumerable <object> argumentsForConstructor)
        {
            var interceptor = new ProxyInterceptor();

            try
            {
                var proxy = DoGenerateProxy(
                    typeOfProxy,
                    additionalInterfacesToImplement,
                    argumentsForConstructor,
                    interceptor);

                return(new ProxyGeneratorResult(
                           generatedProxy: proxy,
                           callInterceptedEventRaiser: interceptor));
            }
            catch (Exception ex)
            {
                Logger.Debug("Failed to create proxy of type {0}, an exception was thrown:\r\n\r\n{1}\r\n\r\n.", typeOfProxy, ex.Message);
                return(GetResultForFailedProxyGeneration(typeOfProxy, argumentsForConstructor));
            }
        }
        private static ProxyGeneratorResult CreateProxyGeneratorResult(Type typeOfProxy, IEnumerable<Type> additionalInterfacesToImplement, IEnumerable<object> argumentsForConstructor)
        {
            var interceptor = new ProxyInterceptor();

            try
            {
                var proxy = DoGenerateProxy(
                    typeOfProxy,
                    additionalInterfacesToImplement,
                    argumentsForConstructor,
                    interceptor);

                return new ProxyGeneratorResult(
                    generatedProxy: proxy,
                    callInterceptedEventRaiser: interceptor);
            }
            catch (Exception ex)
            {
                Logger.Debug("Failed to create proxy of type {0}, an exception was thrown:\r\n\r\n{1}\r\n\r\n.", typeOfProxy, ex.Message);
                return GetResultForFailedProxyGeneration(typeOfProxy, argumentsForConstructor);
            }
        }
예제 #12
0
        private object CreateMockInterface(Type type, Type[] extraTypes)
        {
            var types = new List <Type>(extraTypes);

            types.Add(type);

            var interfaces = new List <Type>(extraTypes);

            interfaces.Add(typeof(IMockInstance));
            interfaces.Add(typeof(IMockExpectationContainer));

            var instance         = new MockInstance(types.ToArray());
            var mockInterceptor  = new MockInterceptor(instance);
            var proxyInterceptor = new ProxyInterceptor(instance);
            var generator        = IdentifyGenerator(type);

            var proxy = generator.CreateInterfaceProxyWithoutTarget(type, interfaces.ToArray(),
                                                                    generatorOptions, mockInterceptor, proxyInterceptor, objectInterceptor);

            instance.ProxyInstance = proxy;
            return(proxy);
        }
예제 #13
0
 internal static ILoggingService GetLoggingService()
 => Program.LoggingService ?? (Program.LoggingService = Router.OutgoingChannel?.RealmProxy.Services.GetCalleeProxy <ILoggingService>(ProxyInterceptor.Create()));
        private static ProxyGeneratorResult CreateProxyGeneratorResult(Type typeOfProxy, IEnumerable<Type> additionalInterfacesToImplement, IEnumerable<object> argumentsForConstructor)
        {
            var interceptor = new ProxyInterceptor();

            try
            {
                var proxy = DoGenerateProxy(
                    typeOfProxy,
                    additionalInterfacesToImplement,
                    argumentsForConstructor,
                    interceptor);

                return new ProxyGeneratorResult(
                    generatedProxy: proxy,
                    callInterceptedEventRaiser: interceptor);
            }
            catch (Exception e)
            {
                return GetResultForFailedProxyGeneration(typeOfProxy, argumentsForConstructor, e);
            }
        }
예제 #15
0
 internal static object GetBakedProxy(string key, ProxyInterceptor interceptor, object[] args)
 {
     throw new NotImplementedException();
 }
예제 #16
0
 internal IController GetServiceManager(string controllerID)
 {
     if (!this.ServiceManagers.TryGetValue(controllerID, out IController serviceManager))
     {
         serviceManager = Router.OutgoingChannel.RealmProxy.Services.GetCalleeProxy <IController>(ProxyInterceptor.Create(controllerID));
         this.ServiceManagers.TryAdd(controllerID, serviceManager);
     }
     return(serviceManager);
 }
예제 #17
0
        public async Task SendInterCommunicateMessageAsync(string type, JToken data = null)
        {
            if (this.RTUService == null)
            {
                return;
            }

            var message = new CommunicateMessage("APIGateway")
            {
                Type = type,
                Data = data ?? new JObject()
            };

            try
            {
                await this.RTUService.SendInterCommunicateMessageAsync(message).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                if (ex is WampException && (ex as WampException).ErrorUri.Equals("wamp.error.no_such_procedure"))
                {
                    try
                    {
                        await Task.Delay(UtilityService.GetRandomNumber(456, 789)).ConfigureAwait(false);

                        this.RTUService = Router.OutgoingChannel.RealmProxy.Services.GetCalleeProxy <IRTUService>(ProxyInterceptor.Create());
                        await this.RTUService.SendInterCommunicateMessageAsync(message).ConfigureAwait(false);
                    }
                    catch (Exception exception)
                    {
                        Global.OnError?.Invoke($"Error occurred while sending an inter-communicate message => {exception.Message}", exception);
                    }
                }
                else
                {
                    Global.OnError?.Invoke($"Error occurred while sending an inter-communicate message => {ex.Message}", ex);
                }
            }
        }
예제 #18
0
        /// <summary>
        /// Creates new instance of services manager
        /// </summary>
        public Manager()
        {
            this.OnIncomingConnectionEstablished = async(sender, args) =>
            {
                try
                {
                    try
                    {
                        await(this.Instance != null ? this.Instance.DisposeAsync().AsTask() : Task.CompletedTask).ConfigureAwait(false);
                    }
                    catch { }
                    this.Instance = await Router.IncomingChannel.RealmProxy.Services.RegisterCallee(this, RegistrationInterceptor.Create()).ConfigureAwait(false);

                    this.Communicator?.Dispose();
                    this.Communicator = Router.IncomingChannel.RealmProxy.Services
                                        .GetSubject <CommunicateMessage>("messages.services.apigateway")
                                        .Subscribe(
                        message => this.ProcessInterCommunicateMessage(message),
                        exception => Global.OnError?.Invoke($"Error occurred while fetching inter-communicate message => {exception.Message}", exception)
                        );
                }
                catch (Exception ex)
                {
                    Global.OnError?.Invoke($"Error occurred while initializing the manager => {ex.Message}", ex);
                }
            };

            this.OnOutgoingConnectionEstablished = async(sender, args) =>
            {
                try
                {
                    while (Router.IncomingChannel == null || Router.OutgoingChannel == null)
                    {
                        await Task.Delay(UtilityService.GetRandomNumber(123, 456)).ConfigureAwait(false);
                    }
                    this.RTUService = Router.OutgoingChannel.RealmProxy.Services.GetCalleeProxy <IRTUService>(ProxyInterceptor.Create());
                    await this.SendRequestInfoAsync().ConfigureAwait(false);

                    Global.OnProcess?.Invoke($"Successfully subscribe the manager's communicator");
                }
                catch (Exception ex)
                {
                    Global.OnError?.Invoke($"Error occurred while sending the request info => {ex.Message}", ex);
                }
            };

            this.RequestInfoInterval = Int32.TryParse(UtilityService.GetAppSetting("TimerInterval:RequestInfo"), out var requestInterval) ? requestInterval : 15;
            this.RequestInfoTimer    = Observable.Timer(TimeSpan.FromMinutes(this.RequestInfoInterval), TimeSpan.FromMinutes(this.RequestInfoInterval)).Subscribe(async _ =>
            {
                if ((DateTime.Now - this.RequestTime).TotalMinutes >= this.RequestInfoInterval - 2)
                {
                    try
                    {
                        await this.SendRequestInfoAsync().ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Global.OnError?.Invoke($"Error occurred while sending the request info => {ex.Message}", ex);
                    }
                    this.RequestTime = DateTime.Now;
                }
            });
        }
        private static ProxyGeneratorResult CreateProxyGeneratorResult(
            Type typeOfProxy,
            ProxyGenerationOptions options,
            IEnumerable<Type> additionalInterfacesToImplement,
            IEnumerable<object> argumentsForConstructor,
            IFakeCallProcessorProvider fakeCallProcessorProvider)
        {
            var interceptor = new ProxyInterceptor(fakeCallProcessorProvider);
            object proxy;

            try
            {
                proxy = DoGenerateProxy(
                    typeOfProxy,
                    options,
                    additionalInterfacesToImplement,
                    argumentsForConstructor,
                    interceptor);
            }
            catch (Exception e)
            {
                return GetResultForFailedProxyGeneration(typeOfProxy, argumentsForConstructor, e);
            }

            fakeCallProcessorProvider.EnsureInitialized(proxy);

            return new ProxyGeneratorResult(generatedProxy: proxy);
        }
예제 #20
0
        /// <summary>
        /// Initializes the real-time updater (RTU) service
        /// </summary>
        /// <returns></returns>
        public static async Task <IRTUService> InitializeRTUServiceAsync()
        {
            if (Global._RTUService == null)
            {
                await Router.OpenOutgoingChannelAsync().ConfigureAwait(false);

                Global._RTUService = Router.OutgoingChannel.RealmProxy.Services.GetCalleeProxy <IRTUService>(ProxyInterceptor.Create());
            }
            return(Global._RTUService);
        }
예제 #21
0
 /// <summary>
 /// 设置代理拦截器
 /// </summary>
 /// <param name="ProxyInter"></param>
 public virtual void SetProxy(ProxyInterceptor ProxyInter)
 {
     ProxyInter.InvokeException += new ExceptionHandler(ExceptionProxy);
     ProxyInter.InvokeAfter     += new InvokeHandler(ProxyInter_InvokeAfter);
 }
예제 #22
0
        /// <summary>
        /// Gets a service of CMS Portals that specified by a name
        /// </summary>
        /// <param name="name">The string that presents the name of a service in CMS Portals</param>
        /// <returns></returns>
        public static ICmsPortalsService GetService(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ServiceNotFoundException("The service name is null or empty");
            }

            if (!CmsPortalsServiceExtensions.Services.TryGetValue(name, out var service))
            {
                service = Router.OutgoingChannel.RealmProxy.Services.GetCalleeProxy <ICmsPortalsService>(ProxyInterceptor.Create(name));
                CmsPortalsServiceExtensions.Services.Add(name, service);
            }

            return(service ?? throw new ServiceNotFoundException($"The service \"{name.ToLower()}\" is not found"));
        }
예제 #23
0
 internal static object GetBakedProxy(string key, ProxyInterceptor interceptor, object[] args)
 {
     throw new NotImplementedException();
 }