示例#1
17
 public void PostProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg, MarshalByRefObject target)
 {
     _timer = (TimeWatcher)callMsg.Properties["codeTimer"];
     _timer.Finish();
 }
示例#2
0
		public MethodReturnDictionary (IMethodReturnMessage message) : base (message)
		{
			if (message.Exception == null)
				MethodKeys = InternalReturnKeys;
			else
				MethodKeys = InternalExceptionKeys;
		}
示例#3
0
 public static string GetExceptionName(IMethodReturnMessage returnedMessage)
 {
     if (returnedMessage.Exception != null) {
         return returnedMessage.Exception.GetType().ToString();
     }
     return "";
 }
        public void PostMethodExecutionProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
        {
            _stopwatch.Stop();

            //Console.WriteLine("Return value: {0}", retMsg.ReturnValue);
            //Console.WriteLine("Ticks consumed: {0}", _stopwatch.ElapsedTicks);
        }
 public MethodReturnMessageWrapper(IMethodReturnMessage msg) : base(msg)
 {
     this._msg = msg;
     this._args = this._msg.Args;
     this._returnValue = this._msg.ReturnValue;
     this._exception = this._msg.Exception;
 }
示例#6
0
 public static string GetExceptionMessage(IMethodReturnMessage returnedMessage)
 {
     if (returnedMessage.Exception != null) {
         return returnedMessage.Exception.Message;
     }
     return "";
 }
		public static void Write(Stream responseStream, IMethodReturnMessage methodReturnMessage)
		{
			var method = (MethodInfo)methodReturnMessage.MethodBase;

			var callContext = methodReturnMessage.LogicalCallContext;
			if ((callContext != null) && callContext.HasInfo)
			{
				Write(responseStream, BinaryFormatterHelper.SerializeObject(callContext), ProtobufMessageTags.CallContext);
			}

			var ex = methodReturnMessage.Exception;
			if (ex != null)
			{
				Write(responseStream, BinaryFormatterHelper.SerializeObject(ex), ProtobufMessageTags.Exception);
			}
			else
			{
				if (method.ReturnType != typeof(void))
				{
					var result = methodReturnMessage.ReturnValue;
					if (result != null)
					{
						Write(responseStream, result, ProtobufMessageTags.Result);
					}
				}

				Write(responseStream, method, IsResponseArgument, methodReturnMessage.Args);
			}
		}
