Exemplo n.º 1
0
        private ChoRealProxyInstanceState GetInstance(IConstructionCallMessage ctorCallMessage)
        {
            if (_instances.ContainsKey(ctorCallMessage.ActivationType))
            {
                return(_instances[ctorCallMessage.ActivationType]);
            }

            lock (_padLock)
            {
                if (!_instances.ContainsKey(ctorCallMessage.ActivationType))
                {
                    IConstructionReturnMessage retMsg   = InitializeServerObject(ctorCallMessage);
                    IConstructionReturnMessage response = null;

                    if (retMsg.Exception == null)
                    {
                        _target = GetUnwrappedServer();
                        SetStubData(this, _target);
                        response = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctorCallMessage, (MarshalByRefObject)this.GetTransparentProxy());
                    }
                    _instances.Add(ctorCallMessage.ActivationType, new ChoRealProxyInstanceState()
                    {
                        Target = _target, MethodMessage = response, Exception = retMsg.Exception, IsInitialized = false
                    });
                }

                return(_instances[ctorCallMessage.ActivationType]);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 實現Invoke方法
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public override IMessage Invoke(IMessage msg)
        {
            IMethodReturnMessage methodReturnMessage = null;
            IMethodCallMessage   methodCallMessage   = msg as IMethodCallMessage;

            if (methodCallMessage != null)
            {
                IConstructionCallMessage constructionCallMessage = methodCallMessage as IConstructionCallMessage;
                if (constructionCallMessage != null)
                {
                    RealProxy defaultProxy = RemotingServices.GetRealProxy(_target);
                    defaultProxy.InitializeServerObject(constructionCallMessage);
                    methodReturnMessage = EnterpriseServicesHelper.CreateConstructionReturnMessage(constructionCallMessage, (MarshalByRefObject)GetTransparentProxy());
                }
                else
                {
                    _interception.PreInvoke(methodCallMessage);
                    try
                    {
                        methodReturnMessage = RemotingServices.ExecuteMessage(_target, methodCallMessage);
                    }
                    catch { }
                    if (methodReturnMessage.Exception != null)
                    {
                        _interception.ExceptionHandle(methodReturnMessage);
                    }
                    else
                    {
                        _interception.PostInvoke(methodReturnMessage);
                    }
                }
            }
            return(methodReturnMessage);
        }
Exemplo n.º 3
0
        //覆写Invoke,处理RealProxy截获的各种消息,
        //此种方式最简捷,但不能截获远程对象的激活,好在我们并不是真的要Remoting
        public override IMessage Invoke(IMessage msg)
        {
            var call = msg as IMethodCallMessage;
            IConstructionCallMessage ctr  = call as IConstructionCallMessage;
            IMethodReturnMessage     back = null;

            //构造函数,只有ContextBoundObject(Inherit from MarshalByRefObject)对象才能截获构造函数
            if (ctr != null)
            {
                RealProxy defaultProxy = RemotingServices.GetRealProxy(_target);
                //如果不做下面这一步,_target还是一个没有直正实例化被代理对象的透明代理,
                //这样的话,会导致没有直正构建对象。
                defaultProxy.InitializeServerObject(ctr);
                //本类是一个RealProxy,它可通过GetTransparentProxy函数得到透明代理
                back = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctr, (MarshalByRefObject)GetTransparentProxy());
            }
            //MarshalByRefObject对象就可截获普通的调用消息,
            //MarshalByRefObject对象告诉编译器,不能将其内部简单的成员函数优化成内联代码,
            //这样才能保证函数调用都能截获。
            else
            {
                IDictionary <string, object> dic = new Dictionary <string, object>();
                dic = call.Args[0] as IDictionary <string, object>;
                if (dic != null & dic.Count > 0)
                {
                    foreach (var m in dic)
                    {
                    }
                }
                back = RemotingServices.ExecuteMessage(_target, call);
            }
            return(back);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Builds a method call return message given the returnvalue, out arguments and methodcall.
        /// </summary>
        /// <param name="returnValue">Return value of the methodcall.</param>
        /// <param name="arguments">Input and output argument values.</param>
        /// <param name="callMessage">The original methodcall object.</param>
        /// <remarks>
        /// This method is to be used during recording phase only. A .NET return message object
        /// is constructed based on the given information, where all non-serializable return
        /// values and output arguments are mocked for recording.
        /// </remarks>
        public static IMethodReturnMessage BuildReturnMessage(object returnValue, object[] arguments, IMethodCallMessage callMessage)
        {
            // Build return message:
            IConstructionCallMessage ccm = callMessage as IConstructionCallMessage;

            if (ccm != null)
            {
                // If constructor message, build returnmessage from construction:
                return(EnterpriseServicesHelper.CreateConstructionReturnMessage(ccm, (MarshalByRefObject)returnValue));
            }
            else
            {
                // Wrap return value:
                object wrappedReturnValue;
                wrappedReturnValue = WrapObject(returnValue, ((MethodInfo)callMessage.MethodBase).ReturnType);
                // Copy arguments, wrapping output arguments:
                int      outArgsCount = 0;
                object[] wrappedArgs  = new object[arguments.Length];
                foreach (ParameterInfo param in callMessage.MethodBase.GetParameters())
                {
                    if (param.ParameterType.IsByRef)
                    {
                        wrappedArgs[param.Position] = WrapObject(arguments[param.Position], param.ParameterType);
                        outArgsCount++;
                    }
                    else
                    {
                        wrappedArgs[param.Position] = arguments[param.Position];
                    }
                }
                // Build return message:
                return(new ReturnMessage(wrappedReturnValue, wrappedArgs, outArgsCount, callMessage.LogicalCallContext, callMessage));
            }
        }
Exemplo n.º 5
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage       call   = msg as IMethodCallMessage;
            IConstructionCallMessage ctor   = msg as IConstructionCallMessage;
            IMethodReturnMessage     result = null;

            if (ctor != null)               // 呼び出し関数がコンストラクタの場合

            {
                _behavior.PreInitializer(ctor);

                RealProxy rp = RemotingServices.GetRealProxy(_target);
                rp.InitializeServerObject(ctor);
                MarshalByRefObject tp = this.GetTransparentProxy() as MarshalByRefObject;
                result = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp);

                _behavior.PostInitializer(ctor);
            }
            else if (call != null)                 // 通常関数の場合

            {
                _behavior.PreCallMethod(call);

                result = RemotingServices.ExecuteMessage(this._target, call);

                _behavior.PostCallMethod(call);
            }
            else
            {
                Console.WriteLine($"メソッドの実行に失敗しました:{msg}");
                //throw new Exception($"メソッドの実行に失敗しました:{msg}");
            }

            return(result);
        }
