public MethodCallContext(IMethodCallMessage mcm, IMessageSink nextSink) { mcm.ThrowIfNullArgument(nameof(mcm)); nextSink.ThrowIfNullArgument(nameof(nextSink)); _mcm = mcm; _nextSink = nextSink; }
private MethodData GetMethodData(IMethodCallMessage methodCall) { MethodData data; MethodBase methodBase = methodCall.MethodBase; if (!this.methodDataCache.TryGetMethodData(methodBase, out data)) { bool flag; System.Type declaringType = methodBase.DeclaringType; if (declaringType == typeof(object)) { MethodType getType; if (methodCall.MethodBase == typeof(object).GetMethod("GetType")) { getType = MethodType.GetType; } else { getType = MethodType.Object; } flag = true; data = new MethodData(methodBase, getType); } else if (declaringType.IsInstanceOfType(this.serviceChannel)) { flag = true; data = new MethodData(methodBase, MethodType.Channel); } else { MethodType service; ProxyOperationRuntime operation = this.proxyRuntime.GetOperation(methodBase, methodCall.Args, out flag); if (operation == null) { if (this.serviceChannel.Factory != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.ServiceModel.SR.GetString("SFxMethodNotSupported1", new object[] { methodBase.Name }))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(System.ServiceModel.SR.GetString("SFxMethodNotSupportedOnCallback1", new object[] { methodBase.Name }))); } if (operation.IsSyncCall(methodCall)) { service = MethodType.Service; } else if (operation.IsBeginCall(methodCall)) { service = MethodType.BeginService; } else { service = MethodType.EndService; } data = new MethodData(methodBase, service, operation); } if (flag) { this.methodDataCache.SetMethodData(data); } } return data; }
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 void Process(ref IMethodCallMessage msg) { //Console.WriteLine("Method details: " + msg.MethodBase); PrintParameters printParameters = new PrintParameters(); printParameters.PrintValues(msg); }
public void PostMethodExecutionProcess(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg) { _stopwatch.Stop(); //Console.WriteLine("Return value: {0}", retMsg.ReturnValue); //Console.WriteLine("Ticks consumed: {0}", _stopwatch.ElapsedTicks); }
internal MethodResponse(IMethodCallMessage msg, object handlerObject, BinaryMethodReturnMessage smuggledMrm) { if (msg != null) { this.MI = msg.MethodBase; this._methodCache = InternalRemotingServices.GetReflectionCachedData(this.MI); this.methodName = msg.MethodName; this.uri = msg.Uri; this.typeName = msg.TypeName; if (this._methodCache.IsOverloaded()) { this.methodSignature = (Type[]) msg.MethodSignature; } this.argCount = this._methodCache.Parameters.Length; } this.retVal = smuggledMrm.ReturnValue; this.outArgs = smuggledMrm.Args; this.fault = smuggledMrm.Exception; this.callContext = smuggledMrm.LogicalCallContext; if (smuggledMrm.HasProperties) { smuggledMrm.PopulateMessageProperties(this.Properties); } this.fSoap = false; }
/// <summary> /// Builds a method call return message given the returnvalue, out arguments and methodcall. /// </summary> /// <param name="returnValue">Return value of the methodcall.</param> /// <param name="arguments">Input and output argument values.</param> /// <param name="callMessage">The original methodcall object.</param> /// <remarks> /// This method is to be used during recording phase only. A .NET return message object /// is constructed based on the given information, where all non-serializable return /// values and output arguments are mocked for recording. /// </remarks> public static IMethodReturnMessage BuildReturnMessage(object returnValue, object[] arguments, IMethodCallMessage callMessage) { // Build return message: IConstructionCallMessage ccm = callMessage as IConstructionCallMessage; if (ccm != null) { // If constructor message, build returnmessage from construction: return EnterpriseServicesHelper.CreateConstructionReturnMessage(ccm, (MarshalByRefObject)returnValue); } else { // Wrap return value: object wrappedReturnValue; wrappedReturnValue = WrapObject(returnValue, ((MethodInfo)callMessage.MethodBase).ReturnType); // Copy arguments, wrapping output arguments: int outArgsCount = 0; object[] wrappedArgs = new object[arguments.Length]; foreach(ParameterInfo param in callMessage.MethodBase.GetParameters()) { if (param.ParameterType.IsByRef) { wrappedArgs[param.Position] = WrapObject(arguments[param.Position], param.ParameterType); outArgsCount++; } else { wrappedArgs[param.Position] = arguments[param.Position]; } } // Build return message: return new ReturnMessage(wrappedReturnValue, wrappedArgs, outArgsCount, callMessage.LogicalCallContext, callMessage); } }
/// <summary> /// Creates a new <see cref="TransparentProxyMethodReturn"/> object that contains a /// return value. /// </summary> /// <param name="callMessage">The original call message that invoked the method.</param> /// <param name="returnValue">Return value from the method.</param> /// <param name="arguments">Collections of arguments passed to the method (including the new /// values of any out params).</param> /// <param name="invocationContext">Invocation context dictionary passed into the call.</param> public TransparentProxyMethodReturn(IMethodCallMessage callMessage, object returnValue, object[] arguments, IDictionary invocationContext) { this.callMessage = callMessage; this.invocationContext = invocationContext; this.arguments = arguments; this.returnValue = returnValue; this.outputs = new TransparentProxyOutputParameterCollection(callMessage, arguments); }
/// <summary> /// Creates a new <see cref="TransparentProxyMethodReturn"/> object that contains an /// exception thrown by the target. /// </summary> /// <param name="ex">Exception that was thrown.</param> /// <param name="callMessage">The original call message that invoked the method.</param> /// <param name="invocationContext">Invocation context dictionary passed into the call.</param> public TransparentProxyMethodReturn(Exception ex, IMethodCallMessage callMessage, IDictionary invocationContext) { this.callMessage = callMessage; this.invocationContext = invocationContext; this.exception = ex; this.arguments = new object[0]; this.outputs = new ParameterCollection(this.arguments, new ParameterInfo[0], pi => false); }
public IEnumerable<SqlCommand> CreateCommands(IMethodCallMessage mcm, SqlConnection connection, string schemaName, out SqlParameter returnValue, out SqlParameter[] outParameters, out ISerializationTypeInfo returnTypeInfo, out ICallDeserializationInfo procInfo, out XmlNameTable xmlNameTable, IList<IDisposable> disposeList) { List<SqlCommand> sqlCommands = new List<SqlCommand>(); SqlCommand sqlCommand = methods[mcm.MethodBase].GetCommand(mcm, connection, out returnValue, out outParameters, out returnTypeInfo, out procInfo, out xmlNameTable, disposeList); sqlCommands.Add(sqlCommand); return sqlCommands; }
/// <summary> /// Creates a new instance of the CallInterceptionData class. /// </summary> /// <param name="parameters">Parameter values of the intercepted call</param> /// <param name="remoteInvoker">Delegate for remote invocation</param> /// <param name="remotingMessage">Remoting message</param> public CallInterceptionData(object[] parameters, InvokeRemoteMethodDelegate remoteInvoker, IMethodCallMessage remotingMessage) { Intercepted = false; ReturnValue = null; Parameters = parameters; _remoteInvoker = remoteInvoker; _remotingMessage = remotingMessage; }
public void PreMethodExecutionProcess(ref IMethodCallMessage msg) { _stopwatch.Start(); //Console.WriteLine("Method details: " + msg.MethodBase); PrintParameters printParameters = new PrintParameters(); printParameters.PrintValues(msg); }
public CompositionException(IMethodCallMessage Message,string message, System.Exception innerException):this(String.Format("Exception:{0}\r\nAssembly:{1}\r\n{2}:{3}\r\nArgs:\r\n",message,Message.TypeName,Message.MethodBase.MemberType,Message.MethodName),innerException) { for(int i=0; i<Message.ArgCount; i+=2) { _message = String.Format("{0}\t{1}={2}\r\n",_message,Message.GetArgName(i),Message.GetArg(i).ToString()); } }
private IMethodReturnMessage CreateReturnMessage(object ret, object[] returnArgs, IMethodCallMessage methodCall) { if (returnArgs != null) { return this.CreateReturnMessage(ret, returnArgs, returnArgs.Length, SetActivityIdInLogicalCallContext(methodCall.LogicalCallContext), methodCall); } return new SingleReturnMessage(ret, methodCall); }
// used by the client internal IMessage FormatResponse(ISoapMessage soapMsg, IMethodCallMessage mcm) { IMessage rtnMsg; if(soapMsg.MethodName == "Fault") { // an exception was thrown by the server Exception e = new SerializationException(); int i = Array.IndexOf(soapMsg.ParamNames, "detail"); if(_serverFaultExceptionField != null) // todo: revue this 'cause it's not safe e = (Exception) _serverFaultExceptionField.GetValue( soapMsg.ParamValues[i]); rtnMsg = new ReturnMessage((System.Exception)e, mcm); } else { object rtnObject = null; //RemMessageType messageType; // Get the output of the function if it is not *void* if(_methodCallInfo.ReturnType != typeof(void)){ int index = Array.IndexOf(soapMsg.ParamNames, "return"); rtnObject = soapMsg.ParamValues[index]; if(rtnObject is IConvertible) rtnObject = Convert.ChangeType( rtnObject, _methodCallInfo.ReturnType); } object[] outParams = new object [_methodCallParameters.Length]; int n=0; // check if there are *out* parameters foreach(ParameterInfo paramInfo in _methodCallParameters) { if(paramInfo.ParameterType.IsByRef || paramInfo.IsOut) { int index = Array.IndexOf(soapMsg.ParamNames, paramInfo.Name); object outParam = soapMsg.ParamValues[index]; if(outParam is IConvertible) outParam = Convert.ChangeType (outParam, paramInfo.ParameterType.GetElementType()); outParams[n] = outParam; } else outParams [n] = null; n++; } Header[] headers = new Header [2 + (soapMsg.Headers != null ? soapMsg.Headers.Length : 0)]; headers [0] = new Header ("__Return", rtnObject); headers [1] = new Header ("__OutArgs", outParams); if (soapMsg.Headers != null) soapMsg.Headers.CopyTo (headers, 2); rtnMsg = new MethodResponse (headers, mcm); } return rtnMsg; }
public RemotingInvocation(RealProxy proxy, IMethodCallMessage message) { this.message = message; this.proxy = proxy; arguments = message.Args; if (arguments == null) arguments = new object[0]; }
/// <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; }
private SmuggledMethodCallMessage(IMethodCallMessage mcm) { this._uri = mcm.Uri; this._methodName = mcm.MethodName; this._typeName = mcm.TypeName; ArrayList argsToSerialize = null; IInternalMessage message = mcm as IInternalMessage; if ((message == null) || message.HasProperties()) { this._propertyCount = MessageSmuggler.StoreUserPropertiesForMethodMessage(mcm, ref argsToSerialize); } if (mcm.MethodBase.IsGenericMethod) { Type[] genericArguments = mcm.MethodBase.GetGenericArguments(); if ((genericArguments != null) && (genericArguments.Length > 0)) { if (argsToSerialize == null) { argsToSerialize = new ArrayList(); } this._instantiation = new MessageSmuggler.SerializedArg(argsToSerialize.Count); argsToSerialize.Add(genericArguments); } } if (RemotingServices.IsMethodOverloaded(mcm)) { if (argsToSerialize == null) { argsToSerialize = new ArrayList(); } this._methodSignature = new MessageSmuggler.SerializedArg(argsToSerialize.Count); argsToSerialize.Add(mcm.MethodSignature); } LogicalCallContext logicalCallContext = mcm.LogicalCallContext; if (logicalCallContext == null) { this._callContext = null; } else if (logicalCallContext.HasInfo) { if (argsToSerialize == null) { argsToSerialize = new ArrayList(); } this._callContext = new MessageSmuggler.SerializedArg(argsToSerialize.Count); argsToSerialize.Add(logicalCallContext); } else { this._callContext = logicalCallContext.RemotingData.LogicalCallID; } this._args = MessageSmuggler.FixupArgs(mcm.Args, ref argsToSerialize); if (argsToSerialize != null) { this._serializedArgs = CrossAppDomainSerializer.SerializeMessageParts(argsToSerialize).GetBuffer(); } }
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))); } }
protected void PreProcess(ref IMethodCallMessage msg) { Trace.WriteLine(String.Format("TracePreProcessor {0} is called", msg.MethodName)); if (msg.InArgCount > 0) Trace.WriteLine(String.Format("In Argument Count {0}", msg.InArgCount)); for (int idx = 0; idx < msg.InArgCount; idx++) { Trace.WriteLine(String.Format("{0}={1}", msg.GetInArgName(idx), msg.GetInArg(idx))); } }
public ReturnMessage(Object ret, Object[] outArgs, int outArgsCount, LogicalCallContext callCtx, IMethodCallMessage mcm) { this.ret = ret; this.outArgs = outArgs; this.outArgsCount = outArgsCount; this.callCtx = callCtx; this.mcm = mcm; }
public ReturnMessage (Exception e, IMethodCallMessage mcm) { _exception = e; if (mcm != null) { _methodBase = mcm.MethodBase; _callCtx = mcm.LogicalCallContext; } _args = new object[0]; // .NET does this }
/// <summary> /// Creates a new <see cref="IMethodInvocation"/> implementation that wraps /// the given <paramref name="callMessage"/>, with the given ultimate /// target object. /// </summary> /// <param name="callMessage">Remoting call message object.</param> /// <param name="target">Ultimate target of the method call.</param> public TransparentProxyMethodInvocation(IMethodCallMessage callMessage, object target) { this.callMessage = callMessage; this.invocationContext = new Hashtable(); this.target = target; this.arguments = callMessage.Args; this.inputParams = new TransparentProxyInputParameterCollection(callMessage, this.arguments); this.allParams = new ParameterCollection(arguments, callMessage.MethodBase.GetParameters(), info => true); }
/// <summary> /// Invokes a method on the object this proxy represents. /// </summary> /// <param name="msg">Message containing the parameters of the method being invoked.</param> /// <param name="representedValue">The object this proxy represents.</param> /// <returns>The <see cref="ReturnMessage"/> instance as a result of method invocation on the /// object which this proxy represents.</returns> protected static ReturnMessage InvokeMethod(IMethodCallMessage msg, object representedValue) { if (msg == null) { throw new ArgumentNullException("msg", "The message containing invocation information cannot be null"); } MethodInfo proxiedMethod = msg.MethodBase as MethodInfo; return new ReturnMessage(proxiedMethod.Invoke(representedValue, msg.Args), null, 0, msg.LogicalCallContext, msg); }
private bool IsGetHashCodeCall(IMethodCallMessage mcm) { if (!mcm.MethodName.Equals("GetHashCode", StringComparison.Ordinal)) return false; var arguments = mcm.MethodSignature as Type[]; if (arguments == null) return false; return (arguments.Length == 0); }
private static void ExecuteBeforeStrategy(ref IMethodCallMessage callMsg) { var types = callMsg.MethodBase.GetCustomAttributes(typeof(InterceptHandlerAttribute), true) .Where(w => ((InterceptHandlerAttribute)w).InterceptType == InterceptType.Before) .Select(s => ((InterceptHandlerAttribute)s).StartegyType).ToArray(); foreach (var startegy in StartegyFactory.CreateBeforeStartegyFactory(callMsg, types)) { startegy.Execute(); } }
/// <summary> /// Instantiates a new MockableCall object based on a IMethodCallMessage. /// </summary> public MockableCall(MockingProxy callee, IMethodCallMessage callmsg) { if (callee == null) throw new ArgumentNullException("callee"); if (callmsg == null) throw new ArgumentNullException("callmsg"); this.originalCall = callmsg; this.callCreationTime = Environment.TickCount; this.callee = callee; this.method = callmsg.MethodBase; this.inArgs = callmsg.InArgs; this.isConstructorCall = (callmsg is IConstructionCallMessage); this.isCompleted = 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); } }
public static IMethodReturnMessage ToMethodReturnMessage(this Delegate @delegate, IMethodCallMessage callMessage) { try { object returnValue = @delegate.DynamicInvoke(callMessage.Args); return new ReturnMessage(returnValue, callMessage.Args, callMessage.ArgCount, callMessage.LogicalCallContext, callMessage); } catch (TargetInvocationException ex) { return new ReturnMessage(ex, callMessage); } }
internal MethodResponse (Exception e, IMethodCallMessage msg) { _callMsg = msg; if (null != msg) _uri = msg.Uri; else _uri = String.Empty; _exception = e; _returnValue = null; _outArgs = new object[0]; // .NET does this }
public static T[] GetAttributes <T>(IMethodCallMessage msg, bool inherit) { return(msg.MethodBase.GetCustomAttributes(typeof(T), true) as T[]); }
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 { // 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
[System.Security.SecurityCritical] // auto-generated internal Object Deserialize(Stream serializationStream, HeaderHandler handler, bool fCheck, IMethodCallMessage methodCallMessage) { return(Deserialize(serializationStream, handler, fCheck, false /*isCrossAppDomain*/, methodCallMessage)); }
[System.Security.SecurityCritical] // auto-generated internal Object Deserialize(Stream serializationStream, HeaderHandler handler, bool fCheck, bool isCrossAppDomain, IMethodCallMessage methodCallMessage) { if (serializationStream == null) { throw new ArgumentNullException("serializationStream", Environment.GetResourceString("ArgumentNull_WithParamName", serializationStream)); } Contract.EndContractBlock(); if (serializationStream.CanSeek && (serializationStream.Length == 0)) { throw new SerializationException(Environment.GetResourceString("Serialization_Stream")); } SerTrace.Log(this, "Deserialize Entry"); InternalFE formatterEnums = new InternalFE(); formatterEnums.FEtypeFormat = m_typeFormat; formatterEnums.FEserializerTypeEnum = InternalSerializerTypeE.Binary; formatterEnums.FEassemblyFormat = m_assemblyFormat; formatterEnums.FEsecurityLevel = m_securityLevel; ObjectReader sor = new ObjectReader(serializationStream, m_surrogates, m_context, formatterEnums, m_binder); sor.crossAppDomainArray = m_crossAppDomainArray; return(sor.Deserialize(handler, new __BinaryParser(serializationStream, sor), fCheck, isCrossAppDomain, methodCallMessage)); }
IMethodReturnMessage InvokeMethod(IMethodCallMessage callMsg) { return(RemotingServices.ExecuteMessage(target, callMsg)); }
public AgileAsyncWorkerItem(IMethodCallMessage message, AsyncResult ar, Object target) { _message = new MethodCall(message, false); _ar = ar; _target = target; }
public MCMDictionary(IMethodCallMessage msg, IDictionary idict) : base(MCMDictionary.MCMkeys, idict) { this._mcmsg = msg; }
public void Preprocess(MarshalByRefObject inst, IMessage msg) { if (mServiceCacheItem == null) { mServiceCacheItem = ONServiceCacheItem.Get("Action", ClassName, ServiceName); } IMethodCallMessage lMsg = msg as IMethodCallMessage; int lIndex = 0; // Extract Action ONAction lAction = inst as ONAction; // Shared Event Control if (lAction.OnContext.InSharedContext == true) // No-Principal Shared Event { return; } lAction.OnContext.InSharedContext = true; mSharedPrincipal = true; // Shared Event Arguments (in Shared Event order) HybridDictionary lSharedEventArguments = new HybridDictionary(true); HybridDictionary lSharedEventArgumentsInfo = new HybridDictionary(true); int i = 0; foreach (ParameterInfo lArgument in lMsg.MethodBase.GetParameters()) { ONSharedArgumentAttribute[] lSharedArgumentsInfo = lArgument.GetCustomAttributes(typeof(ONSharedArgumentAttribute), false) as ONSharedArgumentAttribute[]; foreach (ONSharedArgumentAttribute lSharedArgumentInfo in lSharedArgumentsInfo) { lSharedEventArgumentsInfo[lArgument.Name] = lSharedArgumentInfo; break; } lSharedEventArguments[lArgument.Name] = lMsg.Args[i]; i++; } // Shared Event Arguments for each Class (in Shared Event order) mServiceCacheItems = new List <ONServiceCacheItem>(); foreach (DictionaryEntry lEntry in lSharedEventArgumentsInfo) { string lSharedArgumentName = lEntry.Key as String; ONSharedArgumentAttribute lSharedArgumentInfo = lEntry.Value as ONSharedArgumentAttribute; // Create Instance ONInstance lInstance = (lSharedEventArguments[lSharedArgumentName] as ONOid).GetInstance(lAction.OnContext); if (lInstance == null) { throw new ONInstanceNotExistException(null, "", (lSharedEventArguments[lSharedArgumentName] as ONOid).ClassName); } // Create Action ONAction lSharedAction = ONContext.GetComponent_Action(lSharedArgumentInfo.ClassName, lAction.OnContext); lSharedAction.Instance = lInstance; // Reorder arguments lIndex = 0; object[] lArguments = new object[lSharedEventArguments.Count]; foreach (MethodInfo lMethodInfo in ONContext.GetMethods(lSharedAction.GetType(), typeof(ONServiceAttribute), ToString(lSharedAction.ClassName))) { foreach (ParameterInfo lParameterInfo in lMethodInfo.GetParameters()) { if (lSharedEventArguments.Contains(lParameterInfo.Name)) { // Normal Argument lArguments[lIndex++] = lSharedEventArguments[lParameterInfo.Name]; } else { ONSharedArgumentAttribute[] lSharedArgumentsInfo = lParameterInfo.GetCustomAttributes(typeof(ONSharedArgumentAttribute), false) as ONSharedArgumentAttribute[]; if (lSharedArgumentsInfo.Length == 0) { // Target Oid lArguments[lIndex++] = lInstance.Oid; } else if (string.Compare(lSharedArgumentsInfo[0].ClassName, lAction.ClassName, true) == 0) { // Source Oid lArguments[lIndex++] = lAction.Instance.Oid; } else { lArguments[lIndex++] = null; } } } } mSharedClasses.Add(new KeyValuePair <ONAction, object[]>(lSharedAction, lArguments)); mServiceCacheItems.Add(ONServiceCacheItem.Get("Action", lSharedArgumentInfo.ClassName, ServiceName)); } // Check State Changes if (lAction.OnContext.NeedsVerification) { mServiceCacheItem.InvoqueCheckState(lAction, lMsg.Args); lAction.OnContext.NeedsVerification = false; } // Check Shared STD lIndex = 0; foreach (KeyValuePair <ONAction, object[]> lShared in mSharedClasses) { // Take the active Instance bool lSharedFind = false; foreach (ONInstance lInstance in lAction.OnContext.TransactionStack) { if (lInstance == lShared.Key.Instance) { lShared.Key.Instance = lInstance.GetFacet(lShared.Key.Instance.ClassName); lSharedFind = true; break; } } if (!lSharedFind) { foreach (ONInstance lInstance in lAction.OnContext.OperationStack) { if (lInstance == lShared.Key.Instance) { lShared.Key.Instance = lInstance.GetFacet(lShared.Key.Instance.ClassName); lShared.Key.Instance.OnContext = lShared.Key.OnContext; break; } } } // Push OID to Class Stack lShared.Key.OnContext.TransactionStack.Push(lShared.Key.Instance); // Check STD if (!lSharedFind) { mServiceCacheItems[lIndex++].InvoqueSTD(lShared.Key, lShared.Value); } } // Take the active Instance bool lFind = false; foreach (ONInstance lInstance in lAction.OnContext.TransactionStack) { if (lInstance == lAction.Instance) { lAction.Instance = lInstance.GetFacet(lAction.Instance.ClassName); lFind = true; break; } } if (!lFind) { foreach (ONInstance lInstance in lAction.OnContext.OperationStack) { if (lInstance == lAction.Instance) { // Saving the old context of the This instance lAction.Instance = lInstance.GetFacet(lAction.Instance.ClassName); mThisOnContext = lAction.Instance.OnContext; lAction.Instance.OnContext = lAction.OnContext; break; } } } // Push OID to Class Stack lAction.OnContext.TransactionStack.Push(lAction.Instance); mInStack = true; // Check STD if (!lFind) { mServiceCacheItem.InvoqueSTD(lAction, lMsg.Args); } // Check Shared Precondition lIndex = 0; foreach (KeyValuePair <ONAction, object[]> lShared in mSharedClasses) { mServiceCacheItems[lIndex++].InvoquePrecondition(lShared.Key, lShared.Value); } // Check Precondition mServiceCacheItem.InvoquePrecondition(lAction, lMsg.Args); // Get Initial Values of the instances lAction.OnContext.GetInitialValues(lAction, lMsg.Args); // Throw Check Shared Partials lIndex = 0; foreach (KeyValuePair <ONAction, object[]> lShared in mSharedClasses) { if ((string.Compare(lAction.ClassName, lShared.Key.ClassName, true) != 0) || (lAction.Instance != lShared.Key.Instance)) { mServiceCacheItems[lIndex++].InvoqueService(lShared.Key, lShared.Value); } } }
public object UnsafeDeserializeMethodResponse(Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage) { return(this.Deserialize(serializationStream, handler, false, methodCallMessage)); }
public override IMessage Invoke(IMessage msg) { IMessage returnMessage; IMessage message; IMethodCallMessage methodCallMessage = msg as IMethodCallMessage; MethodParameters methodParameter = new MethodParameters(methodCallMessage.Args); object handle = DelegateContainer.GetHandle(typeof(T).FullName, methodCallMessage.MethodName, InterceptionType.OnEntry); if (handle != null) { ((OnEntry)handle)(methodParameter); } if (methodParameter.MethodFlow != FlowBehavior.Return) { try { try { object obj = methodCallMessage.MethodBase.Invoke(_realObject, methodParameter.Argugemts); object obj1 = obj; methodParameter.ReturnValue = obj; object handle1 = DelegateContainer.GetHandle(typeof(T).FullName, methodCallMessage.MethodName, InterceptionType.OnSuccess); if (handle1 != null) { ((OnSuccess)handle1)(methodParameter); } message = GetReturnMessage(methodParameter.ReturnValue, methodCallMessage); } catch (Exception exception1) { Exception exception = exception1; methodParameter.Exception = exception; methodParameter.MethodFlow = FlowBehavior.ThrowException; object handle2 = DelegateContainer.GetHandle(typeof(T).FullName, methodCallMessage.MethodName, InterceptionType.OnException); if (handle2 != null) { ((OnException)handle2)(methodParameter); } object obj2 = DelegateContainer.GetHandle(typeof(T).GetInterfaces()[0].FullName, "LogException", InterceptionType.OnLogException); if (obj2 != null) { Dictionary <string, object> strs = new Dictionary <string, object>(); ParameterInfo[] parameters = ((MethodInfo)methodCallMessage.MethodBase).GetParameters(); for (int i = 0; i < methodCallMessage.ArgCount; i++) { string name = parameters[i].Name; strs.Add(name, methodCallMessage.Args[i]); } ((OnLogException)obj2)(methodCallMessage.MethodName, strs, (exception.InnerException != null ? exception.InnerException : exception)); } switch (methodParameter.MethodFlow) { case FlowBehavior.Continue: case FlowBehavior.Return: { returnMessage = GetReturnMessage(methodParameter.ReturnValue, methodCallMessage); break; } case FlowBehavior.ThrowException: { returnMessage = new ReturnMessage(methodParameter.Exception, methodCallMessage); break; } default: { goto case FlowBehavior.Return; } } message = returnMessage; } } finally { object handle3 = DelegateContainer.GetHandle(typeof(T).FullName, methodCallMessage.MethodName, InterceptionType.OnExit); if (handle3 != null) { ((OnExit)handle3)(methodParameter); } } } else if (methodParameter.MethodFlow != FlowBehavior.Return) { message = new ReturnMessage(methodParameter.Exception, methodCallMessage); } else { message = GetReturnMessage(methodParameter.ReturnValue, methodCallMessage); } return(message); }
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; LogicalCallContext lcc = CallContext.GetLogicalCallContext(); object xADCall = lcc.GetData(CrossAppDomainSink.LCC_DATA_KEY); bool isCallContextSet = false; 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); isCallContextSet = true; messageCallContext.PropagateIncomingHeadersToCallContext(msg); PreserveThreadPrincipalIfNecessary(messageCallContext, oldCallCtx); // NOTE: target for dispatch will be NULL when the StackBuilderSink // is used for async delegates on static methods. // *** 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.MethodHandle, 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(); if (xADCall != null && ((bool)xADCall) == true && 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); // 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 (isCallContextSet) { CallContext.SetLogicalCallContext(oldCallCtx); } } return(retMessage); }
internal object Deserialize(Stream serializationStream, HeaderHandler handler, bool fCheck, bool isCrossAppDomain, IMethodCallMessage methodCallMessage) { if (serializationStream == null) { throw new ArgumentNullException("serializationStream", Environment.GetResourceString("ArgumentNull_WithParamName", new object[] { serializationStream })); } if (serializationStream.CanSeek && serializationStream.Length == 0L) { throw new SerializationException(Environment.GetResourceString("Serialization_Stream")); } InternalFE internalFE = new InternalFE(); internalFE.FEtypeFormat = this.m_typeFormat; internalFE.FEserializerTypeEnum = InternalSerializerTypeE.Binary; internalFE.FEassemblyFormat = this.m_assemblyFormat; internalFE.FEsecurityLevel = this.m_securityLevel; ObjectReader objectReader = new ObjectReader(serializationStream, this.m_surrogates, this.m_context, internalFE, this.m_binder); objectReader.crossAppDomainArray = this.m_crossAppDomainArray; return(objectReader.Deserialize(handler, new __BinaryParser(serializationStream, objectReader), fCheck, isCrossAppDomain, methodCallMessage)); }
/// <summary>Initializes a new instance of the <see cref="T:System.Runtime.Remoting.Messaging.MethodCallMessageWrapper" /> class by wrapping an <see cref="T:System.Runtime.Remoting.Messaging.IMethodCallMessage" /> interface.</summary><param name="msg">A message that acts as an outgoing method call on a remote object.</param> public MethodCallMessageWrapper(IMethodCallMessage msg) : base(null) { throw new NotImplementedException(); }
public void Postprocess(MarshalByRefObject inst, IMessage msg, ref IMessage msgReturn) { IMethodCallMessage lMsgIn = msg as IMethodCallMessage; IMethodReturnMessage lMsgOut = msgReturn as IMethodReturnMessage; int lIndex = 0; // Extract Action ONAction lAction = inst as ONAction; if ((ServiceType != ServiceTypeEnumeration.Destroy) && (ServiceType != ServiceTypeEnumeration.New)) { if (lAction.Instance.Modified) { // Update Instance ONData lData = ONContext.GetComponent_Data(lAction.ClassName, lAction.OnContext); lData.UpdateEdited(lAction.Instance); // Add ModifiedClass lAction.OnContext.AddModifiedClass(lAction); } else { // Add ModifiedClass lAction.OnContext.AddUnmodifiedClass(lAction); } // Update Inheritance net data foreach (ONInstance lNetInstance in lAction.Instance.GetFacets()) { if (((object)lNetInstance != null) && (lNetInstance.ClassName != lAction.ClassName) && lNetInstance.Modified) { // Update inheritance net Instance ONData lData = ONContext.GetComponent_Data(lNetInstance.ClassName, lNetInstance.OnContext); lData.UpdateEdited(lNetInstance); // Create action class ONAction lNetAction = ONContext.GetComponent_Action(lNetInstance.ClassName, lNetInstance.OnContext); lNetAction.Instance = lNetInstance; // Add inheritance net ModifiedClass lAction.OnContext.AddModifiedClass(lAction); } } if (lAction.OnContext.ModifiedClass.ContainsKey(lAction.Instance.Oid)) { ONAction lNetAction = ONContext.GetComponent_Action(lAction.Instance.Root().ClassName, lAction.Instance.Root().OnContext); lNetAction.Instance = lAction.Instance.Root(); lAction.OnContext.AddUnmodifiedClass(lNetAction); } } // Shared Event Control if (mSharedPrincipal == false) // No-Principal Shared Event { return; } lAction.OnContext.InSharedContext = false; // Calculate Shared OutboundArguments lIndex = 0; object[] lArgs = lMsgOut.Args; foreach (KeyValuePair <ONAction, object[]> lShared in mSharedClasses) { mServiceCacheItems[lIndex++].InvoqueOutboundArguments(lShared.Key, lShared.Value); // Copy outbound arguments (only not initialized) for (int i = lMsgOut.ArgCount - lMsgOut.OutArgCount; i < lMsgOut.ArgCount; i++) { if (new ONBool(lShared.Value[i] as ONSimpleType != null) || lShared.Value[i] as ONOid != null) { lArgs[i] = lShared.Value[i]; } } // Pop the Shared OID from Class Stack lAction.OnContext.TransactionStack.Pop(); } // Calculate OutboundArgumets mServiceCacheItem.InvoqueOutboundArguments(lAction, lArgs); // Pop the OID from Class Stack lAction.OnContext.TransactionStack.Pop(); mInStack = false; // Restoing the old context of the This instance if (mThisOnContext != null) { lAction.Instance.OnContext = mThisOnContext; } msgReturn = new ReturnMessage(lMsgOut.ReturnValue, lArgs, lArgs.Length, lMsgOut.LogicalCallContext, lMsgIn); if (lAction.OnContext.TransactionStack.Count == 0) { // Check triggers lAction.OnContext.CheckTriggers(); // Check integrity constraints lAction.OnContext.CheckIntegrityConstraints(); } lAction.OnContext.InstancesInitialValues.Clear(); }
public MethodCallMessageWrapperEx(IMethodCallMessage imcmsg, System.Reflection.MethodBase mb) : base(imcmsg) { this._mb = mb; }
internal static IMessage DeserializeMessage(String mimeType, Stream xstm, bool methodRequest, IMessage msg, Header[] h) { InternalRemotingServices.RemotingTrace("DeserializeMessage"); InternalRemotingServices.RemotingTrace("MimeType: " + mimeType); CoreChannel.DebugOutXMLStream(xstm, "Deserializing"); Stream fmtStm = null; bool bin64encode = false; bool doHeaderBodyAsOne = true; if (string.Compare(mimeType, BinaryMimeType, StringComparison.Ordinal) == 0) { doHeaderBodyAsOne = true; } if (string.Compare(mimeType, SOAPMimeType, StringComparison.Ordinal) == 0) { doHeaderBodyAsOne = false; } if (bin64encode == false) { fmtStm = xstm; } else { InternalRemotingServices.RemotingTrace("***************** Before base64 decode *****"); long Position = xstm.Position; MemoryStream inStm = (MemoryStream)xstm; byte[] byteArray = inStm.ToArray(); xstm.Position = Position; String base64String = Encoding.ASCII.GetString(byteArray, 0, byteArray.Length); byte[] byteArrayContent = Convert.FromBase64String(base64String); MemoryStream memStm = new MemoryStream(byteArrayContent); fmtStm = memStm; InternalRemotingServices.RemotingTrace("***************** after base64 decode *****"); } Object ret; IRemotingFormatter fmt = MimeTypeToFormatter(mimeType, false); if (doHeaderBodyAsOne == true) { ret = ((BinaryFormatter)fmt).UnsafeDeserializeMethodResponse(fmtStm, null, (IMethodCallMessage)msg); } else { InternalRemotingServices.RemotingTrace("Content"); InternalRemotingServices.RemotingTrace("***************** Before Deserialize Headers *****"); InternalRemotingServices.RemotingTrace("***************** After Deserialize Headers *****"); InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message *****"); if (methodRequest == true) { MethodCall mc = new MethodCall(h); InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message - as MethodCall *****"); fmt.Deserialize(fmtStm, new HeaderHandler(mc.HeaderHandler)); ret = mc; } else { IMethodCallMessage mcm = (IMethodCallMessage)msg; MethodResponse mr = new MethodResponse(h, mcm); InternalRemotingServices.RemotingTrace("***************** Before Deserialize Message - as MethodResponse *****"); fmt.Deserialize(fmtStm, new HeaderHandler(mr.HeaderHandler)); ret = mr; } InternalRemotingServices.RemotingTrace("***************** After Deserialize Message *****"); } // Workaround to make this method verifiable IMessage resMessage = (IMessage)ret; InternalRemotingServices.RemotingTrace("CoreChannel::DeserializeMessage OUT"); CoreChannel.DebugMessage(resMessage); return(resMessage); }
} // Invoke // This is called for all remoted calls on a TP except Ctors // The method called may be Sync, Async or OneWay(special case of Async) // In the Async case we come here for both BeginInvoke & EndInvoke internal virtual IMessage InternalInvoke( IMethodCallMessage reqMcmMsg, bool useDispatchMessage, int callType) { Message reqMsg = reqMcmMsg as Message; if ((reqMsg == null) && (callType != Message.Sync)) { // Only the synchronous call type is supported for messages that // aren't of type Message. throw new RemotingException( Environment.GetResourceString("Remoting_Proxy_InvalidCallType")); } IMessage retMsg = null; Thread currentThread = Thread.CurrentThread; // pick up call context from the thread LogicalCallContext cctx = currentThread.GetLogicalCallContext(); Identity idObj = IdentityObject; ServerIdentity serverID = idObj as ServerIdentity; if ((null != serverID) && idObj.IsFullyDisconnected()) { throw new ArgumentException( String.Format(Environment.GetResourceString("Remoting_ServerObjectNotFound"), reqMcmMsg.Uri)); } // Short-circuit calls to Object::GetType and Object::GetHashCode MethodBase mb = reqMcmMsg.MethodBase; if (_getTypeMethod == mb) { // Time to load the true type of the remote object.... Type t = GetProxiedType(); return(new ReturnMessage(t, null, 0, cctx, reqMcmMsg)); } if (_getHashCodeMethod == mb) { int hashCode = idObj.GetHashCode(); return(new ReturnMessage(hashCode, null, 0, cctx, reqMcmMsg)); } // check for channel sink if (idObj.ChannelSink == null) { throw new RemotingException( Environment.GetResourceString("Remoting_Proxy_NoChannelSink")); } // Set the identity in the message object IInternalMessage iim = (IInternalMessage)reqMcmMsg; iim.IdentityObject = idObj; if (null != serverID) { Message.DebugOut("Setting serveridentity on message \n"); iim.ServerIdentityObject = serverID; } else { // We need to set the URI only for identities that // are not the server identities. The uri is used to // dispatch methods for objects outside the appdomain. // Inside the appdomain (xcontext case) we dispatch // by getting the server object from the server identity. iim.SetURI(idObj.URI); } Message.DebugOut("InternalInvoke. Dispatching based on class type\n"); AsyncResult ar = null; switch (callType) { case Message.Sync: Message.DebugOut("RemotingProxy.Invoke Call: SyncProcessMsg\n"); BCLDebug.Assert(!useDispatchMessage, "!useDispatchMessage"); bool bSkipContextChain = false; Context currentContext = currentThread.GetCurrentContextInternal(); IMessageSink nextSink = idObj.EnvoyChain; // if we are in the default context, there can be no // client context chain, so we can skip the intermediate // calls if there are no envoy sinks if (currentContext.IsDefaultContext) { if (nextSink is EnvoyTerminatorSink) { bSkipContextChain = true; // jump directly to the channel sink nextSink = idObj.ChannelSink; } } retMsg = CallProcessMessage(nextSink, reqMcmMsg, idObj.ProxySideDynamicSinks, currentThread, currentContext, bSkipContextChain); break; case Message.BeginAsync: case Message.BeginAsync | Message.OneWay: // For async calls we clone the call context from the thread // This is a limited clone (we dont deep copy the user data) cctx = (LogicalCallContext)cctx.Clone(); iim.SetCallContext(cctx); ar = new AsyncResult(reqMsg); InternalInvokeAsync(ar, reqMsg, useDispatchMessage, callType); Message.DebugOut("Propagate out params for BeginAsync\n"); retMsg = new ReturnMessage(ar, null, 0, null /*cctx*/, reqMsg); break; case Message.OneWay: // For async calls we clone the call context from the thread // This is a limited clone (we dont deep copy the user data) cctx = (LogicalCallContext)cctx.Clone(); iim.SetCallContext(cctx); InternalInvokeAsync(null, reqMsg, useDispatchMessage, callType); retMsg = new ReturnMessage(null, null, 0, null /*cctx*/, reqMcmMsg); break; case (Message.EndAsync | Message.OneWay): retMsg = new ReturnMessage(null, null, 0, null /*cctx*/, reqMcmMsg); break; case Message.EndAsync: // For endAsync, we merge back the returned callContext // into the thread's callContext retMsg = RealProxy.EndInvokeHelper(reqMsg, true); break; } return(retMsg); }
public MethodResponse(Header[] h1, IMethodCallMessage mcm) { }
/// <summary> /// Intercept method calls /// </summary> /// <param name="myMessage"> /// Contains information about the method being called /// </param> /// <returns> /// A <see cref="ReturnMessage"/>. /// </returns> public override IMessage Invoke(IMessage myMessage) { IMethodCallMessage callMessage = myMessage as IMethodCallMessage; if (null == callMessage) { LOG.DebugFormat("Message type not implemented: {0}", myMessage.GetType().ToString()); return(null); } MethodInfo method = callMessage.MethodBase as MethodInfo; if (null == method) { LOG.DebugFormat("Unrecognized Invoke call: {0}", callMessage.MethodBase.ToString()); return(null); } object returnValue = null; object[] outArgs = null; int outArgsCount = 0; string methodName = method.Name; Type returnType = method.ReturnType; BindingFlags flags = BindingFlags.InvokeMethod; int argCount = callMessage.ArgCount; object invokeObject; Type invokeType; Type byValType; object[] args; object arg; COMWrapper[] originalArgs; COMWrapper wrapper; ParameterModifier[] argModifiers = null; ParameterInfo[] parameters = null; ParameterInfo parameter; if ("Dispose" == methodName && 0 == argCount && typeof(void) == returnType) { this.Dispose(); } else if ("ToString" == methodName && 0 == argCount && typeof(string) == returnType) { returnValue = this.ToString(); } else if ("GetType" == methodName && 0 == argCount && typeof(System.Type) == returnType) { returnValue = this._InterceptType; } else if ("GetHashCode" == methodName && 0 == argCount && typeof(int) == returnType) { returnValue = this.GetHashCode(); } else if ("Equals" == methodName && 1 == argCount && typeof(bool) == returnType) { returnValue = this.Equals(callMessage.Args[0]); } else if (1 == argCount && typeof(void) == returnType && (methodName.StartsWith("add_") || methodName.StartsWith("remove_"))) { bool removeHandler = methodName.StartsWith("remove_"); methodName = methodName.Substring(removeHandler ? 7 : 4); Delegate handler = callMessage.InArgs[0] as Delegate; if (null == handler) { return(new ReturnMessage(new ArgumentNullException("handler"), callMessage)); } } else { invokeObject = this._COMObject; invokeType = this._COMType; if (methodName.StartsWith("get_")) { // Property Get methodName = methodName.Substring(4); flags = BindingFlags.GetProperty; args = callMessage.InArgs; } else if (methodName.StartsWith("set_")) { // Property Set methodName = methodName.Substring(4); flags = BindingFlags.SetProperty; args = callMessage.InArgs; } else { args = callMessage.Args; if (null != args && 0 != args.Length) { // Modifiers for ref / out parameters argModifiers = new ParameterModifier[1]; argModifiers[0] = new ParameterModifier(args.Length); parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { parameter = parameters[i]; if (parameter.IsOut || parameter.ParameterType.IsByRef) { argModifiers[0][i] = true; outArgsCount++; } } if (0 == outArgsCount) { argModifiers = null; } } } // Un-wrap wrapped COM objects before passing to the method if (null == args || 0 == args.Length) { originalArgs = null; } else { originalArgs = new COMWrapper[args.Length]; for (int i = 0; i < args.Length; i++) { if (null != args[i] && RemotingServices.IsTransparentProxy(args[i])) { wrapper = RemotingServices.GetRealProxy(args[i]) as COMWrapper; if (null != wrapper) { originalArgs[i] = wrapper; args[i] = wrapper._COMObject; } } else if (0 != outArgsCount && argModifiers[0][i]) { byValType = GetByValType(parameters[i].ParameterType); if (byValType.IsInterface) { // If we're passing a COM object by reference, and // the parameter is null, we need to pass a // DispatchWrapper to avoid a type mismatch exception. if (null == args[i]) { args[i] = new DispatchWrapper(null); } } else if (typeof(Decimal) == byValType) { // If we're passing a decimal value by reference, // we need to pass a CurrencyWrapper to avoid a // type mismatch exception. // http://support.microsoft.com/?kbid=837378 args[i] = new CurrencyWrapper(args[i]); } } } } do { try { returnValue = invokeType.InvokeMember(methodName, flags, null, invokeObject, args, argModifiers, null, null); break; } catch (Exception ex) { // Test for rejected COMException comEx = ex as COMException; if (comEx == null) { comEx = ex.InnerException as COMException; } if (comEx != null && (comEx.ErrorCode == RPC_E_CALL_REJECTED || comEx.ErrorCode == COMWrapper.RPC_E_FAIL)) { string destinationName = _TargetName; // Try to find a "catchy" name for the rejecting application if (destinationName != null && destinationName.Contains(".")) { destinationName = destinationName.Substring(0, destinationName.IndexOf(".")); } if (destinationName == null) { destinationName = _InterceptType.FullName; } DialogResult result = MessageBox.Show(PluginUtils.Host.GreenshotForm, Language.GetFormattedString("com_rejected", destinationName), Language.GetString("com_rejected_title"), MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); if (result == DialogResult.OK) { continue; } } // Not rejected OR pressed cancel return(new ReturnMessage(ex, callMessage)); } } while (true); // Handle enum and interface return types if (null != returnValue) { if (returnType.IsInterface) { // Wrap the returned value in an intercepting COM wrapper if (Marshal.IsComObject(returnValue)) { returnValue = COMWrapper.Wrap(returnValue, returnType, _TargetName); } } else if (returnType.IsEnum) { // Convert to proper Enum type returnValue = Enum.Parse(returnType, returnValue.ToString()); } } // Handle out args if (0 != outArgsCount) { outArgs = new object[args.Length]; for (int i = 0; i < parameters.Length; i++) { if (!argModifiers[0][i]) { continue; } arg = args[i]; if (null == arg) { continue; } parameter = parameters[i]; wrapper = null; byValType = GetByValType(parameter.ParameterType); if (typeof(Decimal) == byValType) { if (arg is CurrencyWrapper) { arg = ((CurrencyWrapper)arg).WrappedObject; } } else if (byValType.IsEnum) { arg = Enum.Parse(byValType, arg.ToString()); } else if (byValType.IsInterface) { if (Marshal.IsComObject(arg)) { wrapper = originalArgs[i]; if (null != wrapper && wrapper._COMObject != arg) { wrapper.Dispose(); wrapper = null; } if (null == wrapper) { wrapper = new COMWrapper(arg, byValType, _TargetName); } arg = wrapper.GetTransparentProxy(); } } outArgs[i] = arg; } } } return(new ReturnMessage(returnValue, outArgs, outArgsCount, callMessage.LogicalCallContext, callMessage)); }
public ConstructionResponse(Header[] h, IMethodCallMessage mcm) : base(h, mcm) { }
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); }
/// <summary> /// Invokes the method and returns the object to be returned to the caller of the proxy. /// </summary> /// <param name="methodCallMessage">The method call message.</param> /// <param name="onThis">The object on which to invoke the method.</param> /// <returns>The object to be returned to the caller of the proxy.</returns> /// <exception cref="System.InvalidCastException">The value of methodCallMessage.MethodBase cannot be cast to a MethodInfo.</exception> protected abstract object InvokeMethod(IMethodCallMessage methodCallMessage, object onThis);
[System.Security.SecuritySafeCritical] // auto-generated public Object DeserializeMethodResponse(Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage) { return(Deserialize(serializationStream, handler, true, methodCallMessage)); }
/// <summary> /// 関数が呼び出された後に実行されます。 /// </summary> /// <param name="serverType">ターゲットの型です。</param> /// <param name="methodCallMessage">関数の呼び出しメッセージです。</param> public virtual void PostCallMethod(Type serverType, IMethodCallMessage methodCallMessage) { Logger?.Trace($"post-function: {serverType.FullName}::{methodCallMessage.MethodName}"); }
public override IMessage Invoke(IMessage msg) { IMethodCallMessage methodCall = (IMethodCallMessage)msg; var method = (MethodInfo)methodCall.MethodBase; if (method.DeclaringType.IsGenericType && method.DeclaringType.GetGenericTypeDefinition().FullName.Contains( "System.Runtime.InteropServices.WindowsRuntime")) { Dictionary <string, string> methodMap = new Dictionary <string, string> { // add problematic methods here { "Append", "Add" }, { "GetAt", "get_Item" } }; if (methodMap.ContainsKey(method.Name) == false) { throw new Exception("Unable to resolve '" + method.Name + "'."); } // thanks microsoft string correctMethod = methodMap[method.Name]; method = m_baseInterface.GetInterfaces().Select( i => i.GetMethod(correctMethod)).Where( mi => mi != null).FirstOrDefault(); if (method == null) { throw new Exception("Unable to resolve '" + method.Name + "' to '" + correctMethod + "'."); } } try { if (m_coreInstance == null) { var errorMessage = Resource.CoreInstanceIsNull; WriteLogs(errorMessage, TraceEventType.Error); throw new NullReferenceException(errorMessage); } var args = methodCall.Args.Select(a => { object o; if (RemotingServices.IsTransparentProxy(a)) { o = (RemotingServices.GetRealProxy(a) as ProxyBase).m_coreInstance; } else { o = a; } if (method.Name == "get_Item") { // perform parameter conversions here if (a.GetType() == typeof(UInt32)) { return(Convert.ToInt32(a)); } return(a); } return(o); }).ToArray(); // this is where it barfed var result = method.Invoke(m_coreInstance, args); // special handling for GetType() if (method.Name == "GetType") { result = m_baseInterface; } else { // special handling for interface return types if (method.ReturnType.IsInterface) { result = ProxyBase.Create(method.ReturnType, result, m_enforce, m_namingSequence); } } return(new ReturnMessage(result, args, args.Length, methodCall.LogicalCallContext, methodCall)); } catch (Exception e) { WriteLogs("Exception: " + e, TraceEventType.Error); if (e is TargetInvocationException && e.InnerException != null) { return(new ReturnMessage(e.InnerException, msg as IMethodCallMessage)); } return(new ReturnMessage(e, msg as IMethodCallMessage)); } }
/// <summary> /// メッセージシンクの処理(同期処理) /// </summary> /// <param name="msg">メソッド呼び出しのIMessage</param> /// <returns>戻り値のIMessage</returns> public IMessage SyncProcessMessage(IMessage msg) { IConstructionCallMessage ccm = msg as IConstructionCallMessage; if (ccm != null) { if (interceptorMap.Contains(ccm.MethodBase)) { ArrayList list = (ArrayList)interceptorMap[ccm.MethodBase]; IConstructorInterceptor[] intercepters = (IConstructorInterceptor[])list.ToArray(typeof(IConstructorInterceptor)); IJoinPoint jointpoint = new ConstructorInvocation(target, ccm, nextSink, intercepters); try { object[] outAuguments = null; jointpoint.FirstProceed(out outAuguments); return(new InternalConstructionResponse(outAuguments, ccm)); } catch (Exception e) { return(new InternalConstructionResponse(e, ccm)); } } else { return(nextSink.SyncProcessMessage(msg)); } } IMethodCallMessage mcm = msg as IMethodCallMessage; if (mcm != null) { if (interceptorMap.Contains(mcm.MethodBase)) { ArrayList list = (ArrayList)interceptorMap[mcm.MethodBase]; IMethodInterceptor[] intercepters = (IMethodInterceptor[])list.ToArray(typeof(IMethodInterceptor)); IJoinPoint jointpoint = new MethodInvocation(target, mcm, nextSink, intercepters); try { object[] outAuguments = null; object returnValue = jointpoint.FirstProceed(out outAuguments); if (outAuguments == null) { return(new ReturnMessage( returnValue, null, 0, mcm.LogicalCallContext, mcm)); } else { return(new ReturnMessage( returnValue, outAuguments, outAuguments.Length, mcm.LogicalCallContext, mcm)); } } catch (Exception e) { return(new ReturnMessage(e, mcm)); } } else { return(nextSink.SyncProcessMessage(msg)); } } return(nextSink.SyncProcessMessage(msg)); }
private ReturnMessage returnmessage(IMethodCallMessage callMessage, object callBackResult) { return(new ReturnMessage(callBackResult, new object[0], 0, null, callMessage)); }
/// <summary> /// コンストラクタ。コンストラクタ呼び出しに例外が発生した場合はこちらをつかいます /// </summary> /// <param name="e">コンストラクタで発生した例外</param> /// <param name="message">コンストラクタ呼び出しのIMethodCallMessage</param> public InternalConstructionResponse(Exception e, IMethodCallMessage message) : base(e, message) { }
private IMessage GetReturnMessage(object returnValue, IMethodCallMessage callMessage) { IMessage returnMessage = new ReturnMessage(returnValue, callMessage.Args, callMessage.ArgCount - callMessage.InArgCount, callMessage.LogicalCallContext, callMessage); return(returnMessage); }
internal object Deserialize(Stream serializationStream, HeaderHandler handler, bool fCheck, IMethodCallMessage methodCallMessage) { return(this.Deserialize(serializationStream, handler, fCheck, false, methodCallMessage)); }