示例#8
0
 protected void PostProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
 {
     Trace.WriteLine(String.Format("TracePostProcessor {0} Return:{1}", retMsg.MethodName, retMsg.ReturnValue));
     if (retMsg.OutArgCount > 0) Trace.WriteLine(String.Format("Out Argument Count {0}",retMsg.OutArgCount));
     for (int idx = 0; idx < retMsg.OutArgCount; idx++)
     {
         Trace.WriteLine(String.Format("{0}={1}", retMsg.GetOutArgName(idx), retMsg.GetOutArg(idx)));
     }
 }
        public void SetNewReturnValue(object newReturnValue)
        {
            IMethodReturnMessage message = this.methodCallReturnMessage;
            if(message==null)
            {
                return ;
            }

            ReturnMessage newReturnMessage = new ReturnMessage(newReturnValue,message.OutArgs,message.OutArgCount,message.LogicalCallContext,this.MethodCallMessage);
            this.MethodCallReturnMessage = newReturnMessage;
        }
 private static void ExecuteAfterStrategy(IMethodCallMessage callMsg, ref IMethodReturnMessage rtnMsg)
 {
     var types =
         callMsg.MethodBase.GetCustomAttributes(typeof(InterceptHandlerAttribute), true)
             .Where(w => ((InterceptHandlerAttribute)w).InterceptType == InterceptType.After)
             .Select(s => ((InterceptHandlerAttribute)s).StartegyType).ToArray();
     foreach (var startegy in StartegyFactory.CreateAfterStartegyFactory(callMsg,rtnMsg,types))
     {
         startegy.Execute();
     }
 }
		private object GetProxy(IMethodReturnMessage message)
		{
			string key = message.MethodName;

			if (!Proxies.Contains(key))
			{
				Proxies.Add(key, CreateProxy(message));
			}

			return Proxies[key];
		}
	internal MethodResponse(IMethodReturnMessage mrm)
			{
				outArgs = mrm.OutArgs;
				methodName = mrm.MethodName;
				typeName = mrm.TypeName;
				uri = mrm.Uri;
				hasVarArgs = mrm.HasVarArgs;
				context = mrm.LogicalCallContext;
				method = mrm.MethodBase;
				exception = mrm.Exception;
				returnValue = mrm.ReturnValue;
			}
        public void Process(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
        {
            Exception e = retMsg.Exception;
            if (e != null)
            {
                this.HandleException(e);

                Exception newException = this.GetNewException(e);
                if (!object.ReferenceEquals(e, newException))
                    retMsg = new ReturnMessage(newException, callMsg);
            }
        }
		public MethodReturnMessageWrapper (IMethodReturnMessage msg)
			: base (msg)
		{
			if (msg.Exception != null) {
				_exception = msg.Exception;
				_args = new object[0];
			} else {
				_args = msg.Args;
				_return = msg.ReturnValue;
				if (msg.MethodBase != null)
					_outArgInfo = new ArgInfo (msg.MethodBase, ArgInfoType.Out);
			}
		}
示例#15
0
 public static string FormatReturnMessage(IMethodCallMessage callMsg,  IMethodReturnMessage retMsg)
 {
     string message = String.Format("Trace {0}.{1} Return:{2}", retMsg.MethodBase.DeclaringType.FullName, retMsg.MethodName, retMsg.ReturnValue) + System.Environment.NewLine;
     if (retMsg.OutArgCount > 0)
     {
         message += String.Format("Out Argument Count {0}", retMsg.OutArgCount) + System.Environment.NewLine;
         for (int idx = 0; idx < retMsg.OutArgCount; idx++)
         {
             message += String.Format("{0} = {1}", retMsg.GetOutArgName(idx), retMsg.GetOutArg(idx)) + System.Environment.NewLine;
         }
     }
     return message;
 }
示例#16
0
        internal static IMessage CheckReturnMessage(IMessage callMsg, IMessage retMsg)
        {
            IMethodReturnMessage ret = retMsg as IMethodReturnMessage;

            if (ret != null && ret.Exception != null)
            {
                if (RemotingConfiguration.CustomErrorsEnabled(IsLocalCall(callMsg)))
                {
                    Exception ex = new Exception("Server encountered an internal error. For more information, turn off customErrors in the server's .config file.");
                    retMsg = new MethodResponse(ex, (IMethodCallMessage)callMsg);
                }
            }
            return(retMsg);
        }
示例#17
0
        /// <summary>
        /// A helper function that retrieves custom method attributes and handles a return method
        /// exception based on the custom attribute properties.
        /// </summary>
        /// <param name="msgRet">
        /// The return message information that contains the exception to handle.
        /// </param>
        protected void HandleMessageException(IMethodReturnMessage msgRet)
        {
            // Get the method information for the method that was originally called.
            Type       calledType   = Type.GetType(msgRet.TypeName);
            MethodInfo calledMethod = calledType.GetMethod(msgRet.MethodName);

            // Retrieve the ExceptionMethodContextAttribute attribute, if present.  Do not search
            // down to the base class for inherited attributes.
            Object[] customAttributes = calledMethod.GetCustomAttributes(
                typeof(ExceptionMethodContextAttribute), false);

            // Skip out if the attribute does not exist for the method.
            if (customAttributes.Length == 0)
            {
                return;
            }

            // Perform a casting operation to get the type that we need to check.
            Debug.Assert(customAttributes[0].GetType() == typeof(ExceptionMethodContextAttribute));
            ExceptionMethodContextAttribute emca = (ExceptionMethodContextAttribute)customAttributes[0];

            // Write to the event log if attributed to do so.
            if (emca.WriteToEventLog)
            {
                EventLog.WriteEntry("Application", String.Format("Exception thrown: {0}",
                                                                 msgRet.Exception.ToString()));
            }

            // Remove the exception from the return message if attributed to do so.
            if (emca.SwallowException)
            {
                // WARNING: This uses reflection to wipe out a reference in a private variable.  Since
                // the variable is not documented, it could change in future releases of the .NET
                // Framework.  As much as I wanted to get around having to do this, I could not find
                // any other way at this time.
                Type      rmType      = Type.GetType("System.Runtime.Remoting.Messaging.ReturnMessage");
                FieldInfo rmException = rmType.GetField("_e", BindingFlags.NonPublic | BindingFlags.Instance);
                if (rmException != null)
                {
                    rmException.SetValue(msgRet, null);
                }

                // Update the default return value when the exception is swallowed using reflection.
                FieldInfo rmReturnValue = rmType.GetField("_ret", BindingFlags.NonPublic | BindingFlags.Instance);
                if (rmReturnValue != null)
                {
                    rmReturnValue.SetValue(msgRet, emca.ExceptionReturnValue);
                }
            }
        }
示例#18
0
        /// <summary>
        /// Defined by the IMessageSink interface.  Synchronously processes the given message for
        /// an asynchronous server call.
        /// </summary>
        /// <param name="msg">
        /// The message to process.
        /// </param>
        /// <returns>
        /// A reply message in response to the request.
        /// </returns>
        public IMessage AsyncCallback(IMessage msg)
        {
            // Cast the return message to a ReturnMessage object.
            IMethodReturnMessage rmReturn = (IMethodReturnMessage)msg;

            // Keep processing only if the return message has an exception associated with it.
            if (rmReturn.Exception != null)
            {
                HandleMessageException(rmReturn);
            }

            // Pass the message back up the chain.
            return(msg);
        }
        private IMessage Call(IMessage msg)
        {
            IMethodReturnMessage methodReturn = null;
            IMethodCallMessage   methodCall   = (IMethodCallMessage)msg;
            IService             channel      = default(IService);

            try
            {
                var factory = WCFHelper.CreateChannelFactory <IService>(registryInformation);
                channel = factory.CreateChannel();
                object[] copiedArgs = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[];
                methodCall.Args.CopyTo(copiedArgs, 0);
                object returnValue = methodCall.MethodBase.Invoke(channel, copiedArgs);
                methodReturn = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, methodCall.LogicalCallContext, methodCall);
            }
            catch (Exception ex)
            {
                var exception = ex;
                if (ex.InnerException != null)
                {
                    exception = ex.InnerException;
                }
                methodReturn = new ReturnMessage(exception, methodCall);
            }
            finally
            {
                var commObj = channel as ICommunicationObject;
                if (commObj != null)
                {
                    try
                    {
                        commObj.Close();
                    }
                    catch (CommunicationException)
                    {
                        commObj.Abort();
                    }
                    catch (TimeoutException)
                    {
                        commObj.Abort();
                    }
                    catch (Exception)
                    {
                        commObj.Abort();
                    }
                }
            }
            return(methodReturn);
        }
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage callMsg = msg as IMethodCallMessage;

            if (callMsg != null)
            {
                IMethodReturnMessage resultMsg = InvokeMethod(callMsg);

                return(resultMsg);
            }
            else
            {
                throw new NotSupportedException();
            }
        }