Exemplo n.º 6
0
        public override IMessage Invoke(IMessage msg)
        {
            var ctr = msg as IConstructionCallMessage;

            if (ctr != null)
            {
                Console.WriteLine("ctr");
                RealProxy _proxy = RemotingServices.GetRealProxy(this._target);
                _proxy.InitializeServerObject(ctr);
                MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy();
                return(EnterpriseServicesHelper.CreateConstructionReturnMessage(ctr, tp));
            }

            if (_intercepts != null)
            {
                foreach (var _intercept in _intercepts)
                {
                    _intercept.Do();
                }
            }
            var call = msg as IMethodCallMessage;

            Console.WriteLine(string.Format("proxy method:{0}", call.MethodName));
            var result = call.MethodBase.Invoke(this._target, call.Args);

            return(new ReturnMessage(result, new object[0], 0, null, call));
        }
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage                  call = (IMethodCallMessage)msg;
            IConstructionCallMessage            ctor = call as IConstructionCallMessage;
            List <Action <IMethodCallMessage> > OnMethodExecuting = new List <Action <IMethodCallMessage> >();
            List <Action <IMethodCallMessage, IMethodReturnMessage> > OnMethodExecuted = new List <Action <IMethodCallMessage, IMethodReturnMessage> >();

            IMethodReturnMessage returnMessage = null;

            if (ctor != null)
            {
                //构造函数
                //获取最底层的默认真实代理
                RealProxy default_proxy = RemotingServices.GetRealProxy(this.target);
                default_proxy.InitializeServerObject(ctor);
                MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy(); //自定义的透明代理 this
                returnMessage = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp);
            }
            else
            {
                //方法
                object returnObject = null;
                if (!Intercept(call, ref returnObject, ref OnMethodExecuting, ref OnMethodExecuted))
                {
                    if (returnObject is IMethodReturnMessage)
                    {
                        returnMessage = (IMethodReturnMessage)returnObject;
                    }
                    else
                    {
                        if (returnObject == null)
                        {
                            var method     = (MethodInfo)call.MethodBase;
                            var returnType = method.ReturnType;
                            if (returnType != typeof(void))
                            {
                                returnObject = returnType.IsValueType ? Activator.CreateInstance(returnType) : null;
                            }
                        }
                        returnMessage = new ReturnMessage(returnObject, call.Args, call.ArgCount, call.LogicalCallContext, call);
                    }
                }
                else
                {
                    OnMethodExecuting.ForEach((method) => { method(call); });
                    OnMethodExecuting.Clear();
                    try
                    {
                        returnMessage = RemotingServices.ExecuteMessage(this.target, call);
                    }
                    catch (Exception e)
                    {
                        returnMessage = new ReturnMessage(e, call);
                    }
                    OnMethodExecuted.ForEach((method) => { method(call, returnMessage); });
                    OnMethodExecuted.Clear();
                }
            }
            return(returnMessage);
        }
Exemplo n.º 8
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage   callMsg = msg as IMethodCallMessage;
            IMethodReturnMessage retMsg  = null;
            bool fLog = false;

            //메서드 시작 로그
            fLog = MethodEnterLog(callMsg);

            // 생성자 메서드 일경우
            if (msg is IConstructionCallMessage)
            {
                // 객체 생성 메시지 처리
                IConstructionCallMessage ctorMsg = (IConstructionCallMessage)msg;
                RealProxy proxy = RemotingServices.GetRealProxy(target);
                // 실제 객체를 생성한다.
                proxy.InitializeServerObject(ctorMsg);
                // 객체 생성 결과를 ‘만들어’ 반환한다.
                retMsg = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctorMsg, (MarshalByRefObject)this.GetTransparentProxy());
            }
            //일반 메서드
            else if (msg is IMethodCallMessage)
            {
                /*
                 * // 파라메터 있는 메서드와 아닌 메서드 나눌때
                 * if (callMsg.ArgCount > 0)
                 * {
                 *  // 파라메터 리스트 작성
                 *  Console.WriteLine("Parameter list :");
                 *
                 *  for (int i = 0; i < callMsg.ArgCount; i++)
                 *  {
                 *      Console.WriteLine("{0} | {1}: {2}", i, callMsg.GetArgName(i), callMsg.GetArg(i));
                 *  }
                 *  retMsg = RemotingServices.ExecuteMessage(target, callMsg);
                 * }
                 * else
                 * {
                 *  //메소드 실행 코드
                 *  retMsg = RemotingServices.ExecuteMessage(target, callMsg);
                 * }
                 */
                retMsg = RemotingServices.ExecuteMessage(target, callMsg);
            }

            if (retMsg.Exception != null)
            {
                Console.WriteLine(retMsg.MethodName + " 에서 " + retMsg.Exception.Message);
                //Environment.Exit(0);
            }

            // 메소드 종료 로그
            if (fLog)
            {
                MethodLeaveLog(retMsg);
            }

            return(retMsg);
        }
