public IMessage SyncProcessMessage(IMessage msg) { var mcm = (msg as IMethodCallMessage); var mrm = null as IMethodReturnMessage; var handler = ContextBoundObjectInterceptor.GetInterceptor(this.Target); if (handler != null) { var arg = new InterceptionArgs(this.Target, mcm.MethodBase as MethodInfo, mcm.Args); try { handler.Invoke(arg); if (arg.Handled == true) { mrm = new ReturnMessage(arg.Result, new object[0], 0, mcm.LogicalCallContext, mcm); } } catch (Exception ex) { mrm = new ReturnMessage(ex, mcm); } } if (mrm == null) { mrm = this.NextSink.SyncProcessMessage(msg) as IMethodReturnMessage; } return mrm; }
} // ObjectMode public virtual IMessage SyncProcessMessage(IMessage msg) { IMessage replyMsg = null; try { msg.Properties["__Uri"] = _realProxy.IdentityObject.URI; if (_objectMode == WellKnownObjectMode.Singleton) { replyMsg = _realProxy.Invoke(msg); } else { // This is a single call object, so we need to create // a new instance. MarshalByRefObject obj = (MarshalByRefObject)Activator.CreateInstance(_serverType, true); BCLDebug.Assert(RemotingServices.IsTransparentProxy(obj), "expecting a proxy"); RealProxy rp = RemotingServices.GetRealProxy(obj); replyMsg = rp.Invoke(msg); } } catch (Exception e) { replyMsg = new ReturnMessage(e, msg as IMethodCallMessage); } return replyMsg; } // SyncProcessMessage
public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg) { IMethodCallMessage mcMsg = msg as IMethodCallMessage; if (mcMsg != null) { ReturnMessage rlt = null; if (!string.Equals(mcMsg.MethodName, "Test", StringComparison.OrdinalIgnoreCase)) { object instance = null; if (Entity == null) { Type type = Type.GetType(mcMsg.TypeName); instance = Activator.CreateInstance(type); } else { instance = Entity; } object returnValueObject = mcMsg.MethodBase.Invoke(instance, null); rlt = new ReturnMessage(returnValueObject, mcMsg.Args, mcMsg.ArgCount, mcMsg.LogicalCallContext, mcMsg); } else { rlt = new ReturnMessage(new ProxyResult(), mcMsg.Args, mcMsg.ArgCount, mcMsg.LogicalCallContext, mcMsg); } return rlt; } return null; }
public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg) { if (msg is IConstructionCallMessage) // 如果是构造函数,按原来的方式返回即可。 { IConstructionCallMessage constructCallMsg = msg as IConstructionCallMessage; IConstructionReturnMessage constructionReturnMessage = this.InitializeServerObject((IConstructionCallMessage)msg); RealProxy.SetStubData(this, constructionReturnMessage.ReturnValue); return constructionReturnMessage; } else if (msg is IMethodCallMessage) //如果是方法调用(属性也是方法调用的一种) { IMethodCallMessage callMsg = msg as IMethodCallMessage; object[] args = callMsg.Args; IMessage message; try { if (callMsg.MethodName.StartsWith("set_") && args.Length == 1) { method.Invoke(GetUnwrappedServer(), new object[] { callMsg.MethodName.Substring(4)}); } object o = callMsg.MethodBase.Invoke(GetUnwrappedServer(), 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 SyncProcessMessage (IMessage msg) { ServerIdentity identity = (ServerIdentity) RemotingServices.GetMessageTargetIdentity (msg); Context oldContext = null; IMessage response; if (Threading.Thread.CurrentContext != identity.Context) oldContext = Context.SwitchToContext (identity.Context); try { Context.NotifyGlobalDynamicSinks (true, msg, false, false); Thread.CurrentContext.NotifyDynamicSinks (true, msg, false, false); response = identity.Context.GetServerContextSinkChain().SyncProcessMessage (msg); Context.NotifyGlobalDynamicSinks (false, msg, false, false); Thread.CurrentContext.NotifyDynamicSinks (false, msg, false, false); } catch (Exception ex) { response = new ReturnMessage (ex, (IMethodCallMessage)msg); } finally { if (oldContext != null) Context.SwitchToContext (oldContext); } return response; }
/// <summary> /// 函数消息 /// </summary> /// <param name="msg"></param> /// <returns></returns> public override IMessage Invoke(IMessage msg) { IMessage message; var callMessage = msg as IConstructionCallMessage; if (callMessage != null) { message = InitializeServerObject(callMessage); if (message != null) { SetStubData(this, ((IConstructionReturnMessage)message).ReturnValue); } } else { var callMsg = (IMethodCallMessage)msg; var attributes = serverType.GetMethod(callMsg.MethodName).GetCustomAttributes(false); var args = callMsg.Args; try { OnBegin(attributes, callMsg); var ret = callMsg.MethodBase.Invoke(GetUnwrappedServer(), args); OnComplete(attributes, ref ret, callMsg); message = new ReturnMessage(ret, args, args.Length, callMsg.LogicalCallContext, callMsg); } catch (Exception e) { OnException(attributes, e.InnerException, callMsg); message = new ReturnMessage(e.InnerException, callMsg); } } return message; }
private IMessage DeserializeMessage(IMethodCallMessage mcm, ITransportHeaders headers, Stream stream) { IMessage message; string str2; string str3; Header[] h = new Header[] { new Header("__TypeName", mcm.TypeName), new Header("__MethodName", mcm.MethodName), new Header("__MethodSignature", mcm.MethodSignature) }; string contentType = headers["Content-Type"] as string; HttpChannelHelper.ParseContentType(contentType, out str2, out str3); if (string.Compare(str2, "text/xml", StringComparison.Ordinal) == 0) { message = CoreChannel.DeserializeSoapResponseMessage(stream, mcm, h, this._strictBinding); } else { int count = 0x400; byte[] buffer = new byte[count]; StringBuilder builder = new StringBuilder(); for (int i = stream.Read(buffer, 0, count); i > 0; i = stream.Read(buffer, 0, count)) { builder.Append(Encoding.ASCII.GetString(buffer, 0, i)); } message = new ReturnMessage(new RemotingException(builder.ToString()), mcm); } stream.Close(); return message; }
public override IMessage Invoke(IMessage msg) { using (var client = WcfServiceClientFactory.CreateServiceClient<IWcfLogService>()) { var channel = client.Channel; IMethodCallMessage methodCall = (IMethodCallMessage)msg; IMethodReturnMessage methodReturn = null; object[] copiedArgs = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[]; methodCall.Args.CopyTo(copiedArgs, 0); try { object returnValue = methodCall.MethodBase.Invoke(channel, copiedArgs); methodReturn = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, methodCall.LogicalCallContext, methodCall); } catch (Exception ex) { if (ex.InnerException != null) { LocalLogService.Log(ex.InnerException.ToString()); methodReturn = new ReturnMessage(ex.InnerException, methodCall); } else { LocalLogService.Log(ex.ToString()); methodReturn = new ReturnMessage(ex, methodCall); } } return methodReturn; } }
/* * Checks the replySink param for NULL and type. * If the param is good, it returns NULL. * Else it returns a Message with the relevant exception. */ internal static IMessage ValidateMessage(IMessage reqMsg) { IMessage retMsg = null; if (reqMsg == null) { retMsg = new ReturnMessage( new ArgumentNullException("reqMsg"), null); } return retMsg; }
/// <summary> /// Proxy method for substitution of executing methods in adapter interface. /// </summary> /// <param name="methodCall">The IMessage containing method invoking data.</param> /// <returns>The IMessage containing method return data.</returns> protected override IMessage Invoke(IMethodCallMessage methodCall) { ReturnMessage mret = null; // Check if this is a method from IAdapter. Any IAdapter methods should be ignored. if ((methodCall.MethodBase.DeclaringType.FullName != typeof(IAdapter).FullName) && (methodCall.MethodBase.DeclaringType.FullName != typeof(IDisposable).FullName) ) { TestSite.Log.Add(LogEntryKind.EnterAdapter, "Interactive adapter: {0}, method: {1}", ProxyType.Name, methodCall.MethodName); try { // Instantiate a new UI window. using (InteractiveAdapterDialog adapterDlg = new InteractiveAdapterDialog(methodCall, TestSite.Properties)) { DialogResult dialogResult = adapterDlg.ShowDialog(); if (dialogResult != DialogResult.OK) { string msg = "Failed"; TestSite.Assume.Fail(msg); } else { mret = new ReturnMessage( adapterDlg.ReturnValue, adapterDlg.OutArgs.Length > 0 ? adapterDlg.OutArgs : null, adapterDlg.OutArgs.Length, methodCall.LogicalCallContext, methodCall); } } } catch (Exception ex) { TestSite.Log.Add(LogEntryKind.Debug, ex.ToString()); throw; } finally { TestSite.Log.Add(LogEntryKind.ExitAdapter, "Interactive adapter: {0}, method: {1}", ProxyType.Name, methodCall.MethodName); } } else { // TODO: Do we need to take care ReturnMessage (Exception, IMethodCallMessage) ? mret = new ReturnMessage(null, null, 0, methodCall.LogicalCallContext, methodCall); } return mret; }
public override IMessage Invoke(IMessage message) { IMessage result = null; IMethodCallMessage methodCall = message as IMethodCallMessage; MethodInfo method = methodCall.MethodBase as MethodInfo; // Invoke if (result == null) { if (proxyTarget != null) { Console.WriteLine("proxy going to invoke: {0}", method.Name); object callResult; object actualresult; bool make_proxy = true; if (method.ReturnType.IsInterface) { actualresult = method.Invoke(proxyTarget, methodCall.InArgs); if (method.ReturnType.IsGenericType) { // Console.WriteLine("** return value is generic type: {0}", method.ReturnType.GetGenericTypeDefinition()); if (method.ReturnType.GetGenericTypeDefinition() == (typeof(IEnumerator<>))) { Console.WriteLine("** method returning IEnumerator<>, making BatchProxy"); Type[] args = method.ReturnType.GetGenericArguments(); Type srvbatchtype = typeof(EnumeratorServerBatch<>).MakeGenericType(args); object srv = Activator.CreateInstance(srvbatchtype, actualresult); Type clbatchtype = typeof(EnumeratorClientBatch<>).MakeGenericType(args); object client = Activator.CreateInstance(clbatchtype, srv); make_proxy = false; actualresult = client; } } if (make_proxy) { var newproxy = new MyProxy(method.ReturnType, actualresult); callResult = newproxy.GetTransparentProxy(); } else { callResult = actualresult; } } else { callResult = method.Invoke(proxyTarget, methodCall.InArgs); } Console.WriteLine("proxy done Invoking: {0}", method.Name); LogicalCallContext context = methodCall.LogicalCallContext; result = new ReturnMessage(callResult, null, 0, context, message as IMethodCallMessage); } else { NotSupportedException exception = new NotSupportedException("proxyTarget is not defined"); result = new ReturnMessage(exception, message as IMethodCallMessage); } } return result; }
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; }
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); } }
protected void FlagCurrentMethodToBeSkipped(ProcessEventArgs args) { IMethodCallMessage methodCallMessage = args.MethodCallMessage; ReturnMessage customMessage = new ReturnMessage( 1, new object[]{}, 0, methodCallMessage.LogicalCallContext, methodCallMessage); methodCallMessage.LogicalCallContext.SetData("CustomReturnMessage",customMessage) ; }
public override IMessage Invoke(IMessage msg) { IMethodReturnMessage methodReturn = null; IMethodCallMessage methodCall = (IMethodCallMessage)msg; var client = ConfigServiceClientFactory.CreateServiceClient(); var channel = client.CreateChannel(); try { 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(); throw; } } } return methodReturn; }
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); }
public IMessage SyncProcessMessage(IMessage msg) { var mcm = (msg as IMethodCallMessage); IMessage rtnMsg = null; try { ExecuteBeforeStrategy(ref mcm); } catch (Exception exception) { var returnMessage = new ReturnMessage(exception,mcm) as IMethodReturnMessage; ExecuteAfterStrategy(mcm, ref returnMessage); return returnMessage; } rtnMsg = _nextSink.SyncProcessMessage(msg); var methodReturnMessage = (rtnMsg as IMethodReturnMessage); ExecuteAfterStrategy(mcm, ref methodReturnMessage); return (rtnMsg as IMethodReturnMessage); }
public override IMessage Invoke( IMessage msg ) { IMethodCallMessage call = (IMethodCallMessage)msg; IMethodReturnMessage result = null; if ( call != null ) { try { object ret = callHandler.Call( call.MethodName, call.Args ); if ( ret == null ) { MethodInfo info = call.MethodBase as MethodInfo; Type returnType = info.ReturnType; if( returnType == typeof( System.Boolean ) ) ret = false; if( returnType == typeof( System.Byte ) ) ret = (System.Byte)0; if( returnType == typeof( System.SByte ) ) ret = (System.SByte)0; if( returnType == typeof( System.Decimal ) ) ret = (System.Decimal)0; if( returnType == typeof( System.Double ) ) ret = (System.Double)0; if( returnType == typeof( System.Single ) ) ret = (System.Single)0; if( returnType == typeof( System.Int32 ) ) ret = (System.Int32)0; if( returnType == typeof( System.UInt32 ) ) ret = (System.UInt32)0; if( returnType == typeof( System.Int64 ) ) ret = (System.Int64)0; if( returnType == typeof( System.UInt64 ) ) ret = (System.UInt64)0; if( returnType == typeof( System.Int16 ) ) ret = (System.Int16)0; if( returnType == typeof( System.UInt16 ) ) ret = (System.UInt16)0; if( returnType == typeof( System.Char ) ) ret = '?'; } result = new ReturnMessage( ret, null, 0, null, call ); } catch( Exception e ) { result = new ReturnMessage( e, call ); } } return result; }
public IMessage SyncProcessMessage(IMessage msg) { if (msg is IMethodMessage) { var call = msg as IMethodMessage; var type = Type.GetType(call.TypeName); if (type != null) { //var key = call.TypeName + "." + call.MethodName; //var cached = CachingConfiguration.SystemRuntimeCachingProvider.Get<object>(key); //if (null == cached) //{ IMessage returnMethod = m_next.SyncProcessMessage(msg); if (!(returnMethod is IMethodReturnMessage)) return returnMethod; var retMsg = (IMethodReturnMessage)returnMethod; System.Exception e = retMsg.Exception; if (null == e) { if (retMsg.ReturnValue.GetType() != typeof (void)) { var methodMessage = (IMethodCallMessage)msg; var overrideReturnMethod = new ReturnMessage( (int)retMsg.ReturnValue * 2, methodMessage.Args, methodMessage.ArgCount, methodMessage.LogicalCallContext, methodMessage); return overrideReturnMethod; } } return returnMethod; //} //var methodMessage = (IMethodCallMessage)msg; //var overrideReturnMethod = new ReturnMessage(cached, methodMessage.Args, methodMessage.ArgCount, methodMessage.LogicalCallContext, methodMessage); //return overrideReturnMethod; } } return m_next.SyncProcessMessage(msg); }
// メソッド実行時 public override IMessage Invoke(IMessage message) { IMethodMessage myMethodMessage = (IMethodMessage)message; string LogString = myMethodMessage.MethodBase.ReflectedType + "." + myMethodMessage.MethodName + "(" + string.Join(", ", myMethodMessage.Args) + ")"; // 開始ログ LoggerEx.Trace(LogString + " : start"); object returnValue = myType.InvokeMember(myMethodMessage.MethodName, BindingFlags.InvokeMethod, null, myObjectInstance, myMethodMessage.Args); ReturnMessage myReturnMessage = new ReturnMessage(returnValue, null, 0, ((IMethodCallMessage)message).LogicalCallContext, (IMethodCallMessage)message); // 終了ログ LoggerEx.Trace(LogString + " : end"); return myReturnMessage; }
public IMessage SyncProcessMessage (IMessage msg) { IMethodCallMessage mcm = (IMethodCallMessage) msg; int timeout = -1; bool timedOut = false; RemotingService.CallbackData data = RemotingService.GetCallbackData (mcm.Uri, mcm.MethodName); if (data != null) { timeout = data.Timeout; if (data.Calling != null) { IMessage r = data.Calling (data.Target, mcm); if (r != null) return r; } } IMessage res = null; if (timeout != -1) { ManualResetEvent ev = new ManualResetEvent (false); ThreadPool.QueueUserWorkItem (delegate { res = ((IMessageSink)nextSink).SyncProcessMessage (msg); }); if (!ev.WaitOne (timeout, false)) { timedOut = true; res = new ReturnMessage (null, null, 0, mcm.LogicalCallContext, mcm); } } else { res = ((IMessageSink)nextSink).SyncProcessMessage (msg); } if (data != null && data.Called != null) { IMessage cr = data.Called (data.Target, mcm, res as IMethodReturnMessage, timedOut); if (cr != null) res = cr; } return res; }
public override IMessage Invoke(IMessage msg) { b += 1; if (msg is IConstructionCallMessage) { IConstructionCallMessage constructCallMsg = msg as IConstructionCallMessage; IConstructionReturnMessage constructionReturnMessage = this.InitializeServerObject(constructCallMsg); RealProxy.SetStubData(this, constructionReturnMessage.ReturnValue); return constructionReturnMessage; } else if (msg is IMethodCallMessage) { IMethodCallMessage callMsg = msg as IMethodCallMessage; object[] copiedArgs = Array.CreateInstance(typeof(object), callMsg.Args.Length) as object[]; callMsg.Args.CopyTo(copiedArgs, 0); //var copiedArgs = callMsg.Args; IMessage message; try { var taget = GetUnwrappedServer(); object returnValue; if (callMsg.MethodName.StartsWith("set_") && copiedArgs.Length == 1) { var method = _serverType.GetMethod("SetChanges", BindingFlags.NonPublic | BindingFlags.Instance); method.Invoke(taget, new object[] { callMsg.MethodName.Substring(4), copiedArgs[0] }); } returnValue = callMsg.MethodBase.Invoke(taget, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static, null, copiedArgs, null); message = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, callMsg.LogicalCallContext, callMsg); } catch (Exception e) { message = new ReturnMessage(e, callMsg); } return message; } return msg; }
private LogicalCallContext FetchLogicalCallContext() { ReturnMessage returnMessage = this._mrmsg as ReturnMessage; if (returnMessage != null) { return(returnMessage.GetLogicalCallContext()); } MethodResponse methodResponse = this._mrmsg as MethodResponse; if (methodResponse != null) { return(methodResponse.GetLogicalCallContext()); } StackBasedReturnMessage stackBasedReturnMessage = this._mrmsg as StackBasedReturnMessage; if (stackBasedReturnMessage != null) { return(stackBasedReturnMessage.GetLogicalCallContext()); } throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadType")); }
public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink) { IMethodCallMessage mcm = (IMethodCallMessage) msg; try { ITransportHeaders headers; Stream stream; this.SerializeMessage(mcm, out headers, out stream); ClientChannelSinkStack sinkStack = new ClientChannelSinkStack(replySink); sinkStack.Push(this, mcm); this._nextSink.AsyncProcessRequest(sinkStack, msg, headers, stream); } catch (Exception exception) { IMessage message2 = new ReturnMessage(exception, mcm); if (replySink != null) { replySink.SyncProcessMessage(message2); } } return null; }
public static IMessageCtrl AsyncDispatchMessage(IMessage msg, IMessageSink replySink) { IMessageCtrl ctrl = null; try { if (msg == null) { throw new ArgumentNullException("msg"); } IncrementRemoteCalls(); if (!(msg is TransitionCall)) { CheckDisconnectedOrCreateWellKnownObject(msg); } ctrl = GetCrossContextChannelSink().AsyncProcessMessage(msg, replySink); } catch (Exception exception) { if (replySink == null) { return ctrl; } try { IMethodCallMessage message = (IMethodCallMessage) msg; ReturnMessage message2 = new ReturnMessage(exception, (IMethodCallMessage) msg); if (msg != null) { message2.SetLogicalCallContext(message.LogicalCallContext); } replySink.SyncProcessMessage(message2); } catch (Exception) { } } return ctrl; }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { if (requestHeaders["SOAPAction"] != null) { // pass to next sink if this is a SOAP request with SOAPAction header. return NextChannelSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); } XmlRpcHttpRequestConfig requestConfig = GetConfig(requestHeaders); try { MethodCall call = DeserializeRequest(requestHeaders, requestStream, requestConfig); sinkStack.Push(this, call); // forward to next sink in chain - pass request stream as null to // indicate that we have deserialized the request NextChannelSink.ProcessMessage(sinkStack, call, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); SerializeResponse(responseMsg, ref responseHeaders, ref responseStream, requestConfig); } catch (Exception ex) { responseMsg = new ReturnMessage(ex, (IMethodCallMessage)requestMsg); responseStream = new MemoryStream(); XmlRpcResponseSerializer serializer = new XmlRpcResponseSerializer(); XmlRpcResponse faultResponse = new XmlRpcResponse(); faultResponse.Fault = new XmlRpcFault(0, ex.Message); serializer.WriteResponse(responseStream, faultResponse, requestConfig, TypeSerializerFactory); responseHeaders = new TransportHeaders(); responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\""; } return ServerProcessing.Complete; }
internal override void SetSpecialKey(int keyNum, object value) { ReturnMessage returnMessage = this._mrmsg as ReturnMessage; MethodResponse methodResponse = this._mrmsg as MethodResponse; if (keyNum != 0) { if (keyNum != 1) { throw new RemotingException(Environment.GetResourceString("Remoting_Default")); } if (returnMessage != null) { returnMessage.SetLogicalCallContext((LogicalCallContext)value); return; } if (methodResponse != null) { methodResponse.SetLogicalCallContext((LogicalCallContext)value); return; } throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadType")); } else { if (returnMessage != null) { returnMessage.Uri = (string)value; return; } if (methodResponse != null) { methodResponse.Uri = (string)value; return; } throw new RemotingException(Environment.GetResourceString("Remoting_Message_BadType")); } }
public override IMessage Invoke(IMessage msg) { IMethodCallMessage methodMessage = new MethodCallMessageWrapper((IMethodCallMessage)msg); var executeType = GetExecuteType(methodMessage); if (executeType != ExecuteType.None) profiler.ExecuteStart(instance, executeType); object returnValue = methodMessage.MethodBase.Invoke(instance, methodMessage.Args); if (executeType == ExecuteType.Reader) returnValue = new ProfiledDbDataReader((DbDataReader)returnValue, instance.Connection, profiler); IMessage returnMessage = new ReturnMessage(returnValue, methodMessage.Args, methodMessage.ArgCount, methodMessage.LogicalCallContext, methodMessage); if (executeType == ExecuteType.Reader) profiler.ExecuteFinish(instance, executeType, (DbDataReader)returnValue); else if (executeType != ExecuteType.None) profiler.ExecuteFinish(instance, executeType, null); return returnMessage; }
public virtual IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink) { IMethodCallMessage methodCallMessage = (IMethodCallMessage)msg; IMessageCtrl result = null; IMessage message = null; LogicalCallContext logicalCallContext = null; bool flag = false; try { try { LogicalCallContext logicalCallContext2 = (LogicalCallContext)methodCallMessage.Properties[Message.CallContextKey]; object server = this._server; StackBuilderSink.VerifyIsOkToCallMethod(server, methodCallMessage); logicalCallContext = CallContext.SetLogicalCallContext(logicalCallContext2); flag = true; logicalCallContext2.PropagateIncomingHeadersToCallContext(msg); StackBuilderSink.PreserveThreadPrincipalIfNecessary(logicalCallContext2, logicalCallContext); ServerChannelSinkStack serverChannelSinkStack = msg.Properties["__SinkStack"] as ServerChannelSinkStack; if (serverChannelSinkStack != null) { serverChannelSinkStack.ServerObject = server; } MethodBase methodBase = StackBuilderSink.GetMethodBase(methodCallMessage); object[] array = null; RemotingMethodCachedData reflectionCachedData = InternalRemotingServices.GetReflectionCachedData(methodBase); object[] args = Message.CoerceArgs(methodCallMessage, reflectionCachedData.Parameters); object ret = this.PrivateProcessMessage(methodBase.MethodHandle, args, server, out array); this.CopyNonByrefOutArgsFromOriginalArgs(reflectionCachedData, args, ref array); if (replySink != null) { LogicalCallContext logicalCallContext3 = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext; if (logicalCallContext3 != null) { logicalCallContext3.RemovePrincipalIfNotSerializable(); } message = new ReturnMessage(ret, array, (array == null) ? 0 : array.Length, logicalCallContext3, methodCallMessage); logicalCallContext3.PropagateOutgoingHeadersToMessage(message); } } catch (Exception e) { if (replySink != null) { message = new ReturnMessage(e, methodCallMessage); ((ReturnMessage)message).SetLogicalCallContext((LogicalCallContext)methodCallMessage.Properties[Message.CallContextKey]); } } finally { if (replySink != null) { replySink.SyncProcessMessage(message); } } } finally { if (flag) { CallContext.SetLogicalCallContext(logicalCallContext); } } return(result); }
public virtual IMessage SyncProcessMessage(IMessage msg) { IMessage message = InternalSink.ValidateMessage(msg); if (message != null) { return(message); } IMethodCallMessage methodCallMessage = msg as IMethodCallMessage; LogicalCallContext logicalCallContext = null; LogicalCallContext logicalCallContext2 = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext; object data = logicalCallContext2.GetData("__xADCall"); bool flag = false; IMessage message2; try { object server = this._server; StackBuilderSink.VerifyIsOkToCallMethod(server, methodCallMessage); LogicalCallContext logicalCallContext3; if (methodCallMessage != null) { logicalCallContext3 = methodCallMessage.LogicalCallContext; } else { logicalCallContext3 = (LogicalCallContext)msg.Properties["__CallContext"]; } logicalCallContext = CallContext.SetLogicalCallContext(logicalCallContext3); flag = true; logicalCallContext3.PropagateIncomingHeadersToCallContext(msg); StackBuilderSink.PreserveThreadPrincipalIfNecessary(logicalCallContext3, logicalCallContext); if (this.IsOKToStackBlt(methodCallMessage, server) && ((Message)methodCallMessage).Dispatch(server)) { message2 = new StackBasedReturnMessage(); ((StackBasedReturnMessage)message2).InitFields((Message)methodCallMessage); LogicalCallContext logicalCallContext4 = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext; logicalCallContext4.PropagateOutgoingHeadersToMessage(message2); ((StackBasedReturnMessage)message2).SetLogicalCallContext(logicalCallContext4); } else { MethodBase methodBase = StackBuilderSink.GetMethodBase(methodCallMessage); object[] array = null; RemotingMethodCachedData reflectionCachedData = InternalRemotingServices.GetReflectionCachedData(methodBase); object[] args = Message.CoerceArgs(methodCallMessage, reflectionCachedData.Parameters); object ret = this.PrivateProcessMessage(methodBase.MethodHandle, args, server, out array); this.CopyNonByrefOutArgsFromOriginalArgs(reflectionCachedData, args, ref array); LogicalCallContext logicalCallContext5 = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext; if (data != null && (bool)data && logicalCallContext5 != null) { logicalCallContext5.RemovePrincipalIfNotSerializable(); } message2 = new ReturnMessage(ret, array, (array == null) ? 0 : array.Length, logicalCallContext5, methodCallMessage); logicalCallContext5.PropagateOutgoingHeadersToMessage(message2); CallContext.SetLogicalCallContext(logicalCallContext); } } catch (Exception e) { message2 = new ReturnMessage(e, methodCallMessage); ((ReturnMessage)message2).SetLogicalCallContext(methodCallMessage.LogicalCallContext); if (flag) { CallContext.SetLogicalCallContext(logicalCallContext); } } return(message2); }
internal virtual IMessage SyncProcessMessage(IMessage msg, int methodPtr, bool fExecuteInContext) { // Validate message here IMessage errMsg = InternalSink.ValidateMessage(msg); if (errMsg != null) { return(errMsg); } IMethodCallMessage mcMsg = msg as IMethodCallMessage; IMessage retMessage; LogicalCallContext oldCallCtx = null; try { Object server = _server; BCLDebug.Assert((server != null) == (!_bStatic), "Invalid state in stackbuilder sink?"); // validate the method base if necessary VerifyIsOkToCallMethod(server, mcMsg); // install call context onto the thread, holding onto // the one that is currently on the thread LogicalCallContext messageCallContext = null; if (mcMsg != null) { messageCallContext = mcMsg.LogicalCallContext; } else { messageCallContext = (LogicalCallContext)msg.Properties["__CallContext"]; } oldCallCtx = CallContext.SetLogicalCallContext(messageCallContext); messageCallContext.PropagateIncomingHeadersToCallContext(msg); PreserveThreadPrincipalIfNecessary(messageCallContext, oldCallCtx); // NOTE: target for dispatch will be NULL when the StackBuilderSink // is used for async delegates on static methods. RemotingServices.LogRemotingStage(RemotingServices.SERVER_MSG_STACK_BUILD); // *** NOTE *** // Although we always pass _server to these calls in the EE, // when we execute using Message::Dispatch we are using TP as // the this-ptr ... (what the call site thinks is the this-ptr) // when we execute using StackBuilderSink::PrivatePM we use // _server as the this-ptr (which could be different if there // is interception for strictly MBR types in the same AD). // ************ if (IsOKToStackBlt(mcMsg, server) && ((Message)mcMsg).Dispatch(server, fExecuteInContext)) { //retMessage = StackBasedReturnMessage.GetObjectFromPool((Message)mcMsg); retMessage = new StackBasedReturnMessage(); ((StackBasedReturnMessage)retMessage).InitFields((Message)mcMsg); // call context could be different then the one from before the call. LogicalCallContext latestCallContext = CallContext.GetLogicalCallContext(); // retrieve outgoing response headers latestCallContext.PropagateOutgoingHeadersToMessage(retMessage); // Install call context back into Message (from the thread) ((StackBasedReturnMessage)retMessage).SetLogicalCallContext(latestCallContext); } else { MethodBase mb = GetMethodBase(mcMsg); Object[] outArgs = null; Object ret = null; RemotingMethodCachedData methodCache = InternalRemotingServices.GetReflectionCachedData(mb); Message.DebugOut("StackBuilderSink::Calling PrivateProcessMessage\n"); Object[] args = Message.CoerceArgs(mcMsg, methodCache.Parameters); ret = PrivateProcessMessage( mb, args, server, methodPtr, fExecuteInContext, out outArgs); CopyNonByrefOutArgsFromOriginalArgs(methodCache, args, ref outArgs); // call context could be different then the one from before the call. LogicalCallContext latestCallContext = CallContext.GetLogicalCallContext(); retMessage = new ReturnMessage( ret, outArgs, (outArgs == null ? 0 : outArgs.Length), latestCallContext, mcMsg); // retrieve outgoing response headers latestCallContext.PropagateOutgoingHeadersToMessage(retMessage); } // restore the call context on the thread CallContext.SetLogicalCallContext(oldCallCtx); } catch (Exception e) { Message.DebugOut( "StackBuilderSink::The server object probably threw an exception " + e.Message + e.StackTrace + "\n"); retMessage = new ReturnMessage(e, mcMsg); ((ReturnMessage)retMessage).SetLogicalCallContext(mcMsg.LogicalCallContext); if (oldCallCtx != null) { CallContext.SetLogicalCallContext(oldCallCtx); } } RemotingServices.LogRemotingStage(RemotingServices.SERVER_RET_SINK_CHAIN); return(retMessage); }
public virtual IMessageCtrl AsyncProcessMessage( IMessage msg, IMessageSink replySink) { IMethodCallMessage mcMsg = (IMethodCallMessage)msg; IMessageCtrl retCtrl = null; IMessage retMessage = null; LogicalCallContext oldCallCtx = null; try { LogicalCallContext callCtx = (LogicalCallContext) mcMsg.Properties[Message.CallContextKey]; Object server = _server; // validate the method base if necessary VerifyIsOkToCallMethod(server, mcMsg); // install call context onto the thread, holding onto // the one that is currently on the thread oldCallCtx = CallContext.SetLogicalCallContext(callCtx); // retrieve incoming headers callCtx.PropagateIncomingHeadersToCallContext(msg); PreserveThreadPrincipalIfNecessary(callCtx, oldCallCtx); // see if this is a server message that was dispatched asynchronously ServerChannelSinkStack sinkStack = msg.Properties["__SinkStack"] as ServerChannelSinkStack; if (sinkStack != null) { sinkStack.ServerObject = server; } BCLDebug.Assert((server != null) == (!_bStatic), "Invalid state in stackbuilder sink?"); MethodBase mb = GetMethodBase(mcMsg); Object[] outArgs = null; Object ret = null; RemotingMethodCachedData methodCache = InternalRemotingServices.GetReflectionCachedData(mb); Object[] args = Message.CoerceArgs(mcMsg, methodCache.Parameters); ret = PrivateProcessMessage(mb, args, server, 0, false, out outArgs); CopyNonByrefOutArgsFromOriginalArgs(methodCache, args, ref outArgs); if (replySink != null) { // call context could be different then the one from before the call. LogicalCallContext latestCallContext = CallContext.GetLogicalCallContext(); retMessage = new ReturnMessage( ret, outArgs, (outArgs == null ? 0 : outArgs.Length), latestCallContext, mcMsg); // retrieve outgoing response headers latestCallContext.PropagateOutgoingHeadersToMessage(retMessage); replySink.SyncProcessMessage(retMessage); } } catch (Exception e) { try { if (replySink != null) { retMessage = new ReturnMessage(e, mcMsg); ((ReturnMessage)retMessage).SetLogicalCallContext( (LogicalCallContext) mcMsg.Properties[Message.CallContextKey]); replySink.SyncProcessMessage(retMessage); } } catch (Exception) { // Fatal error.. can't do anything .. // bail out silently. } } finally { // restore the call context on the thread if (oldCallCtx != null) { CallContext.SetLogicalCallContext(oldCallCtx); } } return(retCtrl); } // AsyncProcessMessage
[System.Security.SecurityCritical] // auto-generated public virtual IMessageCtrl AsyncProcessMessage( IMessage msg, IMessageSink replySink) { IMethodCallMessage mcMsg = (IMethodCallMessage)msg; IMessageCtrl retCtrl = null; IMessage retMessage = null; LogicalCallContext oldCallCtx = null; bool isCallContextSet = false; try{ try { LogicalCallContext callCtx = (LogicalCallContext) mcMsg.Properties[Message.CallContextKey]; Object server = _server; // validate the method base if necessary VerifyIsOkToCallMethod(server, mcMsg); // install call context onto the thread, holding onto // the one that is currently on the thread oldCallCtx = CallContext.SetLogicalCallContext(callCtx); isCallContextSet = true; // retrieve incoming headers callCtx.PropagateIncomingHeadersToCallContext(msg); PreserveThreadPrincipalIfNecessary(callCtx, oldCallCtx); // see if this is a server message that was dispatched asynchronously ServerChannelSinkStack sinkStack = msg.Properties["__SinkStack"] as ServerChannelSinkStack; if (sinkStack != null) { sinkStack.ServerObject = server; } BCLDebug.Assert((server != null) == (!_bStatic), "Invalid state in stackbuilder sink?"); MethodBase mb = GetMethodBase(mcMsg); Object[] outArgs = null; Object ret = null; RemotingMethodCachedData methodCache = InternalRemotingServices.GetReflectionCachedData(mb); Object[] args = Message.CoerceArgs(mcMsg, methodCache.Parameters); ret = PrivateProcessMessage(mb.MethodHandle, args, server, 0, false, out outArgs); CopyNonByrefOutArgsFromOriginalArgs(methodCache, args, ref outArgs); if (replySink != null) { // call context could be different then the one from before the call. LogicalCallContext latestCallContext = CallContext.GetLogicalCallContext(); if (latestCallContext != null) { // Special case Principal since if might not be serializable before returning // ReturnMessage latestCallContext.RemovePrincipalIfNotSerializable(); } retMessage = new ReturnMessage( ret, outArgs, (outArgs == null ? 0 : outArgs.Length), latestCallContext, mcMsg); // retrieve outgoing response headers latestCallContext.PropagateOutgoingHeadersToMessage(retMessage); } } catch (Exception e) { if (replySink != null) { retMessage = new ReturnMessage(e, mcMsg); ((ReturnMessage)retMessage).SetLogicalCallContext( (LogicalCallContext) mcMsg.Properties[Message.CallContextKey]); } } finally { if (replySink != null) { // Call the reply sink without catching the exceptions // in it. In v2.0 any exceptions in the callback for example // would probably bring down the process replySink.SyncProcessMessage(retMessage); } } } finally { // restore the call context on the thread if (isCallContextSet) { CallContext.SetLogicalCallContext(oldCallCtx); } } return(retCtrl); } // AsyncProcessMessage
public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink) { IMethodCallMessage mcm = (IMethodCallMessage)msg; IMessage retMsg; try { // serialize message ITransportHeaders headers; Stream requestStream; SerializeMessage(msg, out headers, out requestStream); // process message ClientChannelSinkStack sinkStack = new ClientChannelSinkStack(replySink); sinkStack.Push(this, msg); _nextSink.AsyncProcessRequest(sinkStack, msg, headers, requestStream); } catch (Exception e) { retMsg = new ReturnMessage(e, mcm); if (replySink != null) replySink.SyncProcessMessage(retMsg); } return null; } // AsyncProcessMessage
/* this is called from unmanaged code */ internal static object PrivateInvoke (RealProxy rp, IMessage msg, out Exception exc, out object [] out_args) { MonoMethodMessage mMsg = (MonoMethodMessage) msg; mMsg.LogicalCallContext = CallContext.CreateLogicalCallContext (true); CallType call_type = mMsg.CallType; #if MOONLIGHT bool is_remproxy = false; #else bool is_remproxy = (rp is RemotingProxy); #endif out_args = null; IMethodReturnMessage res_msg = null; if (call_type == CallType.BeginInvoke) // todo: set CallMessage in runtime instead mMsg.AsyncResult.CallMessage = mMsg; if (call_type == CallType.EndInvoke) res_msg = (IMethodReturnMessage)mMsg.AsyncResult.EndInvoke (); // Check for constructor msg if (mMsg.MethodBase.IsConstructor) { #if !MOONLIGHT if (is_remproxy) res_msg = (IMethodReturnMessage) (rp as RemotingProxy).ActivateRemoteObject ((IMethodMessage) msg); else #endif msg = new ConstructionCall (rp.GetProxiedType ()); } if (null == res_msg) { bool failed = false; try { res_msg = (IMethodReturnMessage)rp.Invoke (msg); } catch (Exception ex) { failed = true; if (call_type == CallType.BeginInvoke) { // If async dispatch crashes, don't propagate the exception. // The exception will be raised when calling EndInvoke. mMsg.AsyncResult.SyncProcessMessage (new ReturnMessage (ex, msg as IMethodCallMessage)); res_msg = new ReturnMessage (null, null, 0, null, msg as IMethodCallMessage); } else throw; } // Note, from begining this code used AsyncResult.IsCompleted for // checking if it was a remoting or custom proxy, but in some // cases the remoting proxy finish before the call returns // causing this method to be called, therefore causing all kind of bugs. if ((!is_remproxy) && call_type == CallType.BeginInvoke && !failed) { IMessage asyncMsg = null; // allow calltype EndInvoke to finish asyncMsg = mMsg.AsyncResult.SyncProcessMessage (res_msg as IMessage); out_args = res_msg.OutArgs; res_msg = new ReturnMessage (asyncMsg, null, 0, null, res_msg as IMethodCallMessage); } } if (res_msg.LogicalCallContext != null && res_msg.LogicalCallContext.HasInfo) CallContext.UpdateCurrentCallContext (res_msg.LogicalCallContext); exc = res_msg.Exception; // todo: remove throw exception from the runtime invoke if (null != exc) { out_args = null; throw exc.FixRemotingException(); } else if (res_msg is IConstructionReturnMessage) { if (out_args == null) out_args = res_msg.OutArgs; } else if (mMsg.CallType == CallType.BeginInvoke) { // We don't have OutArgs in this case. } else if (mMsg.CallType == CallType.Sync) { out_args = ProcessResponse (res_msg, mMsg); } else if (mMsg.CallType == CallType.EndInvoke) { out_args = ProcessResponse (res_msg, mMsg.AsyncResult.CallMessage); } else { if (out_args == null) out_args = res_msg.OutArgs; } return res_msg.ReturnValue; }
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
public IMessage SyncProcessMessage(IMessage msg) { IMethodCallMessage mcm = msg as IMethodCallMessage; IMessage retMsg; try { // serialize message ITransportHeaders headers; Stream requestStream; SerializeMessage(msg, out headers, out requestStream); // process message Stream returnStream; ITransportHeaders returnHeaders; _nextSink.ProcessMessage(msg, headers, requestStream, out returnHeaders, out returnStream); if (returnHeaders == null) throw new ArgumentNullException("returnHeaders"); // deserialize stream retMsg = DeserializeMessage(mcm, returnHeaders, returnStream); } catch (Exception e) { retMsg = new ReturnMessage(e, mcm); } return retMsg; } // SyncProcessMessage
public virtual IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink) { IMethodCallMessage message = (IMethodCallMessage)msg; IMessageCtrl ctrl = null; IMessage message2 = null; LogicalCallContext threadCallContext = null; bool flag = false; try { try { try { LogicalCallContext callCtx = (LogicalCallContext)message.Properties[Message.CallContextKey]; object server = this._server; VerifyIsOkToCallMethod(server, message); threadCallContext = CallContext.SetLogicalCallContext(callCtx); flag = true; callCtx.PropagateIncomingHeadersToCallContext(msg); PreserveThreadPrincipalIfNecessary(callCtx, threadCallContext); ServerChannelSinkStack stack = msg.Properties["__SinkStack"] as ServerChannelSinkStack; if (stack != null) { stack.ServerObject = server; } MethodBase methodBase = GetMethodBase(message); object[] outArgs = null; object ret = null; RemotingMethodCachedData reflectionCachedData = InternalRemotingServices.GetReflectionCachedData(methodBase); object[] args = Message.CoerceArgs(message, reflectionCachedData.Parameters); ret = this.PrivateProcessMessage(methodBase.MethodHandle, args, server, 0, false, out outArgs); this.CopyNonByrefOutArgsFromOriginalArgs(reflectionCachedData, args, ref outArgs); if (replySink != null) { LogicalCallContext logicalCallContext = CallContext.GetLogicalCallContext(); if (logicalCallContext != null) { logicalCallContext.RemovePrincipalIfNotSerializable(); } message2 = new ReturnMessage(ret, outArgs, (outArgs == null) ? 0 : outArgs.Length, logicalCallContext, message); logicalCallContext.PropagateOutgoingHeadersToMessage(message2); } return(ctrl); } catch (Exception exception) { if (replySink != null) { message2 = new ReturnMessage(exception, message); ((ReturnMessage)message2).SetLogicalCallContext((LogicalCallContext)message.Properties[Message.CallContextKey]); } } return(ctrl); } finally { if (replySink != null) { replySink.SyncProcessMessage(message2); } } } finally { if (flag) { CallContext.SetLogicalCallContext(threadCallContext); } } return(ctrl); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { if (requestMsg != null) { // The message has already been deserialized so delegate to the next sink. return _nextSink.ProcessMessage( sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); } if (requestHeaders == null) throw new ArgumentNullException("requestHeaders"); BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders; ServerProcessing processing; responseHeaders = null; responseStream = null; String verb = null; String contentType = null; bool bCanServiceRequest = true; // determine the content type String contentTypeHeader = null; if (wkRequestHeaders != null) contentTypeHeader = wkRequestHeaders.ContentType; else contentTypeHeader = requestHeaders["Content-Type"] as String; if (contentTypeHeader != null) { String charsetValue; HttpChannelHelper.ParseContentType(contentTypeHeader, out contentType, out charsetValue); } // check to see if Content-Type matches if ((contentType != null) && (String.CompareOrdinal(contentType, CoreChannel.BinaryMimeType) != 0)) { bCanServiceRequest = false; } // check for http specific verbs if (_protocol == Protocol.Http) { verb = (String)requestHeaders["__RequestVerb"]; if (!verb.Equals("POST") && !verb.Equals("M-POST")) bCanServiceRequest = false; } // either delegate or return an error message if we can't service the request if (!bCanServiceRequest) { // delegate to next sink if available if (_nextSink != null) { return _nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); } else { // send back an error message if (_protocol == Protocol.Http) { // return a client bad request error responseHeaders = new TransportHeaders(); responseHeaders["__HttpStatusCode"] = "400"; responseHeaders["__HttpReasonPhrase"] = "Bad Request"; responseStream = null; responseMsg = null; return ServerProcessing.Complete; } else { // The transport sink will catch this and do something here. throw new RemotingException( CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat")); } } } try { String objectUri = null; bool bIsCustomErrorEnabled = true; object oIsCustomErrorEnabled = requestHeaders["__CustomErrorsEnabled"]; if (oIsCustomErrorEnabled != null && oIsCustomErrorEnabled is bool){ bIsCustomErrorEnabled = (bool)oIsCustomErrorEnabled; } CallContext.SetData("__CustomErrorsEnabled", bIsCustomErrorEnabled); if (wkRequestHeaders != null) objectUri = wkRequestHeaders.RequestUri; else objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri]; if (objectUri != lastUri && RemotingServices.GetServerTypeForUri(objectUri) == null) throw new RemotingException( CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished")); else lastUri = objectUri; PermissionSet currentPermissionSet = null; if (this.TypeFilterLevel != TypeFilterLevel.Full) { currentPermissionSet = new PermissionSet(PermissionState.None); currentPermissionSet.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter)); } try { if (currentPermissionSet != null) currentPermissionSet.PermitOnly(); // Deserialize Request - Stream to IMessage requestMsg = CoreChannel.DeserializeBinaryRequestMessage(objectUri, requestStream, _strictBinding, this.TypeFilterLevel); } finally { if (currentPermissionSet != null) CodeAccessPermission.RevertPermitOnly(); } requestStream.Close(); if(requestMsg == null) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage")); } // Transparent proxy IMessages are allowed conditionally by AppSettings if (RemotingServices.IsTransparentProxy(requestMsg) && !AppSettings.AllowTransparentProxyMessage) { // Null request to prevent calling transparent proxy methods in catch below. // Fwlink is provided to explain why it is not supported. Inner exceptions propagate back to sender. requestMsg = null; throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"), new NotSupportedException(AppSettings.AllowTransparentProxyMessageFwLink)); } // Dispatch Call sinkStack.Push(this, null); processing = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); // make sure that responseStream is null if (responseStream != null) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream")); } switch (processing) { case ServerProcessing.Complete: { if (responseMsg == null) throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage")); sinkStack.Pop(this); SerializeResponse(sinkStack, responseMsg, ref responseHeaders, out responseStream); break; } // case ServerProcessing.Complete case ServerProcessing.OneWay: { sinkStack.Pop(this); break; } // case ServerProcessing.OneWay: case ServerProcessing.Async: { sinkStack.Store(this, null); break; } // case ServerProcessing.Async } // switch (processing) } catch(Exception e) { processing = ServerProcessing.Complete; responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg==null?new ErrorMessage():requestMsg)); // CallContext.SetData("__ClientIsClr", true); responseStream = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, _includeVersioning); CallContext.FreeNamedDataSlot("__ClientIsClr"); responseStream.Position = 0; responseHeaders = new TransportHeaders(); if (_protocol == Protocol.Http) { responseHeaders["Content-Type"] = CoreChannel.BinaryMimeType; } } finally{ CallContext.FreeNamedDataSlot("__CustomErrorsEnabled"); } return processing; } // ProcessMessage
internal virtual IMessage SyncProcessMessage(IMessage msg, int methodPtr, bool fExecuteInContext) { IMessage message3; IMessage message = InternalSink.ValidateMessage(msg); if (message != null) { return(message); } IMethodCallMessage message2 = msg as IMethodCallMessage; LogicalCallContext threadCallContext = null; object obj2 = CallContext.GetLogicalCallContext().GetData("__xADCall"); bool flag = false; try { object server = this._server; VerifyIsOkToCallMethod(server, message2); LogicalCallContext callCtx = null; if (message2 != null) { callCtx = message2.LogicalCallContext; } else { callCtx = (LogicalCallContext)msg.Properties["__CallContext"]; } threadCallContext = CallContext.SetLogicalCallContext(callCtx); flag = true; callCtx.PropagateIncomingHeadersToCallContext(msg); PreserveThreadPrincipalIfNecessary(callCtx, threadCallContext); if (this.IsOKToStackBlt(message2, server) && ((Message)message2).Dispatch(server, fExecuteInContext)) { message3 = new StackBasedReturnMessage(); ((StackBasedReturnMessage)message3).InitFields((Message)message2); LogicalCallContext context4 = CallContext.GetLogicalCallContext(); context4.PropagateOutgoingHeadersToMessage(message3); ((StackBasedReturnMessage)message3).SetLogicalCallContext(context4); return(message3); } MethodBase methodBase = GetMethodBase(message2); object[] outArgs = null; object ret = null; RemotingMethodCachedData reflectionCachedData = InternalRemotingServices.GetReflectionCachedData(methodBase); object[] args = Message.CoerceArgs(message2, reflectionCachedData.Parameters); ret = this.PrivateProcessMessage(methodBase.MethodHandle, args, server, methodPtr, fExecuteInContext, out outArgs); this.CopyNonByrefOutArgsFromOriginalArgs(reflectionCachedData, args, ref outArgs); LogicalCallContext logicalCallContext = CallContext.GetLogicalCallContext(); if (((obj2 != null) && ((bool)obj2)) && (logicalCallContext != null)) { logicalCallContext.RemovePrincipalIfNotSerializable(); } message3 = new ReturnMessage(ret, outArgs, (outArgs == null) ? 0 : outArgs.Length, logicalCallContext, message2); logicalCallContext.PropagateOutgoingHeadersToMessage(message3); CallContext.SetLogicalCallContext(threadCallContext); } catch (Exception exception) { message3 = new ReturnMessage(exception, message2); ((ReturnMessage)message3).SetLogicalCallContext(message2.LogicalCallContext); if (flag) { CallContext.SetLogicalCallContext(threadCallContext); } } return(message3); }