示例#21
0
        private void PostProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage rtnMsg)
        {
            string     methodName = callMsg.MethodName;
            MethodInfo method     = sourceType.GetMethods().Where(a => a.Name == methodName).FirstOrDefault();

            if (method.IsNull())
            {
                return;
            }
            object[] attrs = method.GetCustomAttributes(typeof(AspectProcessorAttribute), true);
            foreach (AspectProcessorAttribute a in attrs)
            {
                a.PostProcess(callMsg, ref rtnMsg);
            }
        }
示例#22
0
 /// <summary>
 /// Set the result of the call by it's return message.
 /// </summary>
 public virtual void SetResult(IMethodReturnMessage returnmsg)
 {
     if (returnmsg.Exception != null)
     {
         this.SetExceptionResult(returnmsg.Exception);
     }
     else if (this.IsConstructorCall)
     {
         this.SetConstructionResult(callee.InstanceName, returnmsg.OutArgs);
     }
     else
     {
         this.SetCallResult(returnmsg.ReturnValue, returnmsg.OutArgs);
     }
 }
示例#23
0
        public void Postprocess(MarshalByRefObject inst, IMessage msg, ref IMessage msgReturn)
        {
            IMethodCallMessage   lMsgIn  = msg as IMethodCallMessage;
            IMethodReturnMessage lMsgOut = msgReturn as IMethodReturnMessage;

            // Extract Server
            ONServer lServer = inst as ONServer;

            // Throw triggers
            lServer.OnContext.ThrowAcceptedTriggers();

            // Pop the OID from Class Stack
            lServer.OnContext.OperationStack.Pop();
            mInStack = false;
        }
        public void Process(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
        {
            Exception e = retMsg.Exception;

            if (e != null)
            {
                this.HandleException(e);

                Exception newException = this.GetNewException(e);
                if (!object.ReferenceEquals(e, newException))
                {
                    retMsg = new ReturnMessage(newException, callMsg);
                }
            }
        }
示例#25
0
        public void PostProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg, MarshalByRefObject target)
        {
            Type type = target.GetType();
            MethodInfo mi = type.GetMethod("UpdateSetting");
            if (mi == null) return;
            Settings = (Dictionary<string, string>)callMsg.Properties["_settings"];
            if (Settings != null)
            {
                foreach (KeyValuePair<string, string> setting in Settings)
                {
                    mi.Invoke(target, new object[] { setting.Key, setting.Value });
                }

            }
        }
示例#26
0
        public virtual IMessage SyncProcessMessage(IMessage msg)
        {
            IMethodCallMessage   reqMsg = (IMethodCallMessage)msg;
            IMethodReturnMessage methodReturnMessage = RemotingServices.ExecuteMessage(this._comObject, reqMsg);

            if (methodReturnMessage != null)
            {
                COMException comException = methodReturnMessage.Exception as COMException;
                if (comException != null && (comException._HResult == -2147023174 || comException._HResult == -2147023169))
                {
                    this._comObject     = (MarshalByRefObject)Activator.CreateInstance(this._serverType, true);
                    methodReturnMessage = RemotingServices.ExecuteMessage(this._comObject, reqMsg);
                }
            }
            return((IMessage)methodReturnMessage);
        }
        /// <summary>
        /// Synchronously processes the given message.
        /// </summary>
        /// <param name="msg">The message to process.</param>
        /// <returns>
        /// A reply message in response to the request.
        /// </returns>
        /// <exception cref="T:System.Security.SecurityException">
        /// The immediate caller makes the call through a reference to the interface and does not have infrastructure permission.
        /// </exception>
        public IMessage SyncProcessMessage(IMessage msg)
        {
            IMethodMessage methodMessage = (IMethodMessage)msg;

            if (methodMessage.MethodName == ".ctor")
            {
                IMethodReturnMessage ret = (IMethodReturnMessage)_nextSink.SyncProcessMessage(msg);
                _realObject = (ObjRef)ret.ReturnValue;
                return(ret);
            }
            else
            {
                AspectOrientedObject obj = (AspectOrientedObject)RemotingServices.Unmarshal(_realObject);
                return(obj.SyncProcessMessage(_nextSink, msg));
            }
        }
        private void SerializeResponse(IServerResponseChannelSinkStack sinkStack, IMessage msg, bool bClientIsClr, ref ITransportHeaders headers, out Stream stream)
        {
            BaseTransportHeaders headers2 = new BaseTransportHeaders();

            if (headers != null)
            {
                foreach (DictionaryEntry entry in headers)
                {
                    headers2[entry.Key] = entry.Value;
                }
            }
            headers = headers2;
            headers2.ContentType = "text/xml; charset=\"utf-8\"";
            if (this._protocol == Protocol.Http)
            {
                IMethodReturnMessage message = msg as IMethodReturnMessage;
                if ((message != null) && (message.Exception != null))
                {
                    headers["__HttpStatusCode"]   = "500";
                    headers["__HttpReasonPhrase"] = "Internal Server Error";
                }
            }
            bool flag = false;

            stream = sinkStack.GetResponseStream(msg, headers);
            if (stream == null)
            {
                stream = new ChunkedMemoryStream(CoreChannel.BufferPool);
                flag   = true;
            }
            bool bBashedUrl = CoreChannel.SetupUrlBashingForIisSslIfNecessary();

            CallContext.SetData("__ClientIsClr", bClientIsClr);
            try
            {
                CoreChannel.SerializeSoapMessage(msg, stream, this._includeVersioning);
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                CoreChannel.CleanupUrlBashingForIisSslIfNecessary(bBashedUrl);
            }
            if (flag)
            {
                stream.Position = 0L;
            }
        }