Exemplo n.º 9
0
            /// <summary>
            /// Invokes the message.
            /// </summary>
            /// <param name="msg">The message.</param>
            /// <returns>The result of invocation.</returns>
            public override IMessage Invoke(IMessage msg)
            {
                IConstructionCallMessage constructorCall = msg as IConstructionCallMessage;

                if (constructorCall != null)
                {
                    if (this.target == null)
                    {
                        MethodInfo factoryMethodInfo = Utility.GetInheritedMethod(constructorCall.ActivationType, DynamicConstructionAttribute.InstantiateMethodName, new[] { typeof(Type), typeof(object[]) });

                        if (factoryMethodInfo == null)
                        {
                            throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cannot create an instance of type '{0}' because there is no '{1}' static method defined in its inheritance hierarchy. See '{2}' methods for an example of corresponding method signature.", constructorCall.ActivationType.AssemblyQualifiedName, DynamicConstructionAttribute.InstantiateMethodName, typeof(LiveTest).AssemblyQualifiedName));
                        }

                        if (!DynamicConstructionAttribute.EnterInstantiationPhase())
                        {
                            throw new InvalidOperationException("Error in instantiation workflow. Object is already in the middle of instantiation when another instance of the object is created.");
                        }

                        try
                        {
                            this.target = (LiveTest)factoryMethodInfo.Invoke(null, new object[] { constructorCall.ActivationType, constructorCall.Args });
                        }
                        finally
                        {
                            DynamicConstructionAttribute.LeaveInstantiationPhase();
                        }
                    }

                    return(EnterpriseServicesHelper.CreateConstructionReturnMessage(constructorCall, (MarshalByRefObject)this.GetTransparentProxy()));
                }

                IMethodCallMessage methodCall = msg as IMethodCallMessage;

                if (methodCall != null)
                {
                    methodCall = new MethodCall(methodCall);

                    MethodCallEventArgs eventArgs = typeof(LiveTest).IsAssignableFrom(methodCall.MethodBase.DeclaringType) ? new MethodCallEventArgs(Interlocked.Increment(ref methodCallId), methodCall.MethodBase, methodCall.Args) : null;

                    if (eventArgs != null)
                    {
                        this.target.OnBeforeMethodCall(this.target, eventArgs);
                    }

                    IMessage result = RemotingServices.GetRealProxy(this.target).Invoke(methodCall);

                    if (eventArgs != null)
                    {
                        this.target.OnAfterMethodCall(this.target, eventArgs);
                    }

                    return(result);
                }

                throw new NotSupportedException("Operations other than constructor and method calls are not supported.");
            }
Exemplo n.º 10
0
        public override IMessage Invoke(IMessage msg)
        {
            IMessage             retMsg       = null;
            IMethodCallMessage   methodCall   = (IMethodCallMessage)msg;
            IMethodReturnMessage methodReturn = null;

            object[] copiedArgs = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[];
            methodCall.Args.CopyTo(copiedArgs, 0);
            List <RaiseEventAttribute> eventRaisors = null;

            if (msg is IConstructionCallMessage)
            {
                IConstructionCallMessage ccm = (IConstructionCallMessage)msg;
                RemotingServices.GetRealProxy(target).InitializeServerObject(ccm);
                ObjRef oRef = RemotingServices.Marshal(target);
                RemotingServices.Unmarshal(oRef);
                retMsg = EnterpriseServicesHelper.CreateConstructionReturnMessage(ccm, (MarshalByRefObject)this.GetTransparentProxy());
            }
            else
            {
                IMethodCallMessage mcm   = (IMethodCallMessage)msg;
                object[]           attrs = methodCall.MethodBase.GetCustomAttributes(typeof(RaiseEventAttribute), false);
                if (attrs != null && attrs.Count() > 0)
                {
                    eventRaisors = new List <RaiseEventAttribute>();
                    foreach (object att in attrs)
                    {
                        eventRaisors.Add((RaiseEventAttribute)attrs[0]);
                    }
                }

                try
                {
                    object returnValue = methodCall.MethodBase.Invoke(this.target, copiedArgs);
                    methodReturn = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, methodCall.LogicalCallContext, methodCall);

                    if (eventRaisors != null)
                    {
                        eventRaisors.ForEach(t => SysRuntime.EventBus.RaiseEvent(t.EventType, null));
                    }
                }
                catch (Exception ex)
                {
                    if (null != ex.InnerException)
                    {
                        methodReturn = new ReturnMessage(ex.InnerException, methodCall);
                    }
                    else
                    {
                        methodReturn = new ReturnMessage(ex, methodCall);
                    }
                }
                retMsg = methodReturn;
            }
            return(retMsg);
        }
Exemplo n.º 11
0
        public override IMessage Invoke(IMessage msg)
        {
            //throw new NotImplementedException();

            IMethodCallMessage       call = (IMethodCallMessage)msg;
            IConstructionCallMessage ctor = call as IConstructionCallMessage;
            IMethodReturnMessage     back = null;

            //filter method
            object[] attrs       = call.MethodBase.GetCustomAttributes(typeof(BusinessMethodAttribute), true);
            bool     isAopMethod = attrs.Length > 0;

            if (ctor != null)
            {
                //构造开始时
                //do something
                if (this.EventConstructionBegin != null)
                {
                    this.EventConstructionBegin(msg, back, this._target, null);
                }

                //执行远程对象构造方法
                MarshalByRefObject mbro      = this.GetTransparentProxy() as MarshalByRefObject;
                RealProxy          realProxy = RemotingServices.GetRealProxy(this._target);
                realProxy.InitializeServerObject(ctor);
                back = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, mbro);

                //构造结束时
                //do something
                if (this.EventConstructionEnd != null)
                {
                    this.EventConstructionEnd(msg, back, this._target, null);
                }

                return(back);
            }


            //方法执行开始时
            //do something
            if (this.EventMethodBegin != null && isAopMethod)
            {
                this.EventMethodBegin(msg, back, this._target, attrs[0] as BusinessMethodAttribute);
            }

            //执行远程对象方法
            back = RemotingServices.ExecuteMessage(this._target, call);

            //方法执行结束时
            //do something
            if (this.EventMethodEnd != null && isAopMethod)
            {
                this.EventMethodEnd(msg, back, this._target, attrs[0] as BusinessMethodAttribute);
            }
            return(back);
        }
