// TODO: @cleanup: Move to ServicedComponentProxy private static void ReconnectForPooling(ServicedComponentProxy scp) { Type serverType = scp.GetProxiedType(); bool fIsJitActivated = scp.IsJitActivated; bool fIsTypePooled = scp.IsObjectPooled; bool fAreMethodsSecure = scp.AreMethodsSecure; ProxyTearoff tearoff = null; DBG.Assert(fIsTypePooled == true, "CS.ReconnectForPooling called on a non-pooled proxy!"); DBG.Info(DBG.SC, "CS.ReconnectForPooling (type is pooled) " + serverType); ServicedComponent server = scp.DisconnectForPooling(ref tearoff); // now setup a new SCP that we can add to the pool // with the current server object and the CCW ServicedComponentProxy newscp = new ServicedComponentProxy(serverType, fIsJitActivated, fIsTypePooled, fAreMethodsSecure, false); DBG.Info(DBG.SC, "CS.ReconnectForPooling (calling newscp.ConnectForPooling)"); newscp.ConnectForPooling(scp, server, tearoff, false); // switch the CCW from oldtp to new tp DBG.Info(DBG.SC, "CS.ReconnectForPooling (SwitchingWrappers)"); EnterpriseServicesHelper.SwitchWrappers(scp, newscp); // Strengthen the CCW: The only reference now held is // the reference from the pool. if (tearoff != null) { Marshal.ChangeWrapperHandleStrength(tearoff, false); } Marshal.ChangeWrapperHandleStrength(newscp.GetTransparentProxy(), false); }
//覆写Invoke,处理RealProxy截获的各种消息, //此种方式最简捷,但不能截获远程对象的激活,好在我们并不是真的要Remoting public override IMessage Invoke(IMessage msg) { var call = msg as IMethodCallMessage; IConstructionCallMessage ctr = call as IConstructionCallMessage; IMethodReturnMessage back = null; //构造函数,只有ContextBoundObject(Inherit from MarshalByRefObject)对象才能截获构造函数 if (ctr != null) { RealProxy defaultProxy = RemotingServices.GetRealProxy(_target); //如果不做下面这一步,_target还是一个没有直正实例化被代理对象的透明代理, //这样的话,会导致没有直正构建对象。 defaultProxy.InitializeServerObject(ctr); //本类是一个RealProxy,它可通过GetTransparentProxy函数得到透明代理 back = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctr, (MarshalByRefObject)GetTransparentProxy()); } //MarshalByRefObject对象就可截获普通的调用消息, //MarshalByRefObject对象告诉编译器,不能将其内部简单的成员函数优化成内联代码, //这样才能保证函数调用都能截获。 else { IDictionary <string, object> dic = new Dictionary <string, object>(); dic = call.Args[0] as IDictionary <string, object>; if (dic != null & dic.Count > 0) { foreach (var m in dic) { } } back = RemotingServices.ExecuteMessage(_target, call); } return(back); }
public override IMessage Invoke(IMessage msg) { IMethodCallMessage call = (IMethodCallMessage)msg; IConstructionCallMessage ctor = call as IConstructionCallMessage; List <Action <IMethodCallMessage> > OnMethodExecuting = new List <Action <IMethodCallMessage> >(); List <Action <IMethodCallMessage, IMethodReturnMessage> > OnMethodExecuted = new List <Action <IMethodCallMessage, IMethodReturnMessage> >(); IMethodReturnMessage returnMessage = null; if (ctor != null) { //构造函数 //获取最底层的默认真实代理 RealProxy default_proxy = RemotingServices.GetRealProxy(this.target); default_proxy.InitializeServerObject(ctor); MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy(); //自定义的透明代理 this returnMessage = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp); } else { //方法 object returnObject = null; if (!Intercept(call, ref returnObject, ref OnMethodExecuting, ref OnMethodExecuted)) { if (returnObject is IMethodReturnMessage) { returnMessage = (IMethodReturnMessage)returnObject; } else { if (returnObject == null) { var method = (MethodInfo)call.MethodBase; var returnType = method.ReturnType; if (returnType != typeof(void)) { returnObject = returnType.IsValueType ? Activator.CreateInstance(returnType) : null; } } returnMessage = new ReturnMessage(returnObject, call.Args, call.ArgCount, call.LogicalCallContext, call); } } else { OnMethodExecuting.ForEach((method) => { method(call); }); OnMethodExecuting.Clear(); try { returnMessage = RemotingServices.ExecuteMessage(this.target, call); } catch (Exception e) { returnMessage = new ReturnMessage(e, call); } OnMethodExecuted.ForEach((method) => { method(call, returnMessage); }); OnMethodExecuted.Clear(); } } return(returnMessage); }
/// <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)); } }
public override IMessage Invoke(IMessage msg) { IMethodCallMessage call = msg as IMethodCallMessage; IConstructionCallMessage ctor = msg as IConstructionCallMessage; IMethodReturnMessage result = null; if (ctor != null) // 呼び出し関数がコンストラクタの場合 { _behavior.PreInitializer(ctor); RealProxy rp = RemotingServices.GetRealProxy(_target); rp.InitializeServerObject(ctor); MarshalByRefObject tp = this.GetTransparentProxy() as MarshalByRefObject; result = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp); _behavior.PostInitializer(ctor); } else if (call != null) // 通常関数の場合 { _behavior.PreCallMethod(call); result = RemotingServices.ExecuteMessage(this._target, call); _behavior.PostCallMethod(call); } else { Console.WriteLine($"メソッドの実行に失敗しました:{msg}"); //throw new Exception($"メソッドの実行に失敗しました:{msg}"); } return(result); }
public override IMessage Invoke(IMessage msg) { var ctr = msg as IConstructionCallMessage; if (ctr != null) { Console.WriteLine("ctr"); RealProxy _proxy = RemotingServices.GetRealProxy(this._target); _proxy.InitializeServerObject(ctr); MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy(); return(EnterpriseServicesHelper.CreateConstructionReturnMessage(ctr, tp)); } if (_intercepts != null) { foreach (var _intercept in _intercepts) { _intercept.Do(); } } var call = msg as IMethodCallMessage; Console.WriteLine(string.Format("proxy method:{0}", call.MethodName)); var result = call.MethodBase.Invoke(this._target, call.Args); return(new ReturnMessage(result, new object[0], 0, null, call)); }
private ChoRealProxyInstanceState GetInstance(IConstructionCallMessage ctorCallMessage) { if (_instances.ContainsKey(ctorCallMessage.ActivationType)) { return(_instances[ctorCallMessage.ActivationType]); } lock (_padLock) { if (!_instances.ContainsKey(ctorCallMessage.ActivationType)) { IConstructionReturnMessage retMsg = InitializeServerObject(ctorCallMessage); IConstructionReturnMessage response = null; if (retMsg.Exception == null) { _target = GetUnwrappedServer(); SetStubData(this, _target); response = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctorCallMessage, (MarshalByRefObject)this.GetTransparentProxy()); } _instances.Add(ctorCallMessage.ActivationType, new ChoRealProxyInstanceState() { Target = _target, MethodMessage = response, Exception = retMsg.Exception, IsInitialized = false }); } return(_instances[ctorCallMessage.ActivationType]); } }
public override IMessage Invoke(IMessage msg) { var constructionCallMessage = msg as IConstructionCallMessage; if (constructionCallMessage != null) { if (!_injector.Attach(_exeFile)) { throw new InvalidOperationException("Not attached"); } _injector.Insider.CreateInstance(constructionCallMessage.ActivationType, constructionCallMessage.Args); return(EnterpriseServicesHelper.CreateConstructionReturnMessage(constructionCallMessage, (MarshalByRefObject)GetTransparentProxy())); } var methodCall = msg as IMethodCallMessage; if (methodCall != null) { return(_injector.Insider.Invoke(methodCall)); } throw new InvalidOperationException(); }
/// <summary> /// 實現Invoke方法 /// </summary> /// <param name="msg"></param> /// <returns></returns> public override IMessage Invoke(IMessage msg) { IMethodReturnMessage methodReturnMessage = null; IMethodCallMessage methodCallMessage = msg as IMethodCallMessage; if (methodCallMessage != null) { IConstructionCallMessage constructionCallMessage = methodCallMessage as IConstructionCallMessage; if (constructionCallMessage != null) { RealProxy defaultProxy = RemotingServices.GetRealProxy(_target); defaultProxy.InitializeServerObject(constructionCallMessage); methodReturnMessage = EnterpriseServicesHelper.CreateConstructionReturnMessage(constructionCallMessage, (MarshalByRefObject)GetTransparentProxy()); } else { _interception.PreInvoke(methodCallMessage); try { methodReturnMessage = RemotingServices.ExecuteMessage(_target, methodCallMessage); } catch { } if (methodReturnMessage.Exception != null) { _interception.ExceptionHandle(methodReturnMessage); } else { _interception.PostInvoke(methodReturnMessage); } } } return(methodReturnMessage); }
public override IMessage Invoke(IMessage msg) { IMethodCallMessage callMsg = msg as IMethodCallMessage; IMethodReturnMessage retMsg = null; bool fLog = false; //메서드 시작 로그 fLog = MethodEnterLog(callMsg); // 생성자 메서드 일경우 if (msg is IConstructionCallMessage) { // 객체 생성 메시지 처리 IConstructionCallMessage ctorMsg = (IConstructionCallMessage)msg; RealProxy proxy = RemotingServices.GetRealProxy(target); // 실제 객체를 생성한다. proxy.InitializeServerObject(ctorMsg); // 객체 생성 결과를 ‘만들어’ 반환한다. retMsg = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctorMsg, (MarshalByRefObject)this.GetTransparentProxy()); } //일반 메서드 else if (msg is IMethodCallMessage) { /* * // 파라메터 있는 메서드와 아닌 메서드 나눌때 * if (callMsg.ArgCount > 0) * { * // 파라메터 리스트 작성 * Console.WriteLine("Parameter list :"); * * for (int i = 0; i < callMsg.ArgCount; i++) * { * Console.WriteLine("{0} | {1}: {2}", i, callMsg.GetArgName(i), callMsg.GetArg(i)); * } * retMsg = RemotingServices.ExecuteMessage(target, callMsg); * } * else * { * //메소드 실행 코드 * retMsg = RemotingServices.ExecuteMessage(target, callMsg); * } */ retMsg = RemotingServices.ExecuteMessage(target, callMsg); } if (retMsg.Exception != null) { Console.WriteLine(retMsg.MethodName + " 에서 " + retMsg.Exception.Message); //Environment.Exit(0); } // 메소드 종료 로그 if (fLog) { MethodLeaveLog(retMsg); } return(retMsg); }
public override void SetCOMIUnknown(IntPtr pUnk) { if (this._server == null) { this._pUnk = pUnk; this._server = EnterpriseServicesHelper.WrapIUnknownWithComObject(pUnk); } }
/// <summary> /// Invokes the message. /// </summary> /// <param name="msg">The message.</param> /// <returns>The result of invocation.</returns> public override IMessage Invoke(IMessage msg) { IConstructionCallMessage constructorCall = msg as IConstructionCallMessage; if (constructorCall != null) { if (this.target == null) { MethodInfo factoryMethodInfo = Utility.GetInheritedMethod(constructorCall.ActivationType, DynamicConstructionAttribute.InstantiateMethodName, new[] { typeof(Type), typeof(object[]) }); if (factoryMethodInfo == null) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Cannot create an instance of type '{0}' because there is no '{1}' static method defined in its inheritance hierarchy. See '{2}' methods for an example of corresponding method signature.", constructorCall.ActivationType.AssemblyQualifiedName, DynamicConstructionAttribute.InstantiateMethodName, typeof(LiveTest).AssemblyQualifiedName)); } if (!DynamicConstructionAttribute.EnterInstantiationPhase()) { throw new InvalidOperationException("Error in instantiation workflow. Object is already in the middle of instantiation when another instance of the object is created."); } try { this.target = (LiveTest)factoryMethodInfo.Invoke(null, new object[] { constructorCall.ActivationType, constructorCall.Args }); } finally { DynamicConstructionAttribute.LeaveInstantiationPhase(); } } return(EnterpriseServicesHelper.CreateConstructionReturnMessage(constructorCall, (MarshalByRefObject)this.GetTransparentProxy())); } IMethodCallMessage methodCall = msg as IMethodCallMessage; if (methodCall != null) { methodCall = new MethodCall(methodCall); MethodCallEventArgs eventArgs = typeof(LiveTest).IsAssignableFrom(methodCall.MethodBase.DeclaringType) ? new MethodCallEventArgs(Interlocked.Increment(ref methodCallId), methodCall.MethodBase, methodCall.Args) : null; if (eventArgs != null) { this.target.OnBeforeMethodCall(this.target, eventArgs); } IMessage result = RemotingServices.GetRealProxy(this.target).Invoke(methodCall); if (eventArgs != null) { this.target.OnAfterMethodCall(this.target, eventArgs); } return(result); } throw new NotSupportedException("Operations other than constructor and method calls are not supported."); }
public override IMessage Invoke(IMessage msg) { IMessage retMsg = null; IMethodCallMessage methodCall = (IMethodCallMessage)msg; IMethodReturnMessage methodReturn = null; object[] copiedArgs = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[]; methodCall.Args.CopyTo(copiedArgs, 0); List <RaiseEventAttribute> eventRaisors = null; if (msg is IConstructionCallMessage) { IConstructionCallMessage ccm = (IConstructionCallMessage)msg; RemotingServices.GetRealProxy(target).InitializeServerObject(ccm); ObjRef oRef = RemotingServices.Marshal(target); RemotingServices.Unmarshal(oRef); retMsg = EnterpriseServicesHelper.CreateConstructionReturnMessage(ccm, (MarshalByRefObject)this.GetTransparentProxy()); } else { IMethodCallMessage mcm = (IMethodCallMessage)msg; object[] attrs = methodCall.MethodBase.GetCustomAttributes(typeof(RaiseEventAttribute), false); if (attrs != null && attrs.Count() > 0) { eventRaisors = new List <RaiseEventAttribute>(); foreach (object att in attrs) { eventRaisors.Add((RaiseEventAttribute)attrs[0]); } } try { object returnValue = methodCall.MethodBase.Invoke(this.target, copiedArgs); methodReturn = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, methodCall.LogicalCallContext, methodCall); if (eventRaisors != null) { eventRaisors.ForEach(t => SysRuntime.EventBus.RaiseEvent(t.EventType, null)); } } catch (Exception ex) { if (null != ex.InnerException) { methodReturn = new ReturnMessage(ex.InnerException, methodCall); } else { methodReturn = new ReturnMessage(ex, methodCall); } } retMsg = methodReturn; } return(retMsg); }
public override IMessage Invoke(IMessage msg) { //throw new NotImplementedException(); IMethodCallMessage call = (IMethodCallMessage)msg; IConstructionCallMessage ctor = call as IConstructionCallMessage; IMethodReturnMessage back = null; //filter method object[] attrs = call.MethodBase.GetCustomAttributes(typeof(BusinessMethodAttribute), true); bool isAopMethod = attrs.Length > 0; if (ctor != null) { //构造开始时 //do something if (this.EventConstructionBegin != null) { this.EventConstructionBegin(msg, back, this._target, null); } //执行远程对象构造方法 MarshalByRefObject mbro = this.GetTransparentProxy() as MarshalByRefObject; RealProxy realProxy = RemotingServices.GetRealProxy(this._target); realProxy.InitializeServerObject(ctor); back = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, mbro); //构造结束时 //do something if (this.EventConstructionEnd != null) { this.EventConstructionEnd(msg, back, this._target, null); } return(back); } //方法执行开始时 //do something if (this.EventMethodBegin != null && isAopMethod) { this.EventMethodBegin(msg, back, this._target, attrs[0] as BusinessMethodAttribute); } //执行远程对象方法 back = RemotingServices.ExecuteMessage(this._target, call); //方法执行结束时 //do something if (this.EventMethodEnd != null && isAopMethod) { this.EventMethodEnd(msg, back, this._target, attrs[0] as BusinessMethodAttribute); } return(back); }
public override IMessage Invoke(IMessage msg) { if (msg != null) { if (msg is IConstructionCallMessage) { IConstructionCallMessage constructCallMsg = msg as IConstructionCallMessage; //IConstructionReturnMessage constructionReturnMessage = this.InitializeServerObject((IConstructionCallMessage)msg); //RealProxy.SetStubData(this, constructionReturnMessage.ReturnValue); //return constructionReturnMessage; RealProxy defaultProxy = RemotingServices.GetRealProxy(_target); //如果不做下面这一步,_target还是一个没有直正实例化被代理对象的透明代理, //这样的话,会导致没有直正构建对象。 defaultProxy.InitializeServerObject(constructCallMsg); //本类是一个RealProxy,它可通过GetTransparentProxy函数得到透明代理 return(EnterpriseServicesHelper.CreateConstructionReturnMessage(constructCallMsg, (MarshalByRefObject)GetTransparentProxy())); } else if (msg is IMethodCallMessage) { IMethodCallMessage callMsg = msg as IMethodCallMessage; object[] args = callMsg.Args; //System.Windows.Forms.MessageBox.Show(callMsg.MethodBase.ToString()); if (callMsg.MethodName.StartsWith("set_") && args.Length == 1) { method.Invoke(_target, new object[] { callMsg.MethodName.Substring(4), args[0] });//对属性进行调用 } return(RemotingServices.ExecuteMessage(_target, callMsg)); //IMessage message = null; //try //{ // MarshalByRefObject obj = GetUnwrappedServer(); // if (callMsg.MethodName.StartsWith("set_") && args.Length == 1) // { // method.Invoke(obj, new object[] { callMsg.MethodName.Substring(4), args[0] });//对属性进行调用 // } // object o = callMsg.MethodBase.Invoke(obj, args); // message = new ReturnMessage(o, args, args.Length, callMsg.LogicalCallContext, callMsg); //} //catch (Exception e) //{ // message = new ReturnMessage(e, callMsg); //} //return message; } } return(msg); }
public IMessage LocalInvoke(IMessage reqMsg) { IMessage message = null; if (reqMsg is IConstructionCallMessage) { this.ActivateProxy(); if (this._filterConstructors) { this._filterConstructors = false; RealProxy.SetStubData(this, this._token); } if (((IConstructionCallMessage)reqMsg).ArgCount > 0) { throw new ServicedComponentException(Resource.FormatString("ServicedComponentException_ConstructorArguments")); } MarshalByRefObject transparentProxy = (MarshalByRefObject)this.GetTransparentProxy(); return(EnterpriseServicesHelper.CreateConstructionReturnMessage((IConstructionCallMessage)reqMsg, transparentProxy)); } if (reqMsg is IMethodCallMessage) { message = this.HandleSpecialMethods(reqMsg); if (message != null) { return(message); } if ((base.GetUnwrappedServer() == null) || (((IntPtr)RealProxy.GetStubData(this)) == NegativeOne)) { throw new ObjectDisposedException("ServicedComponent"); } bool flag = this.SendMethodCall(reqMsg); try { message = RemotingServices.ExecuteMessage((MarshalByRefObject)this.GetTransparentProxy(), (IMethodCallMessage)reqMsg); if (flag) { this.SendMethodReturn(reqMsg, ((IMethodReturnMessage)message).Exception); } } catch (Exception exception) { if ((exception is NullReferenceException) || (exception is SEHException)) { throw; } if (flag) { this.SendMethodReturn(reqMsg, exception); } throw; } } return(message); }
public static MarshalByRefObject CreateMonikerInstance() { IProxyCreator proxyCreator = new MonikerBuilder(); IProxyManager proxyManager = new ProxyManager(proxyCreator); Guid gUID = typeof(IMoniker).GUID; IntPtr punk = OuterProxyWrapper.CreateOuterProxyInstance(proxyManager, ref gUID); MarshalByRefObject obj2 = EnterpriseServicesHelper.WrapIUnknownWithComObject(punk) as MarshalByRefObject; Marshal.Release(punk); return(obj2); }
public override void SetCOMIUnknown(IntPtr pUnk) { if (_server == null) { DBG.Info(DBG.SC, "RSCP: SetCOMIUnknown: storing pUnk."); _pUnk = pUnk; _server = EnterpriseServicesHelper.WrapIUnknownWithComObject(pUnk); // add this to our table of weak references //IdentityTable.AddObject(_pUnk, GetTransparentProxy()); } }
public static MarshalByRefObject CreateMonikerInstance() { IProxyCreator serviceChannelBuilder = new MonikerBuilder(); IProxyManager proxyManager = new ProxyManager(serviceChannelBuilder); Guid iid = typeof(IMoniker).GUID; IntPtr ppv = OuterProxyWrapper.CreateOuterProxyInstance(proxyManager, ref iid); MarshalByRefObject ret = EnterpriseServicesHelper.WrapIUnknownWithComObject(ppv) as MarshalByRefObject; Marshal.Release(ppv); return(ret); }
// Token: 0x060001AD RID: 429 RVA: 0x000126A8 File Offset: 0x000108A8 public static object CreateDsInstance(ref Guid clsid, ref Guid riid) { IntPtr intPtr; int num = DsBugWO.CoCreateInstance(ref clsid, IntPtr.Zero, CLSCTX.Inproc, ref riid, ref intPtr); Guid guid = new Guid("00000000-0000-0000-C000-000000000046"); IntPtr intPtr2; num = Marshal.QueryInterface(intPtr, ref guid, out intPtr2); object objectValue = RuntimeHelpers.GetObjectValue(EnterpriseServicesHelper.WrapIUnknownWithComObject(intPtr)); int num2 = Marshal.Release(intPtr); return(objectValue); }
public override IMessage Invoke(IMessage msg) { Exception InnerException; msg.Properties["__Uri"] = _TcpUrl; IMessage retMsg = _messageSinks[0].SyncProcessMessage(msg); // Handle construction call message differently than other method // call messages. if (msg is IConstructionCallMessage) { // need to finish CAO activation manually. string url = GetUrlForCAO(_serverType); if (url.Length > 0) { ActivatedCAO((IConstructionCallMessage)msg, url); } IConstructionReturnMessage crm = EnterpriseServicesHelper.CreateConstructionReturnMessage((IConstructionCallMessage)msg, (MarshalByRefObject)this.GetTransparentProxy()); return(crm); } else { if (retMsg is IMethodReturnMessage) { IMethodReturnMessage mrm = (IMethodReturnMessage)retMsg; if (mrm.Exception == null) { return(retMsg); } else { InnerException = mrm.Exception; } } else { MethodCallMessageWrapper mcm = new MethodCallMessageWrapper((IMethodCallMessage)msg); mcm.Uri = RemotingServices.GetObjectUri((MarshalByRefObject)_targetTcp); return(RemotingServices.GetEnvoyChainForProxy((MarshalByRefObject)_targetTcp).SyncProcessMessage(msg)); } msg.Properties["__Uri"] = _HttpUrl; retMsg = _messageSinks[1].SyncProcessMessage(msg); if (retMsg is IMethodReturnMessage) { IMethodReturnMessage mrm = (IMethodReturnMessage)retMsg; } return(retMsg); } }
internal RemoteServicedComponentProxy(Type serverType, IntPtr pUnk, bool fAttachServer) : base(serverType) { this._fUseIntfDispatch = ServicedComponentInfo.IsTypeEventSource(serverType) || ServicedComponentInfo.AreMethodsSecure(serverType); if (pUnk != IntPtr.Zero) { this._pUnk = pUnk; this._server = EnterpriseServicesHelper.WrapIUnknownWithComObject(pUnk); if (fAttachServer) { base.AttachServer((MarshalByRefObject)this._server); this._fAttachedServer = true; } } }
public object Smuggle() { object comObject; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { comObject = EnterpriseServicesHelper.WrapIUnknownWithComObject(base.handle); GC.KeepAlive(this); } return(comObject); }
public void SetObject <T>(T obj) { if (Marshal.IsComObject(obj)) { IntPtr iUnknownForObject = Marshal.GetIUnknownForObject(obj); if (IntPtr.Zero == iUnknownForObject) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.ServiceModel.SR.GetString("UnableToRetrievepUnk"))); } try { IntPtr zero = IntPtr.Zero; Guid gUID = typeof(IPersistStream).GUID; int num = Marshal.QueryInterface(iUnknownForObject, ref gUID, out zero); if (HR.S_OK == num) { try { if (IntPtr.Zero == zero) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.ServiceModel.SR.GetString("PersistWrapperIsNull"))); } IPersistStream persistableObject = (IPersistStream)EnterpriseServicesHelper.WrapIUnknownWithComObject(zero); try { this.dataStream = PersistHelper.PersistIPersistStreamToByteArray(persistableObject); this.clsid = typeof(T).GUID; } finally { Marshal.ReleaseComObject(persistableObject); } return; } finally { Marshal.Release(zero); } } throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("CLSIDDoesNotSupportIPersistStream", new object[] { typeof(T).GUID.ToString("B") }))); } finally { Marshal.Release(iUnknownForObject); } } throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.ServiceModel.SR.GetString("NotAComObject"))); }
/// <summary> /// 执行代理方法 /// </summary> /// <param name="message"></param> /// <returns></returns> public override IMessage Invoke(IMessage message) { var callMessage = message as IMethodCallMessage; var constructionCallMessage = callMessage as IConstructionCallMessage; if (constructionCallMessage != null) { //if ctor var defaultProxy = RemotingServices.GetRealProxy(_instance); defaultProxy.InitializeServerObject(constructionCallMessage); return(EnterpriseServicesHelper.CreateConstructionReturnMessage(constructionCallMessage, (MarshalByRefObject) GetTransparentProxy())); } var processer = new Processer(_interfaceType, _instance, callMessage); if (callMessage != null) { #region Get Attributes var allFilters = new List <IAOPFilter>(); //获取类方法上的Attributes var methodFilters = GetFilterAttributes(callMessage.MethodName, callMessage.MethodSignature).ToList(); //获取类上的 var clsAttrs = _instance.GetType().GetCustomAttributes(typeof(IAOPFilter), false).Cast <IAOPFilter>(); allFilters.InsertRange(0, clsAttrs); if (_interfaceType != null && _instance.GetType() != _interfaceType) { //获取接口方法上的Attributes var interMethodAttributes = callMessage.MethodBase.GetCustomAttributes(typeof(IAOPFilter), false) .Cast <IAOPFilter>(); //获取接口上的 var interfaceAttributes = _interfaceType.GetCustomAttributes(typeof(IAOPFilter), false).Cast <IAOPFilter>(); allFilters.AddRange(interMethodAttributes.Reverse()); allFilters.InsertRange(0, interfaceAttributes); } allFilters.AddRange(methodFilters); #endregion new AOPFilterContainer(allFilters).Execute(processer); } return(processer.MethodReturnMessage); }
public override IMessage Invoke(IMessage msg) { var call = (IMethodCallMessage)msg; var ctor = call as IConstructionCallMessage; IMethodReturnMessage res; var logAttr = call.MethodBase.GetCustomAttributes(true).FirstOrDefault(r => r.GetType() == typeof(TraceLogAttribute)) as TraceLogAttribute; if (ctor != null) { //以下、コンストラクタを実行する処理 var rp = RemotingServices.GetRealProxy(this._target); res = rp.InitializeServerObject(ctor); var tp = this.GetTransparentProxy() as MarshalByRefObject; res = EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp); } else { //以下、コンストラクタ以外のメソッドを実行する処理 if (logAttr != null) { //メソッド前処理 Console.WriteLine("[{0}]{1} : 実行開始", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), logAttr.Title + "開始"); } //メソッド実行 res = RemotingServices.ExecuteMessage(this._target, call); if (res.Exception != null) { throw res.Exception; } if (logAttr != null) { //メソッド後処理 Console.WriteLine("[{0}]{1} : 実行終了", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), logAttr.Title + "終了"); } } return(res); }
public override IMessage Invoke(IMessage msg) { IMethodReturnMessage methodReturnMessage = null; var constructionCallMessage = msg as IConstructionCallMessage; if (constructionCallMessage != null) // Constructor Method. { var defaultProxy = RemotingServices.GetRealProxy(_target); defaultProxy.InitializeServerObject(constructionCallMessage); methodReturnMessage = EnterpriseServicesHelper.CreateConstructionReturnMessage(constructionCallMessage, (MarshalByRefObject)GetTransparentProxy()); return(methodReturnMessage); } var methodCallMessage = msg as IMethodCallMessage; if (methodCallMessage != null) { var methodInfo = (MethodInfo)methodCallMessage.MethodBase; var interceptMethods = _interception.InterceptMethod; // 不进行拦截 if (!interceptMethods.Any(x => { var reg = x.Replace("*", @".*"); var regx = new Regex("^" + reg + "$"); return(regx.IsMatch(methodInfo.Name)); })) { try { var obj = methodInfo.Invoke(_target, methodCallMessage.Args); return(new ReturnMessage(obj, null, 0, methodCallMessage.LogicalCallContext, methodCallMessage)); } catch (Exception ex) { return(new ReturnMessage(ex.InnerException ?? ex, methodCallMessage)); } } methodReturnMessage = Proceed(methodInfo, methodCallMessage); } return(methodReturnMessage); }
public override IMessage Invoke(IMessage message) { IMethodCallMessage caller = (IMethodCallMessage)message; // Get proxy able bool proxyAble = _proxy; if (!proxyAble) { foreach (AProxyMethodAttribute attribute in caller.MethodBase.GetCustomAttributes(typeof(AProxyMethodAttribute), false)) { if (attribute.IsProxy) { proxyAble = true; break; } } } // Process before if (proxyAble) { ProcessBefore(caller); } // Process IMethodReturnMessage response = null; IConstructionCallMessage constructor = caller as IConstructionCallMessage; if (constructor != null) { // Constructor RealProxy defaultProxy = RemotingServices.GetRealProxy(_object); defaultProxy.InitializeServerObject(constructor); MarshalByRefObject transparentProxy = (MarshalByRefObject)this.GetTransparentProxy(); response = EnterpriseServicesHelper.CreateConstructionReturnMessage(constructor, transparentProxy); } else { // Method response = RemotingServices.ExecuteMessage(_object, caller); } // Process after if (proxyAble) { ProcessAfter(caller, response); } return(response); }
public override IMessage Invoke(IMessage msg) { bool useAspect = false; IMethodCallMessage call = (IMethodCallMessage)msg; //查询目标方法是否使用了启用AOP的AopSwitcherAttribute //默认为使用Aspect var attr = CoreHelper.GetMemberAttribute <AopSwitcherAttribute>(call.MethodBase); if (attr != null) { useAspect = attr.UseAspect; } else { useAspect = true; } if (useAspect) { this.PreProceed(call); } //如果触发的是构造函数,此时target的构建还未开始 IConstructionCallMessage ctor = call as IConstructionCallMessage; if (ctor != null) { //获取最底层的默认真实代理 RealProxy default_proxy = RemotingServices.GetRealProxy(this.target); default_proxy.InitializeServerObject(ctor); MarshalByRefObject tp = (MarshalByRefObject)this.GetTransparentProxy(); //自定义的透明代理 this return(EnterpriseServicesHelper.CreateConstructionReturnMessage(ctor, tp)); } IMethodReturnMessage result_msg = RemotingServices.ExecuteMessage(this.target, call); //将消息转化为堆栈,并执行目标方法,方法完成后,再将堆栈转化为消息 if (useAspect) { this.PostProceed(call, ref result_msg); } return(result_msg); }
public static object CreateDsInstance(ref Guid clsid, ref Guid riid) { IntPtr ptr; IntPtr ptr2; int errorCode = CoCreateInstance(ref clsid, IntPtr.Zero, CLSCTX.Inproc, ref riid, out ptr); if ((errorCode != 0) || (ptr == IntPtr.Zero)) { Marshal.ThrowExceptionForHR(errorCode); } Guid iid = new Guid("00000000-0000-0000-C000-000000000046"); errorCode = Marshal.QueryInterface(ptr, ref iid, out ptr2); object obj2 = EnterpriseServicesHelper.WrapIUnknownWithComObject(ptr); Marshal.Release(ptr); return(obj2); }