示例#29
0
 /// <summary>Wraps an <see cref="T:System.Runtime.Remoting.Messaging.IMethodReturnMessage" /> to create a <see cref="T:System.Runtime.Remoting.Messaging.MethodReturnMessageWrapper" />. </summary>
 /// <param name="msg">A message that acts as an outgoing method call on a remote object.</param>
 public MethodReturnMessageWrapper(IMethodReturnMessage msg) : base(msg)
 {
     if (msg.Exception != null)
     {
         this._exception = msg.Exception;
         this._args      = new object[0];
     }
     else
     {
         this._args   = msg.Args;
         this._return = msg.ReturnValue;
         if (msg.MethodBase != null)
         {
             this._outArgInfo = new ArgInfo(msg.MethodBase, ArgInfoType.Out);
         }
     }
 }
示例#30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public IMessage SyncProcessMessage(IMessage msg)
        {
            IMessage           retMsg = null;
            IMethodCallMessage call   = msg as IMethodCallMessage;

            if (call == null || (Attribute.GetCustomAttribute(call.MethodBase, typeof(TransactionMethodAttribute))) == null)
            {
                retMsg = nextSink.SyncProcessMessage(msg);
            }
            else
            {
                //此处换成自己的数据库连接
                using (SqlConnection Connect = new SqlConnection(ConfigurationManager.AppSettings["MySetting"]))
                {
                    Connect.Open();
                    SqlTransaction SqlTrans = Connect.BeginTransaction();

                    //讲存储存储在上下文
                    CallContext.SetData(TransactionAop.ContextName, SqlTrans);

                    //传递消息给下一个接收器 - > 就是指执行你自己的方法
                    retMsg = nextSink.SyncProcessMessage(msg);

                    if (SqlTrans != null)
                    {
                        IMethodReturnMessage methodReturn = retMsg as IMethodReturnMessage;
                        Exception            except       = methodReturn.Exception;

                        if (except != null)
                        {
                            SqlTrans.Rollback();
                            //可以做日志及其他处理
                        }
                        else
                        {
                            SqlTrans.Commit();
                        }

                        SqlTrans.Dispose();
                        SqlTrans = null;
                    }
                }
            }

            return(retMsg);
        }
示例#31
0
        /// <summary>
        /// Defined by the IMessageSink interface.  Synchronously processes the given message.
        /// </summary>
        /// <param name="msg">
        /// The message to process.
        /// </param>
        /// <returns>
        /// A reply message in response to the request.
        /// </returns>
        public IMessage SyncProcessMessage(IMessage msg)
        {
            // Get the return message by passing the processing down the chain.
            IMessage msgRet = _NextSink.SyncProcessMessage(msg);

            // Cast the return message to a ReturnMessage object.
            IMethodReturnMessage rmReturn = (IMethodReturnMessage)msgRet;

            // Keep processing only if the return message has an exception associated with it.
            if (rmReturn.Exception != null)
            {
                HandleMessageException(rmReturn);
            }

            // Pass the message back up the chain.
            return(msgRet);
        }
示例#32
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);
        }
示例#33
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);
        }
 private void PostMethodExecution(IMethodCallMessage callMsg, ref IMethodReturnMessage rtnMsg)
 {
     try {
         PostMethodExecutionAttribute[] attrs =
             (PostMethodExecutionAttribute[])
             callMsg.MethodBase.GetCustomAttributes(typeof(PostMethodExecutionAttribute), true);
         for (int i = 0; i < attrs.Length; i++)
         {
             attrs[i].MethodCallHandler.Process(callMsg, ref rtnMsg);
         }
     }
     catch (Exception e)
     {
         SeleniumLog log = SeleniumLog.Instance();
         log.Warning().WriteLine("SeleniumLog Exception: 01-13 - " + e.Message);
     }
 }
 public void Process(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
 {
     if (_enabled)
     {
         SeleniumLog log = SeleniumLog.Instance();
         try
         {
             //_stopwatch.Stop();
             log.Blue().WriteLine(string.Format("Return value: {0}", retMsg.ReturnValue));
             log.RestoreIndent("__SELENIUMLOG_INDENT__");
         }
         catch (Exception e)
         {
             log.Warning().WriteLine("SeleniumLog Exception: 01-05 - " + e.Message);
         }
     }
 }
示例#36
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);
        }