Exemplo n.º 12
0
        public override IMessage Invoke(IMessage msg)
        {
            if (msg != null)
            {
                if (msg is IConstructionCallMessage)
                {
                    IConstructionCallMessage constructCallMsg = msg as IConstructionCallMessage;
                    //IConstructionReturnMessage constructionReturnMessage = this.InitializeServerObject((IConstructionCallMessage)msg);
                    //RealProxy.SetStubData(this, constructionReturnMessage.ReturnValue);
                    //return constructionReturnMessage;

                    RealProxy defaultProxy = RemotingServices.GetRealProxy(_target);

                    //如果不做下面这一步,_target还是一个没有直正实例化被代理对象的透明代理,
                    //这样的话,会导致没有直正构建对象。
                    defaultProxy.InitializeServerObject(constructCallMsg);

                    //本类是一个RealProxy,它可通过GetTransparentProxy函数得到透明代理
                    return(EnterpriseServicesHelper.CreateConstructionReturnMessage(constructCallMsg, (MarshalByRefObject)GetTransparentProxy()));
                }
                else if (msg is IMethodCallMessage)
                {
                    IMethodCallMessage callMsg = msg as IMethodCallMessage;
                    object[]           args    = callMsg.Args;

                    //System.Windows.Forms.MessageBox.Show(callMsg.MethodBase.ToString());

                    if (callMsg.MethodName.StartsWith("set_") && args.Length == 1)
                    {
                        method.Invoke(_target, new object[] { callMsg.MethodName.Substring(4), args[0] });//对属性进行调用
                    }
                    return(RemotingServices.ExecuteMessage(_target, callMsg));

                    //IMessage message = null;
                    //try
                    //{

                    //    MarshalByRefObject obj = GetUnwrappedServer();
                    //    if (callMsg.MethodName.StartsWith("set_") && args.Length == 1)
                    //    {
                    //        method.Invoke(obj, new object[] { callMsg.MethodName.Substring(4), args[0] });//对属性进行调用
                    //    }

                    //    object o = callMsg.MethodBase.Invoke(obj, args);
                    //    message = new ReturnMessage(o, args, args.Length, callMsg.LogicalCallContext, callMsg);
                    //}
                    //catch (Exception e)
                    //{
                    //    message = new ReturnMessage(e, callMsg);
                    //}
                    //return message;
                }
            }
            return(msg);
        }
        public IMessage LocalInvoke(IMessage reqMsg)
        {
            IMessage message = null;

            if (reqMsg is IConstructionCallMessage)
            {
                this.ActivateProxy();
                if (this._filterConstructors)
                {
                    this._filterConstructors = false;
                    RealProxy.SetStubData(this, this._token);
                }
                if (((IConstructionCallMessage)reqMsg).ArgCount > 0)
                {
                    throw new ServicedComponentException(Resource.FormatString("ServicedComponentException_ConstructorArguments"));
                }
                MarshalByRefObject transparentProxy = (MarshalByRefObject)this.GetTransparentProxy();
                return(EnterpriseServicesHelper.CreateConstructionReturnMessage((IConstructionCallMessage)reqMsg, transparentProxy));
            }
            if (reqMsg is IMethodCallMessage)
            {
                message = this.HandleSpecialMethods(reqMsg);
                if (message != null)
                {
                    return(message);
                }
                if ((base.GetUnwrappedServer() == null) || (((IntPtr)RealProxy.GetStubData(this)) == NegativeOne))
                {
                    throw new ObjectDisposedException("ServicedComponent");
                }
                bool flag = this.SendMethodCall(reqMsg);
                try
                {
                    message = RemotingServices.ExecuteMessage((MarshalByRefObject)this.GetTransparentProxy(), (IMethodCallMessage)reqMsg);
                    if (flag)
                    {
                        this.SendMethodReturn(reqMsg, ((IMethodReturnMessage)message).Exception);
                    }
                }
                catch (Exception exception)
                {
                    if ((exception is NullReferenceException) || (exception is SEHException))
                    {
                        throw;
                    }
                    if (flag)
                    {
                        this.SendMethodReturn(reqMsg, exception);
                    }
                    throw;
                }
            }
            return(message);
        }
Exemplo n.º 14
0
        public override IMessage Invoke(IMessage msg)
        {
            Exception InnerException;

            msg.Properties["__Uri"] = _TcpUrl;
            IMessage retMsg = _messageSinks[0].SyncProcessMessage(msg);

            // Handle construction call message differently than other method
            // call messages.
            if (msg is IConstructionCallMessage)
            {
                // need to finish CAO activation manually.
                string url = GetUrlForCAO(_serverType);
                if (url.Length > 0)
                {
                    ActivatedCAO((IConstructionCallMessage)msg, url);
                }

                IConstructionReturnMessage crm = EnterpriseServicesHelper.CreateConstructionReturnMessage((IConstructionCallMessage)msg, (MarshalByRefObject)this.GetTransparentProxy());
                return(crm);
            }
            else
            {
                if (retMsg is IMethodReturnMessage)
                {
                    IMethodReturnMessage mrm = (IMethodReturnMessage)retMsg;
                    if (mrm.Exception == null)
                    {
                        return(retMsg);
                    }
                    else
                    {
                        InnerException = mrm.Exception;
                    }
                }
                else
                {
                    MethodCallMessageWrapper mcm = new MethodCallMessageWrapper((IMethodCallMessage)msg);
                    mcm.Uri = RemotingServices.GetObjectUri((MarshalByRefObject)_targetTcp);
                    return(RemotingServices.GetEnvoyChainForProxy((MarshalByRefObject)_targetTcp).SyncProcessMessage(msg));
                }
                msg.Properties["__Uri"] = _HttpUrl;
                retMsg = _messageSinks[1].SyncProcessMessage(msg);
                if (retMsg is IMethodReturnMessage)
                {
                    IMethodReturnMessage mrm = (IMethodReturnMessage)retMsg;
                }
                return(retMsg);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 执行代理方法
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public override IMessage Invoke(IMessage message)
        {
            var callMessage             = message as IMethodCallMessage;
            var constructionCallMessage = callMessage as IConstructionCallMessage;

            if (constructionCallMessage != null)
            {
                //if ctor
                var defaultProxy = RemotingServices.GetRealProxy(_instance);
                defaultProxy.InitializeServerObject(constructionCallMessage);
                return(EnterpriseServicesHelper.CreateConstructionReturnMessage(constructionCallMessage,
                                                                                (MarshalByRefObject)
                                                                                GetTransparentProxy()));
            }
            var processer = new Processer(_interfaceType, _instance, callMessage);

            if (callMessage != null)
            {
                #region Get Attributes

                var allFilters = new List <IAOPFilter>();
                //获取类方法上的Attributes
                var methodFilters = GetFilterAttributes(callMessage.MethodName, callMessage.MethodSignature).ToList();

                //获取类上的
                var clsAttrs = _instance.GetType().GetCustomAttributes(typeof(IAOPFilter), false).Cast <IAOPFilter>();
                allFilters.InsertRange(0, clsAttrs);
                if (_interfaceType != null && _instance.GetType() != _interfaceType)
                {
                    //获取接口方法上的Attributes
                    var interMethodAttributes = callMessage.MethodBase.GetCustomAttributes(typeof(IAOPFilter), false)
                                                .Cast <IAOPFilter>();
                    //获取接口上的
                    var interfaceAttributes = _interfaceType.GetCustomAttributes(typeof(IAOPFilter), false).Cast <IAOPFilter>();


                    allFilters.AddRange(interMethodAttributes.Reverse());
                    allFilters.InsertRange(0, interfaceAttributes);
                }
                allFilters.AddRange(methodFilters);
                #endregion

                new AOPFilterContainer(allFilters).Execute(processer);
            }
            return(processer.MethodReturnMessage);
        }
Exemplo n.º 16
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodReturnMessage methodReturnMessage = null;

            var constructionCallMessage = msg as IConstructionCallMessage;

            if (constructionCallMessage != null) // Constructor Method.
            {
                var defaultProxy = RemotingServices.GetRealProxy(_target);
                defaultProxy.InitializeServerObject(constructionCallMessage);
                methodReturnMessage =
                    EnterpriseServicesHelper.CreateConstructionReturnMessage(constructionCallMessage,
                                                                             (MarshalByRefObject)GetTransparentProxy());
                return(methodReturnMessage);
            }

            var methodCallMessage = msg as IMethodCallMessage;

            if (methodCallMessage != null)
            {
                var methodInfo = (MethodInfo)methodCallMessage.MethodBase;

                var interceptMethods = _interception.InterceptMethod;
                // 不进行拦截
                if (!interceptMethods.Any(x =>
                {
                    var reg = x.Replace("*", @".*");
                    var regx = new Regex("^" + reg + "$");
                    return(regx.IsMatch(methodInfo.Name));
                }))
                {
                    try
                    {
                        var obj = methodInfo.Invoke(_target, methodCallMessage.Args);
                        return(new ReturnMessage(obj, null, 0, methodCallMessage.LogicalCallContext,
                                                 methodCallMessage));
                    }
                    catch (Exception ex)
                    {
                        return(new ReturnMessage(ex.InnerException ?? ex, methodCallMessage));
                    }
                }
                methodReturnMessage = Proceed(methodInfo, methodCallMessage);
            }
            return(methodReturnMessage);
        }
Exemplo n.º 17
0
        public override IMessage Invoke(IMessage msg)
        {
            bool useAspect          = false;
            IMethodCallMessage call = (IMethodCallMessage)msg;

            //查询目标方法是否使用了启用AOP的AopSwitcherAttribute
            //默认为使用Aspect
            var attr = CoreHelper.GetMemberAttribute <AopSwitcherAttribute>(call.MethodBase);

            if (attr != null)
            {
                useAspect = attr.UseAspect;
            }
            else
            {
                useAspect = true;
            }

            if (useAspect)
            {
                this.PreProceed(call);
            }

            //如果触发的是构造函数,此时target的构建还未开始
            IConstructionCallMessage ctor = call as IConstructionCallMessage;

            if (ctor != null)
            {
                //获取最底层的默认真实代理
                RealProxy default_proxy = RemotingServices.GetRealProxy(this.target);

                default_proxy.InitializeServerObject(ctor);
                MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy(); //自定义的透明代理 this

                return(EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp));
            }

            IMethodReturnMessage result_msg = RemotingServices.ExecuteMessage(this.target, call); //将消息转化为堆栈,并执行目标方法,方法完成后,再将堆栈转化为消息

            if (useAspect)
            {
                this.PostProceed(call, ref result_msg);
            }

            return(result_msg);
        }
Exemplo n.º 18
0
        public override IMessage Invoke(IMessage message)
        {
            IMethodCallMessage caller = (IMethodCallMessage)message;
            // Get proxy able
            bool proxyAble = _proxy;

            if (!proxyAble)
            {
                foreach (AProxyMethodAttribute attribute in caller.MethodBase.GetCustomAttributes(typeof(AProxyMethodAttribute), false))
                {
                    if (attribute.IsProxy)
                    {
                        proxyAble = true;
                        break;
                    }
                }
            }
            // Process before
            if (proxyAble)
            {
                ProcessBefore(caller);
            }
            // Process
            IMethodReturnMessage     response    = null;
            IConstructionCallMessage constructor = caller as IConstructionCallMessage;

            if (constructor != null)
            {
                // Constructor
                RealProxy defaultProxy = RemotingServices.GetRealProxy(_object);
                defaultProxy.InitializeServerObject(constructor);
                MarshalByRefObject transparentProxy = (MarshalByRefObject)this.GetTransparentProxy();
                response = EnterpriseServicesHelper.CreateConstructionReturnMessage(constructor, transparentProxy);
            }
            else
            {
                // Method
                response = RemotingServices.ExecuteMessage(_object, caller);
            }
            // Process after
            if (proxyAble)
            {
                ProcessAfter(caller, response);
            }
            return(response);
        }