示例#37
0
        private void PostProcess(IMessage msg, IMessage msgReturn)
        {
            // 处理返回方法调用时的接口
            if (!(msg is IMethodMessage) ||
                !(msgReturn is IMethodReturnMessage))
            {
                return;
            }
            if (!FilterMethodName(msg))
            {
                return;
            }
            IMethodReturnMessage retMsg = (IMethodReturnMessage)msgReturn;
            string    logText           = "PostProcessing: ";
            Exception e = retMsg.Exception;

            if (e != null)
            {
                logText += "Exception was thrown: " + e;
                Logger.Log.Error(logText);
                return;
            }

            // 遍历输出参数
            logText += mTypeAndName + "(";
            if (retMsg.OutArgCount > 0)
            {
                logText += "out parameters[";
                for (int i = 0; i < retMsg.OutArgCount; ++i)
                {
                    if (i > 0)
                    {
                        logText += ", ";
                    }
                    logText += retMsg.GetOutArgName(i) + " = " +
                               retMsg.GetOutArg(i);
                }
                logText += "]";
            }
            if (retMsg.ReturnValue.GetType() != typeof(void))
            {
                logText += " returned [" + retMsg.ReturnValue + "]";
            }
            logText += " )";
            Logger.Log.Info(logText);
        }
示例#38
0
        /// <summary>
        /// Interceptorのチェーンの呼び出しを行います
        /// </summary>
        /// <param name="outArgumemnts">メソッドのout引数</param>
        /// <returns>メソッドの戻り値</returns>
        public object Proceed(out object[] outArgumemnts)
        {
            while (interceptIndex < interceptors.Length)
            {
                return(interceptors[interceptIndex++].Construct(this, out outArgumemnts));
            }

            IMethodReturnMessage ret = (IMethodReturnMessage)nextSink.SyncProcessMessage(message);

            outArgumemnts = ret.OutArgs;

            if (ret.Exception != null)
            {
                throw ret.Exception;
            }

            return(ret.ReturnValue);
        }
示例#39
0
 private void PostProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage rtnMsg)
 {
     PostProcessAttribute[] attrs
         = (PostProcessAttribute[])callMsg.MethodBase.GetCustomAttributes(typeof(PostProcessAttribute), true);
     for (int i = 0; i < attrs.Length; i++)
     {
         attrs[i].Processor.Process(callMsg, ref rtnMsg);
     }
     if (attrs.Length == 0)
     {
         ProcessAttribute[] pattrs
             = (ProcessAttribute[])callMsg.MethodBase.GetCustomAttributes(typeof(ProcessAttribute), true);
         for (int i = 0; i < pattrs.Length; i++)
         {
             pattrs[i].PostProcess(callMsg, ref rtnMsg);
         }
     }
 }
示例#40
0
        public Stream GetResponseStream(IMethodReturnMessage responseMsg, ITransportHeaders responseHeaders)
        {
            // transport signature
            _writer.Write(BinaryWireProtocol.ClientNameAndVersion);
            // operation opcode
            _writer.Write(BinaryWireProtocol.OperationType.Reply);
            // content length
            _writer.Write((Int32)(-1));
            // status code
            _writer.Write(BinaryWireProtocol.HeaderType.StatusCode);
            _writer.Write(responseMsg.Exception == null ? BinaryWireProtocol.StatusCode.Success : BinaryWireProtocol.StatusCode.ServerError);
            // response headers
            WriteHeaders(responseHeaders);

            // create stream for writing response
            _directAccess = true;
            return(new ChunkedWriteStream(_bufferedStream));
        }
示例#41
0
        public void Postprocess(MarshalByRefObject inst, IMessage msg, ref IMessage msgReturn)
        {
            IMethodCallMessage   lMsgIn  = msg as IMethodCallMessage;
            IMethodReturnMessage lMsgOut = msgReturn as IMethodReturnMessage;

            // Extract Server
            ONServer lServer = inst as ONServer;

            // Calculate OutputArgumets
            object[] lArgs = lMsgOut.Args;
            mServiceCacheItem.InvoqueOutboundArguments(lServer, lArgs);

            // Pop the OID from Class Stack
            lServer.OnContext.OperationStack.Pop();
            mInStack = false;

            msgReturn = new ReturnMessage(lMsgOut.ReturnValue, lArgs, lArgs.Length, lMsgOut.LogicalCallContext, lMsgIn);
        }
示例#42
0
        internal void DoCallBackGeneric(IntPtr targetCtxID, CrossContextDelegate deleg)
        {
            TransitionCall transitionCall = new TransitionCall(targetCtxID, deleg);

            Message.PropagateCallContextFromThreadToMessage((IMessage)transitionCall);
            IMessage msg = this.GetClientContextChain().SyncProcessMessage((IMessage)transitionCall);

            if (msg != null)
            {
                Message.PropagateCallContextFromMessageToThread(msg);
            }
            IMethodReturnMessage methodReturnMessage = msg as IMethodReturnMessage;

            if (methodReturnMessage != null && methodReturnMessage.Exception != null)
            {
                throw methodReturnMessage.Exception;
            }
        }
示例#43
0
        public virtual IMessage SyncProcessMessage(object o, IMessageSink sink, IMessage msg)
        {
            Begin(o, msg);
            IMethodReturnMessage returnedMessage = (IMethodReturnMessage)sink.SyncProcessMessage(msg);

            if (returnedMessage.Exception != null)
            {
                if (Error(returnedMessage.Exception, o, msg))
                {
                    returnedMessage = new MethodReturnMessageWrapper(returnedMessage)
                    {
                        Exception = null
                    };
                }
            }
            End(o, msg);
            return(returnedMessage);
        }
示例#44
0
        private static object[] ProcessResponse(IMethodReturnMessage mrm, MonoMethodMessage call)
        {
            MethodInfo methodInfo = (MethodInfo)call.MethodBase;

            if (mrm.ReturnValue != null && !methodInfo.ReturnType.IsInstanceOfType(mrm.ReturnValue))
            {
                throw new InvalidCastException("Return value has an invalid type");
            }
            int num;

            if (call.NeedsOutProcessing(out num))
            {
                ParameterInfo[] parameters = methodInfo.GetParameters();
                object[]        array      = new object[num];
                int             num2       = 0;
                foreach (ParameterInfo parameterInfo in parameters)
                {
                    if (parameterInfo.IsOut && !parameterInfo.ParameterType.IsByRef)
                    {
                        object obj = (parameterInfo.Position >= mrm.ArgCount) ? null : mrm.GetArg(parameterInfo.Position);
                        if (obj != null)
                        {
                            object arg = call.GetArg(parameterInfo.Position);
                            if (arg == null)
                            {
                                throw new RemotingException("Unexpected null value in local out parameter '" + parameterInfo.Name + "'");
                            }
                            RemotingServices.UpdateOutArgObject(parameterInfo, arg, obj);
                        }
                    }
                    else if (parameterInfo.ParameterType.IsByRef)
                    {
                        object obj2 = (parameterInfo.Position >= mrm.ArgCount) ? null : mrm.GetArg(parameterInfo.Position);
                        if (obj2 != null && !parameterInfo.ParameterType.GetElementType().IsInstanceOfType(obj2))
                        {
                            throw new InvalidCastException("Return argument '" + parameterInfo.Name + "' has an invalid type");
                        }
                        array[num2++] = obj2;
                    }
                }
                return(array);
            }
            return(new object[0]);
        }
示例#45
0
        internal static IMessage EndInvokeHelper(Message reqMsg, bool bProxyCase)
        {
            AsyncResult asyncResult = reqMsg.GetAsyncResult() as AsyncResult;
            IMessage    result      = null;

            if (asyncResult == null)
            {
                throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadAsyncResult"));
            }
            if (asyncResult.AsyncDelegate != reqMsg.GetThisPtr())
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MismatchedAsyncResult"));
            }
            if (!asyncResult.IsCompleted)
            {
                asyncResult.AsyncWaitHandle.WaitOne(-1, Thread.CurrentContext.IsThreadPoolAware);
            }
            AsyncResult obj = asyncResult;

            lock (obj)
            {
                if (asyncResult.EndInvokeCalled)
                {
                    throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EndInvokeCalledMultiple"));
                }
                asyncResult.EndInvokeCalled = true;
                IMethodReturnMessage methodReturnMessage = (IMethodReturnMessage)asyncResult.GetReplyMessage();
                if (!bProxyCase)
                {
                    Exception exception = methodReturnMessage.Exception;
                    if (exception != null)
                    {
                        throw exception.PrepForRemoting();
                    }
                    reqMsg.PropagateOutParameters(methodReturnMessage.Args, methodReturnMessage.ReturnValue);
                }
                else
                {
                    result = methodReturnMessage;
                }
                Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext.Merge(methodReturnMessage.LogicalCallContext);
            }
            return(result);
        }
示例#46
0
        private static object ParseResult(BinaryReader reader)
        {
            uint magic = reader.ReadUInt32();

            if (magic != 0x54454E2E)
            {
                throw new InvalidDataException("Invalid magic value");
            }

            reader.ReadByte();   // Major
            reader.ReadByte();   // Minor
            reader.ReadUInt16(); // Operation Type
            reader.ReadUInt16(); // Content distribution

            int len = reader.ReadInt32();

            ReadHeaders(reader);

            byte[] data = reader.ReadBytes(len);

            BinaryFormatter fmt = new BinaryFormatter();

            fmt.AssemblyFormat = FormatterAssemblyStyle.Simple;

            MemoryStream stm = new MemoryStream(data);

            IMethodReturnMessage ret = fmt.Deserialize(stm) as IMethodReturnMessage;

            if (ret != null)
            {
                if (ret.Exception != null)
                {
                    return(ret.Exception);
                }
                else
                {
                    return(ret.ReturnValue ?? "void");
                }
            }
            else
            {
                return("Error");
            }
        }
 public void PostMethodExecutionProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
 {
     SeleniumLog log = SeleniumLog.Instance();
     try
     {
         if (_enabled)
         {
             _stopwatch.Stop();
             log.Blue().WriteLine(string.Format("Return value: {0}", retMsg.ReturnValue));
             log.Blue().WriteLine(string.Format("Duration: {0} msec", _stopwatch.ElapsedMilliseconds));
             //log.RestoreIndent("__SELENIUMLOG_INDENT__");
             log.RestoreIndent("__PRE_METHOD_EXECUTION_PROCESS_1_");
         }
     }
     catch (Exception e)
     {
         log.Warning().WriteLine("SeleniumLog Exception: 01-02 - " + e.Message);
     }
 }