Exemplo n.º 19
0
        public override IMessage Invoke(IMessage msg)
        {
            var call = (IMethodCallMessage)msg;
            var ctor = call as IConstructionCallMessage;

            IMethodReturnMessage res;

            var logAttr = call.MethodBase.GetCustomAttributes(true).FirstOrDefault(r => r.GetType() == typeof(TraceLogAttribute)) as TraceLogAttribute;

            if (ctor != null)
            {
                //以下、コンストラクタを実行する処理

                var rp = RemotingServices.GetRealProxy(this._target);
                res = rp.InitializeServerObject(ctor);
                var tp = this.GetTransparentProxy() as MarshalByRefObject;
                res = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp);
            }
            else
            {
                //以下、コンストラクタ以外のメソッドを実行する処理

                if (logAttr != null)
                {
                    //メソッド前処理
                    Console.WriteLine("[{0}]{1} : 実行開始",
                                      DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), logAttr.Title + "開始");
                }

                //メソッド実行
                res = RemotingServices.ExecuteMessage(this._target, call);
                if (res.Exception != null)
                {
                    throw res.Exception;
                }

                if (logAttr != null)
                {
                    //メソッド後処理
                    Console.WriteLine("[{0}]{1} : 実行終了",
                                      DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), logAttr.Title + "終了");
                }
            }

            return(res);
        }
Exemplo n.º 20
0
        public override IMessage Invoke(IMessage msg)
        {
            MockableCall call = new MockableCall(this, (IMethodCallMessage)msg);

            this.mocker.HandleCall(this, call);
            IMethodCallMessage mcm = msg as IMethodCallMessage;

            if (call.Exception != null)
            {
                return(new ReturnMessage(call.Exception, mcm));
            }
            else if (call.IsConstructorCall)
            {
                return(EnterpriseServicesHelper.CreateConstructionReturnMessage((IConstructionCallMessage)msg, (MarshalByRefObject)this.GetTransparentProxy()));
            }
            else
            {
                return(new ReturnMessage(call.ReturnValue, call.Args, call.GetOutParameters().Length, mcm.LogicalCallContext, mcm));
            }
        }
Exemplo n.º 21
0
        public virtual object GetInstance(IConstructionCallMessage ctorCallMessage, ref IMethodMessage returnMsg)
        {
            lock (_padLock)
            {
                if (!_ctorMsgs.ContainsKey(ctorCallMessage.ActivationType))
                {
                    RealProxy defaultProxy = RemotingServices.GetRealProxy(_target);
                    var       x            = defaultProxy.InitializeServerObject(ctorCallMessage);
                    IConstructionReturnMessage response = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctorCallMessage, (MarshalByRefObject)this.GetTransparentProxy());

                    _ctorMsgs.SetValue(ctorCallMessage.ActivationType, response);
                    _instanceMsgs.SetValue(ctorCallMessage.ActivationType, DoObjectInitialize(_target));

                    //_ctorMsgs.SetValue(ctorCallMessage.ActivationType, InitializeServerObject(ctorCallMessage));
                    //_instanceMsgs.SetValue(ctorCallMessage.ActivationType, DoObjectInitialize(GetUnwrappedServer()));
                }

                returnMsg = _ctorMsgs.GetValue(ctorCallMessage.ActivationType);
                return(_instanceMsgs.GetValue(ctorCallMessage.ActivationType));
            }
        }
Exemplo n.º 22
0
        /// <summary>
        ///  処理を実行します。
        /// </summary>
        /// <param name="msg">呼び出し元を表すメッセージです。</param>
        /// <returns>戻り値を表すメッセージです。</returns>
        public override IMessage Invoke(IMessage msg)
        {
            IMessage result = null;

            if (msg is IConstructionCallMessage ctor)               // コンストラクタの場合
            // 特殊な処理
            {
                _behavior.PreInitializer(_serverType, ctor);

                // コンストラクタ呼び出し
                var rp = RemotingServices.GetRealProxy(_target);
                rp.InitializeServerObject(ctor);
                var tp = this.GetTransparentProxy() as MarshalByRefObject;
                result = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp);

                // 特殊な処理
                _behavior.PostInitializer(_serverType, ctor);
            }
            else if (msg is IMethodCallMessage func)                 // 通常関数の場合
            // 特殊な処理
            {
                _behavior.PreCallMethod(_serverType, func);

                // 通常関数呼び出し
                result = RemotingServices.ExecuteMessage(_target, func);

                // 特殊な処理
                _behavior.PostCallMethod(_serverType, func);
            }
            else
            {
                // 呼び出しが不正
                result = _behavior.HandleInvalidCall(_serverType, msg);
            }

            return(result);
        }