示例#48
0
        public void PostProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
        {
            if (_sessionInfo != null)
            {
                try
                {
                    //Get User Information
                    _sessionInfo.LastAccessTime = DateTime.Now;

                    //MongoDB Update(save)
                    new MongoDacHelper(_configSection, "test", _collectionName).Insert<SessionInfoT>(_sessionInfo);
                }

                catch
                {
                }
                finally
                {
                }
            }
        }
        /// <summary>
        /// Handles the exception.
        /// </summary>
        /// <param name="returnedMessage">The returned message.</param>
        /// <param name="exception">The exception.</param>
        /// <param name="data">The data.</param>
        /// <param name="removeException">if set to <c>true</c> [remove exception].</param>
        /// <returns>Exception.</returns>
        protected Exception HandleException(IMethodReturnMessage returnedMessage, Exception exception, object data, out bool removeException)
        {
            removeException = false;

            if (returnedMessage == null || exception == null)
            {
                return null;
            }

            var operationName = returnedMessage.MethodName;

            var newException = exception.Handle(data, operationName: operationName);

            if (!ThrowException)
            {
                removeException = true;
                Framework.ApiTracking?.LogException(newException.ToExceptionInfo());
            }

            return newException;
        }
		public object PostProcess(IMethodReturnMessage message)
		{
			if (message != null)
			{
				if (message.Exception != null)
				{
					throw message.Exception;
				}

				var returnValue = message.ReturnValue as IAsyncResult;

				if (returnValue == null)
				{
					throw new InvalidOperationException("Return value of the message is not of type IAsyncResult. " +
						"This indicate it's not a result of async operation.  This may also be a bug, so if you think it is, please report it.");
				}

				AsyncResult = returnValue;
			}

			return defaultReturn;
		}
        protected override void PostProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
        {
            var attributes = callMsg.MethodBase.GetCustomAttributes(typeof(CacheAttribute), false);

            if (attributes.Length > 0)
            {
                CacheAttribute cacheAttribute = (CacheAttribute)attributes[0];

                //if (cacheAttribute.IsRefreshNeeded && !string.IsNullOrEmpty(cacheAttribute.CachedObjectName))
                //{
                //    //DB 에서 서버 IP 리스트 조회
                //    foreach (ServerT server in new ServerBiz().GetServerList())
                //    {
                //        Task.Factory.StartNew(() =>
                //            {
                //                //각각의 서버의 Cache를 갱신
                //                HttpWebRequest request = WebRequest.Create(
                //                    string.Format(@"http://{0}/ClientBin/HRMS-Web-Services-CacheService.svc/binary/RefreshCachedObject?cachedObjectName={1}",
                //                        server.ServerIP, cacheAttribute.CachedObjectName
                //                        )
                //                    ) as HttpWebRequest;
                //                request.Host = "hrms.ebay.co.kr";
                //                WebResponse response;
                //                try
                //                {
                //                    response = request.GetResponse();
                //                    //HRMSContext.RefreshCachedObject(cacheAttribute.CachedObjectName);
                //                }
                //                catch(Exception ex)
                //                {
                //                    HRMSContext.RefreshCachedObject(cacheAttribute.CachedObjectName);
                //                    //new ServerBiz().RemoveServer(server.ServerIP);
                //                }
                //            });
                //    }
                //}
            }
        }
        public override void PostProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg, MarshalByRefObject target)
        {
            Exception e = retMsg.Exception;
            if (e != null)
            {
                List<string> infoList = new List<string>();
                string name = this.GetType().FullName;
                if (callMsg.Properties.Contains(name))
                {
                    infoList = (List<string>)callMsg.Properties[name];
                    callMsg.Properties.Remove(name);
                }
                foreach (string content in infoList)
                {
                    Trace.WriteLine(content);
                }
                this.HandleException(e);

                Exception newException = this.GetNewException(e);
                if (!object.ReferenceEquals(e, newException))
                    retMsg = new ReturnMessage(newException, callMsg);
            }
        }
示例#53
0
		/// <summary>
		/// Builds a method call return message based on an IMethodReturnMessage from the .NET framework.
		/// </summary>
		/// <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(IMethodReturnMessage returnMessage, IMethodCallMessage callMessage) {
			if (returnMessage.Exception != null) {
				return BuildReturnMessage(returnMessage.Exception, callMessage);
			} else {
				// Build arguments array:
				object[] arguments = new object[callMessage.ArgCount];
				// Fill with input arguments:
				int inargpos = 0;
				foreach(ParameterInfo param in callMessage.MethodBase.GetParameters()) {
					if (!param.IsOut) {
						arguments[param.Position] = callMessage.InArgs[inargpos++];
					}
				}
				// Fill with output arguments:
				int outargpos = 0;
				foreach(ParameterInfo param in returnMessage.MethodBase.GetParameters()) {
					if (param.ParameterType.IsByRef) {
						arguments[param.Position] = returnMessage.OutArgs[outargpos++];
					}
				}
				// Delegate to overloaded variant:
				return BuildReturnMessage(returnMessage.ReturnValue, arguments, callMessage);
			}
		}
示例#54
0
 /// <summary>
 /// Exits the specified method message.
 /// </summary>
 /// <param name="methodMessage">The method message.</param>
 /// <param name="exitStamp">The exit stamp.</param>
 internal static void Exit(IMethodReturnMessage methodMessage, DateTime? exitStamp = null)
 {
     _current?.FillExitInfo(methodMessage.Exception.ToExceptionInfo(), exitStamp ?? DateTime.UtcNow);
 }