Exemplo n.º 23
0
        /// <summary>
        /// 当在派生类中重写时,在当前实例所表示的远程对象上调用在所提供的 IMessage 中指定的方法。<br />
        /// WebsharpAspect在这里执行对方法执行的拦截处理
        /// </summary>
        /// <param name="msg">IMessage,包含有关方法调用的信息。</param>
        /// <returns>调用的方法所返回的消息,包含返回值和所有 out 或 ref 参数。</returns>
        public override IMessage Invoke(IMessage msg)
        {
            bool     canInjection = checkCanInjection(msg);
            DateTime beginExecute = System.DateTime.Now;

            if (canInjection)
            {
                BeginProcess(msg);
            }

            if (msg is IConstructionCallMessage)
            {
                IConstructionCallMessage ccm = (IConstructionCallMessage)msg;
                RemotingServices.GetRealProxy(_Target).InitializeServerObject(ccm);
                ObjRef oRef = RemotingServices.Marshal(_Target);
                RemotingServices.Unmarshal(oRef);
                IMessage retMsg = EnterpriseServicesHelper.CreateConstructionReturnMessage(ccm, (MarshalByRefObject)this.GetTransparentProxy());
                if (canInjection)
                {
                    EndProcess(beginExecute, retMsg);
                }

                return(retMsg);
            }
            else
            {
                IMethodReturnMessage returnmsg = RemotingServices.ExecuteMessage(_Target, (IMethodCallMessage)msg);

                if (canInjection)
                {
                    EndProcess(beginExecute, returnmsg);
                }

                return(returnmsg);
            }
        }
Exemplo n.º 24
0
        public override IMessage Invoke(IMessage msg)
        {
            Console.WriteLine("Proxy called: " + msg.Properties["__MethodName"]);
            if (msg is IConstructionCallMessage)
            {
                IConstructionCallMessage ctorMsg = (IConstructionCallMessage)msg;

                try {
                    RemotingServices.GetRealProxy(realObject).InitializeServerObject(ctorMsg);
                } catch {
                }

                ObjRef objRef = RemotingServices.Marshal(realObject);
                RemotingServices.Unmarshal(objRef);

                MarshalByRefObject transpProxy = (MarshalByRefObject)this.GetTransparentProxy();

                return(EnterpriseServicesHelper.CreateConstructionReturnMessage(ctorMsg, transpProxy));
            }
            else
            {
                return(RemotingServices.ExecuteMessage(realObject, (IMethodCallMessage)msg));
            }
        }
Exemplo n.º 25
0
        /// In the Invoke Method we do our interception work.
        public override IMessage Invoke(IMessage msg)
        {
            if (msg is IConstructionCallMessage)
            {
                ChoRealProxyInstanceState instance = GetInstance(msg as IConstructionCallMessage);
                if (instance.Exception != null)
                {
                    throw instance.Exception;
                }

                _target = instance.Target;
                return(EnterpriseServicesHelper.CreateConstructionReturnMessage(msg as IConstructionCallMessage, (MarshalByRefObject)this.GetTransparentProxy()));
            }
            else
            {
                IMethodMessage            returnMsg = null;
                ChoRealProxyInstanceState instance  = _instances[_target.GetType()];
                if (!instance.IsInitialized)
                {
                    DoObjectInitialize(_target);
                    instance.IsInitialized = true;
                }

                ///the MethodCallMessageWrapper provides read/write access to the method call arguments.
                MethodCallMessageWrapper methodCallMsg = new MethodCallMessageWrapper((IMethodCallMessage)msg);
                ///This is the reflected method base of the called method.
                MethodInfo methodInfo = (MethodInfo)methodCallMsg.MethodBase;

                ///This is the object we are proxying.
                MarshalByRefObject owner = _target as MarshalByRefObject;
                //MarshalByRefObject owner = _realObject as MarshalByRefObject;
                ///Some basic initializations for later use
                if (owner != null)
                {
                    ChoMemberInfo memberInfo = new ChoMemberInfo(owner, _objType, methodCallMsg);
                    if (!ChoType.IsValidObjectMember(memberInfo.Info))
                    {
                        return(RemotingServices.ExecuteMessage(owner, methodCallMsg));
                    }

                    return(ExecuteMethod(ref returnMsg, methodCallMsg, owner, memberInfo));

                    //if (methodCallMsg.LogicalCallContext.GetData("CallerId") != null)
                    //    return ExecuteMethod(ref returnMsg, methodCallMsg, owner, memberInfo);
                    //else
                    //{
                    //    methodCallMsg.LogicalCallContext.SetData("CallerId", ChoRandom.NextRandom());
                    //    IChoAsyncResult result = ChoQueuedExecutionService.Global.Enqueue(() =>
                    //        {
                    //            return ExecuteMethod(ref returnMsg, methodCallMsg, owner, memberInfo);
                    //        });

                    //    return (IMessage)result.EndInvoke();
                    //}
                }
                else
                {
                    return(new ReturnMessage(new NullReferenceException("Missing target object."), methodCallMsg));
                }
            }
        }