示例#55
0
		static object[] ProcessResponse (IMethodReturnMessage mrm, MonoMethodMessage call)
		{
			// Check return type

			MethodInfo mi = (MethodInfo) call.MethodBase;
			if (mrm.ReturnValue != null && !mi.ReturnType.IsInstanceOfType (mrm.ReturnValue))
				throw new InvalidCastException ("Return value has an invalid type");

			// Check out parameters

			
			int no;
			
			if (call.NeedsOutProcessing (out no))
			{
				ParameterInfo[] parameters = mi.GetParameters();
				object[] outArgs = new object [no];
				int narg = 0;
	
				foreach (ParameterInfo par in parameters)
				{
					if (par.IsOut && !par.ParameterType.IsByRef)
					{
						// Special marshalling required
						object outArg = par.Position < mrm.ArgCount ? mrm.GetArg (par.Position) : null;
						if (outArg != null) {
							object local = call.GetArg (par.Position);
							if (local == null) throw new RemotingException ("Unexpected null value in local out parameter '" + par.Name + "'");
							RemotingServices.UpdateOutArgObject (par, local, outArg);
						}
					}
					else if (par.ParameterType.IsByRef)
					{
						object outArg = par.Position < mrm.ArgCount ? mrm.GetArg (par.Position) : null;
						if (outArg != null && !par.ParameterType.GetElementType ().IsInstanceOfType (outArg))
						{
							throw new InvalidCastException ("Return argument '" + par.Name + "' has an invalid type");
						}
						outArgs [narg++] = outArg;
					}
				}
				return outArgs;
			}
			else
				return new object [0];
		}
			public DictionaryWrapper(IMethodReturnMessage message, IDictionary wrappedDictionary) : base (message)
			{
				_wrappedDictionary = wrappedDictionary;
				MethodKeys = _keys;
			}
示例#57
0
		internal CADMethodReturnMessage(IMethodReturnMessage retMsg): base (retMsg) {
			ArrayList serializeList = null; 
			
			_propertyCount = MarshalProperties (retMsg.Properties, ref serializeList);

			_returnValue = MarshalArgument ( retMsg.ReturnValue, ref serializeList);
			_args = MarshalArguments ( retMsg.Args, ref serializeList);

			_sig = GetSignature (method, true);

			if (null != retMsg.Exception) {
				if (null == serializeList)
					serializeList = new ArrayList();
				
				_exception = new CADArgHolder (serializeList.Count);
				serializeList.Add(retMsg.Exception);
			}

			// Save callcontext
			SaveLogicalCallContext (retMsg, ref serializeList);

			if (null != serializeList) {
				MemoryStream stm = CADSerializer.SerializeObject (serializeList.ToArray());
				_serializedArgs = stm.GetBuffer();
			}
		}
示例#58
0
        [System.Security.SecurityCritical]  // auto-generated 
        private SmuggledMethodReturnMessage(IMethodReturnMessage mrm)
        {
            ArrayList argsToSerialize = null;
 
            ReturnMessage retMsg = mrm as ReturnMessage;
 
            // user properties (everything but special entries) 
            if ((retMsg == null) || retMsg.HasProperties())
                _propertyCount = StoreUserPropertiesForMethodMessage(mrm, ref argsToSerialize); 

            // handle exception
            Exception excep = mrm.Exception;
            if (excep != null) 
            {
                if (argsToSerialize == null) 
                    argsToSerialize = new ArrayList(); 
                _exception = new SerializedArg(argsToSerialize.Count);
                argsToSerialize.Add(excep); 
            }

            // handle call context
            LogicalCallContext lcc = mrm.LogicalCallContext; 
            if (lcc == null)
            { 
                _callContext = null; 
            }
            else 
            if (lcc.HasInfo)
            {
                if (lcc.Principal != null)
                    lcc.Principal = null; 

                if (argsToSerialize == null) 
                    argsToSerialize = new ArrayList(); 
                _callContext = new SerializedArg(argsToSerialize.Count);
                argsToSerialize.Add(lcc); 
            }
            else
            {
                // just smuggle the call id string 
                _callContext = lcc.RemotingData.LogicalCallID;
            } 
 
            _returnValue = FixupArg(mrm.ReturnValue, ref argsToSerialize);
            _args = FixupArgs(mrm.Args, ref argsToSerialize); 

            if (argsToSerialize != null)
            {
                MemoryStream argStm = CrossAppDomainSerializer.SerializeMessageParts(argsToSerialize); 
                //MemoryStream argStm = CrossAppDomainSerializer.SerializeMessageParts(argsToSerialize, out _serializerSmuggledArgs);
                _serializedArgs = argStm.GetBuffer(); 
            } 

        } // SmuggledMethodReturnMessage 
        [System.Security.SecurityCritical]  // auto-generated
        private Object[] WriteMethodReturn(IMethodReturnMessage mrm)
        {
            Object    returnValue = mrm.ReturnValue;
            Object[]  args = mrm.Args;
            Exception exception = mrm.Exception;
            Object callContext;
            Object[] properties = null;

            ReturnMessage retMsg = mrm as ReturnMessage;

            // user properties (everything but special entries)
            if ((retMsg == null) || retMsg.HasProperties())
                properties = StoreUserPropertiesForMethodMessage(mrm);

            // handle call context
            LogicalCallContext lcc = mrm.LogicalCallContext;
            if (lcc == null)
            {
                callContext = null;
            }
            else if (lcc.HasInfo)
                callContext = lcc;
            else
            {
                // just smuggle the call id string
                callContext = lcc.RemotingData.LogicalCallID;
            }

           return serWriter.WriteReturnArray(returnValue, args, exception, callContext, properties);
        }
 public static IEnumerable<IStartegy> CreateAfterStartegyFactory(IMethodCallMessage methodCallMessage, IMethodReturnMessage methodReturnMessage, params Type[] afterStartegies)
 {
     return afterStartegies.Select(baseAfterStartegy => Activator.CreateInstance(baseAfterStartegy, methodCallMessage, methodReturnMessage) as BaseAfterStartegy);
 }