Exemplo n.º 26
0
        // Implement Invoke
        public override IMessage Invoke(IMessage reqMsg)
        {
            AssertValid();
            IMessage retMsg = null;

            // CHECK FOR CTOR
            if (reqMsg is IConstructionCallMessage)
            {
                DBG.Info(DBG.SC, "RSCP: Short circuiting constructor call.");

                if (((IConstructionCallMessage)reqMsg).ArgCount > 0)
                {
                    throw new ServicedComponentException(Resource.FormatString("ServicedComponentException_ConstructorArguments"));
                }

                // WE don't need dispatch the constructor message, the default .ctor is called
                // by CoCI
                // Create the return message
                MarshalByRefObject retObj = (MarshalByRefObject)GetTransparentProxy();
                return(EnterpriseServicesHelper.CreateConstructionReturnMessage((IConstructionCallMessage)reqMsg, retObj));
            }

            // NON CTOR MESSAGE
            MethodBase mb = ((IMethodMessage)reqMsg).MethodBase;
            MemberInfo m  = (MemberInfo)mb;

            DBG.Assert(m != null, "member info should not be null");

            if (mb == _getTypeMethod)
            {
                DBG.Info(DBG.SC, "RSCP: Hijacking call to GetType");
                IMethodCallMessage mcm = (IMethodCallMessage)reqMsg;
                return(new ReturnMessage(ProxiedType, null, 0, mcm.LogicalCallContext, mcm));
            }

            if (mb == _getHashCodeMethod)
            {
                int hashCode = this.GetHashCode();
                DBG.Info(DBG.SC, "RSCP: Hijacking call to GetHashCode, returning " + hashCode);
                IMethodCallMessage mcm = (IMethodCallMessage)reqMsg;
                return(new ReturnMessage(hashCode, null, 0, mcm.LogicalCallContext, mcm));
            }

            DBG.Info(DBG.SC, "RSCP: Delivering call to " + mb.Name);

            // convert to class member info
            MemberInfo clsMemInfo = ReflectionCache.ConvertToClassMI(ProxiedType, m);

            DBG.Assert(!clsMemInfo.ReflectedType.IsInterface,
                       "Failed to convert interface member info to class member info");

            // dispatch the call
#if _DEBUG
            if (clsMemInfo != m)
            {
                DBG.Info(DBG.SC, "RSCP: converted interface to class call: " + clsMemInfo.Name);
            }
#endif

            try
            {
                int iMethodInfo;
                // check for rolebased security
                if (_fUseIntfDispatch ||
                    (((iMethodInfo = ServicedComponentInfo.MICachedLookup(clsMemInfo)) & ServicedComponentInfo.MI_HASSPECIALATTRIBUTES) != 0) ||
                    ((iMethodInfo & ServicedComponentInfo.MI_EXECUTEMESSAGEVALID) != 0)
                    )
                {
                    // role based security implies we dispatch through an interface
                    MemberInfo intfMemInfo = ReflectionCache.ConvertToInterfaceMI(m);
                    if (intfMemInfo == null)
                    {
                        throw new ServicedComponentException(Resource.FormatString("ServicedComponentException_SecurityMapping"));
                    }
                    //retMsg = EnterpriseServicesHelper.DispatchRemoteCall(reqMsg, intfMemInfo, _server);
                    MethodCallMessageWrapperEx msgex = new MethodCallMessageWrapperEx((IMethodCallMessage)reqMsg, (MethodBase)intfMemInfo);
                    retMsg = RemotingServices.ExecuteMessage((MarshalByRefObject)_server, (IMethodCallMessage)msgex);
                }
                else
                {
                    // check for AutoDone
                    bool fAutoDone = (iMethodInfo & ServicedComponentInfo.MI_AUTODONE) != 0;

                    String s = ComponentServices.ConvertToString(reqMsg);

                    IRemoteDispatch iremDisp = (IRemoteDispatch)_server;

                    String sret;
                    if (fAutoDone)
                    {
                        sret = iremDisp.RemoteDispatchAutoDone(s);
                    }
                    else
                    {
                        sret = iremDisp.RemoteDispatchNotAutoDone(s);
                    }
                    retMsg = ComponentServices.ConvertToReturnMessage(sret, reqMsg);
                }
            }
            catch (COMException e)
            {
                if (!(e.ErrorCode == Util.CONTEXT_E_ABORTED || e.ErrorCode == Util.CONTEXT_E_ABORTING))
                {
                    throw;
                }
                if (IsDisposeRequest(reqMsg))
                {
                    IMethodCallMessage mcm = reqMsg as IMethodCallMessage;
                    retMsg = new ReturnMessage(null, null, 0, mcm.LogicalCallContext, mcm);
                }
                else
                {
                    throw;
                }
            }

            // if disposing, we need to release this side of the world.
            if (IsDisposeRequest(reqMsg))
            {
                Dispose(true);
            }

            return(retMsg);
        }
Exemplo n.º 27
0
        public override IMessage Invoke(IMessage msg)
        {
            UseAopType         useAspect = 0;
            string             uselog    = "";
            IMethodCallMessage call      = (IMethodCallMessage)msg;

            //查询目标方法是否使用了启用AOP的MethodAopSwitcherAttribute
            foreach (Attribute attr in call.MethodBase.GetCustomAttributes(false))
            {
                MethodAopSwitcherAttribute mehodAopAttr = attr as MethodAopSwitcherAttribute;
                if (mehodAopAttr != null)
                {
                    useAspect = mehodAopAttr.UseAspect;
                    uselog    = mehodAopAttr.Userlog;
                    break;
                    //if (mehodAopAttr.UseAspect==1)
                    //{
                    //    useAspect = 1;
                    //    break;
                    //}
                }
            }

            if (useAspect == UseAopType.before)
            {
                this.PreProcess(msg);   //执行方法之前的操作
            }

            //如果触发的是构造函数,此时target的构建还未开始
            IConstructionCallMessage ctor = call as IConstructionCallMessage;

            if (ctor != null)
            {
                //获取最底层的默认真实代理
                RealProxy default_proxy = RemotingServices.GetRealProxy(this.target);

                default_proxy.InitializeServerObject(ctor);
                MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy(); //自定义的透明代理 this

                return(EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp));
            }
            if (useAspect == UseAopType.before)
            {
                //#region 若不想运行目标方法可以执行该代码,如果直接return null会导致异常发生
                //IMethodCallMessage callMsg = msg as IMethodCallMessage;
                //return new ReturnMessage(callMsg.InArgs, null, 0, null, callMsg);
                //#endregion

                #region 调用目标方法代码
                IMethodMessage result_msg;
                result_msg = RemotingServices.ExecuteMessage(this.target, call);
                return(result_msg);

                #endregion
            }
            else
            {
                #region 调用目标方法代码
                IMethodMessage result_msg;
                result_msg = RemotingServices.ExecuteMessage(this.target, call);
                object result = null;
                if (result_msg is ReturnMessage)
                {
                    result = (result_msg as ReturnMessage).ReturnValue;
                }
                //IMethodReturnMessage result_msg = RemotingServices.ExecuteMessage(this.target, call);
                #endregion
                if (useAspect == UseAopType.after)
                {
                    this.PostProcess(msg, result_msg, result, uselog);      //执行方法结束后的操作
                }
                return(result_msg);
            }
        }