コード例 #1
0
        /// <summary>
        /// 注册服务端对象,例如广播对象
        /// </summary>
        /// <param name="t">对象类型</param>
        /// <param name="obj">对象</param>
        /// <param name="uriName">注册名</param>
        /// <returns></returns>
        public string RegisteRemoteStaticObject(string dllpath, string classname, string property, string uriName)
        {
            MarshalByRefObject obj = Common.Reflection.ClassHelper.GetPropertyValue(Common.Reflection.ClassHelper.GetClassObject(dllpath, classname),
                                                                                    property, true) as MarshalByRefObject;

            return(RegisteRemoteStaticObject(obj.GetType(), obj, uriName));
        }
コード例 #2
0
 public MockingProxy(MarshalByRefObject wrappedInstance, IInterceptor interceptor, IMockMixin mockMixin)
     : base(wrappedInstance.GetType())
 {
     this.WrappedInstance = wrappedInstance;
     this.interceptor     = interceptor;
     this.mockMixin       = mockMixin;
 }
コード例 #3
0
    public MyProxy(MarshalByRefObject
target)
        : base(target.GetType())
    {
        this.target
        =
        target;
    }
コード例 #4
0
    public static void Publish(string socketPath, MarshalByRefObject obj)
    {
        IChannel channel = new UnixChannel(socketPath);

        ChannelServices.RegisterChannel(channel, false);

        RemotingServices.Marshal(obj, obj.GetType().ToString());
    }
コード例 #5
0
ファイル: stackbuildersink.cs プロジェクト: ydunk/masters
        private static void VerifyIsOkToCallMethod(Object server, IMethodMessage msg)
        {
            bool bTypeChecked      = false;
            MarshalByRefObject mbr = server as MarshalByRefObject;

            if (mbr != null)
            {
                bool     fServer;
                Identity id = MarshalByRefObject.GetIdentity(mbr, out fServer);
                if (id != null)
                {
                    ServerIdentity srvId = id as ServerIdentity;
                    if ((srvId != null) && srvId.MarshaledAsSpecificType)
                    {
                        Type srvType = srvId.ServerType;
                        if (srvType != null)
                        {
                            MethodBase mb            = GetMethodBase(msg);
                            Type       declaringType = mb.DeclaringType;

                            // make sure that srvType is not more restrictive than method base
                            // (i.e. someone marshaled with a specific type or interface exposed)
                            if ((declaringType != srvType) &&
                                !declaringType.IsAssignableFrom(srvType))
                            {
                                throw new RemotingException(
                                          String.Format(
                                              Environment.GetResourceString("Remoting_InvalidCallingType"),
                                              mb.DeclaringType.FullName, srvType.FullName));
                            }
                            // Set flag so we don't repeat this work below.
                            bTypeChecked = true;
                        }
                    }
                }

                // We must always verify that the type corresponding to
                // the method being invoked is compatible with the real server
                // type.
                if (!bTypeChecked)
                {
                    MethodBase mb            = GetMethodBase(msg);
                    Type       reflectedType = mb.ReflectedType;
                    if (!reflectedType.IsInterface)
                    {
                        if (!reflectedType.IsInstanceOfType(mbr))
                        {
                            throw new RemotingException(
                                      String.Format(
                                          Environment.GetResourceString("Remoting_InvalidCallingType"),
                                          reflectedType.FullName,
                                          mbr.GetType().FullName));
                        }
                    }
                }
            }
        } // VerifyIsOkToCallMethod
コード例 #6
0
ファイル: FilterInfoModel.cs プロジェクト: SeanLiao7/AopLib
        public FilterInfoModel(MarshalByRefObject target, MethodInfo method)
        {
            var classAttributes  = target.GetType( ).GetCustomAttributes(typeof(Attribute), true);
            var methodAttributes = Attribute.GetCustomAttributes(method, typeof(Attribute), true);
            var unionAttributes  = classAttributes.Union(methodAttributes).ToList( );

            ExecuteFilters   = unionAttributes.OfType <IExecuteFilter>( ).ToList( );
            ExceptionFilters = unionAttributes.OfType <IExceptionFilter>( ).ToList( );
        }
コード例 #7
0
        public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
        {
            if (obj.GetType().GetCustomAttributes(typeof(ONContextAttribute), true).Length > 0)
            {
                nextSink = new ONContextInterceptor(obj, nextSink, mOnContextClass);
            }

            return(nextSink);
        }
コード例 #8
0
        protected string Filter(string ReturnValue, string MethodName)
        {
            MethodInfo methodInfo = target.GetType().GetMethod(MethodName);

            object[] attributes = methodInfo.GetCustomAttributes(typeof(StringFilter), true);
            foreach (object attrib in attributes)
            {
                return(FilterHandler.Process(((StringFilter)attrib).FilterType, ReturnValue));
            }
            return(ReturnValue);
        }
コード例 #9
0
    public FilterInfo(MarshalByRefObject target, MethodInfo method)
    {
        //search for class Attribute
        var classAttr = target.GetType().GetCustomAttributes(typeof(AopBaseAttribute), true);
        //search for method Attribute
        var methodAttr = Attribute.GetCustomAttributes(method, typeof(AopBaseAttribute), true);

        var unionAttr = classAttr.Union(methodAttr);

        _excuteFilters.AddRange(unionAttr.OfType <IExcuteFilter>());
    }
コード例 #10
0
 /// <summary>
 /// アスペクトをインスタンスにWeaveする
 /// </summary>
 /// <param name="aspect">Weaveするアスペクト</param>
 /// <exception cref="CanNotWeaveAspectException">
 /// 引数のインスタンスがWeave不可能なインスタンスの場合この例外を投げる
 /// </exception>
 public void Weave(IAspect aspect)
 {
     if (!RemotingServices.IsTransparentProxy(target))
     {
         throw new CanNotWeaveAspectException();
     }
     foreach (ConstructorInfo ci in target.GetType().GetConstructors())
     {
         if (aspect.Pointcut.IsApplied(ci))
         {
             if (interceptorMap.Contains(ci))
             {
                 ArrayList list = (ArrayList)interceptorMap[ci];
                 list.Add(aspect.Interceptor);
             }
             else
             {
                 ArrayList list = new ArrayList();
                 list.Add(aspect.Interceptor);
                 interceptorMap.Add(ci, list);
             }
         }
     }
     foreach (MethodInfo mi in target.GetType().GetMethods())
     {
         if (aspect.Pointcut.IsApplied(mi))
         {
             if (interceptorMap.Contains(mi))
             {
                 ArrayList list = (ArrayList)interceptorMap[mi];
                 list.Add(aspect.Interceptor);
             }
             else
             {
                 ArrayList list = new ArrayList();
                 list.Add(aspect.Interceptor);
                 interceptorMap.Add(mi, list);
             }
         }
     }
 }
コード例 #11
0
        private Stream PrepareLocationFwdStream(string host, ushort port,
                                                MarshalByRefObject target)
        {
            // loc fwd ior
            byte[] objectKey    = IorUtil.GetObjectKeyForObj(target);
            string repositoryID = Repository.GetRepositoryID(target.GetType());
            // this server support GIOP 1.2 --> create an GIOP 1.2 profile
            InternetIiopProfile profile = new InternetIiopProfile(new GiopVersion(1, 2), host,
                                                                  port, objectKey);

            profile.AddTaggedComponent(Services.CodeSetService.CreateDefaultCodesetComponent(m_codec));
            Ior locFwdTarget = new Ior(repositoryID, new IorProfile[] { profile });
            CdrOutputStreamImpl iorStream = new CdrOutputStreamImpl(new MemoryStream(),
                                                                    0, new GiopVersion(1, 2));

            locFwdTarget.WriteToStream(iorStream);
            uint encodedIorLength = (uint)iorStream.GetPosition();

            // create the location fwd reply
            MemoryStream        sourceStream = new MemoryStream();
            CdrOutputStreamImpl cdrOut       = new CdrOutputStreamImpl(sourceStream, 0, new GiopVersion(1, 2));

            cdrOut.WriteOpaque(m_giopMagic);
            // version
            cdrOut.WriteOctet(1);
            cdrOut.WriteOctet(2);
            // flags
            cdrOut.WriteOctet(0);
            // msg-type: reply
            cdrOut.WriteOctet(1);

            // msg-length
            cdrOut.WriteULong(28 + encodedIorLength);
            // request-id
            cdrOut.WriteULong(5);
            // reply-status: location fwd
            cdrOut.WriteULong(3);
            // one service context to enforce alignement requirement for giop 1.2
            cdrOut.WriteULong(1);
            cdrOut.WriteULong(162739); // service context id
            cdrOut.WriteULong(2);      // length of svc context
            cdrOut.WriteBool(true);
            cdrOut.WriteBool(false);
            // svc context end
            // body: 8 aligned
            cdrOut.ForceWriteAlign(Aligns.Align8);

            locFwdTarget.WriteToStream(cdrOut);

            sourceStream.Seek(0, SeekOrigin.Begin);
            return(sourceStream);
        }
コード例 #12
0
        public override IMessage Invoke(IMessage myIMessage)
        {
            MarshalByRefObject obj2 = (MarshalByRefObject)Activator.CreateInstance(this._type);
            string             uRI  = RemotingServices.Marshal(obj2).URI;

            myIMessage.Properties["__Uri"] = uRI;
            Type type = obj2.GetType();
            IMethodCallMessage callMessage = (IMethodCallMessage)myIMessage;
            MethodInfo pMehotdInfo = type.GetMethods().Where <MethodInfo>(delegate(MethodInfo x)
            {
                return(x.ToString().Equals(callMessage.MethodBase.ToString()));
            }).FirstOrDefault <MethodInfo>();

            if (pMehotdInfo == null)
            {
                this.MethodNotFound(callMessage.MethodName, type.ToString());
            }
            IMessage         message = null;
            TransactionScope scope   = null;
            bool             flag    = false;

            try
            {
                if (this.UsingTransaction)
                {
                    scope = new TransactionScope();
                }
                this.BeforeInvoke();
                if (this.ValidateCanInvoke(pMehotdInfo))
                {
                    message = ChannelServices.SyncDispatchMessage(myIMessage);
                }
                this.AfterInvoke();
            }
            catch
            {
                flag = true;
                throw;
            }
            finally
            {
                if (scope != null)
                {
                    if (!flag)
                    {
                        scope.Complete();
                    }
                    scope.Dispose();
                }
            }
            return(message);
        }
コード例 #13
0
 internal ServerIdentity(MarshalByRefObject obj, Context serverCtx) : base(obj is ContextBoundObject)
 {
     if (obj != null)
     {
         if (!RemotingServices.IsTransparentProxy(obj))
         {
             this._srvType = obj.GetType();
         }
         else
         {
             this._srvType = RemotingServices.GetRealProxy(obj).GetProxiedType();
         }
     }
     this._srvCtx            = serverCtx;
     this._serverObjectChain = null;
     this._stackBuilderSink  = null;
 }
コード例 #14
0
ファイル: serveridentity.cs プロジェクト: ydunk/masters
        //   Creates a new server identity. This form is used by RemotingServices.Wrap
        //
        internal ServerIdentity(MarshalByRefObject obj, Context serverCtx) : base(obj is ContextBoundObject)
        {
            if (null != obj)
            {
                if (!RemotingServices.IsTransparentProxy(obj))
                {
                    _srvType = obj.GetType();
                }
                else
                {
                    RealProxy rp = RemotingServices.GetRealProxy(obj);
                    _srvType = rp.GetProxiedType();
                }
            }

            _srvCtx            = serverCtx;
            _serverObjectChain = null;
            _stackBuilderSink  = null;
            _refCount          = 0;
        }
コード例 #15
0
ファイル: RemotingServices.cs プロジェクト: gustavo-melo/mono
		internal static IMethodReturnMessage InternalExecuteMessage (
		        MarshalByRefObject target, IMethodCallMessage reqMsg)
		{
			ReturnMessage result;
			
			Type tt = target.GetType ();
			MethodBase method;
			if (reqMsg.MethodBase.DeclaringType == tt ||
			    reqMsg.MethodBase == FieldSetterMethod || 
			    reqMsg.MethodBase == FieldGetterMethod) {
				method = reqMsg.MethodBase;
			} else {
				method = GetVirtualMethod (tt, reqMsg.MethodBase);

				if (method == null)
					throw new RemotingException (
						String.Format ("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
			}

			if (reqMsg.MethodBase.IsGenericMethod) {
				Type[] genericArguments = reqMsg.MethodBase.GetGenericArguments ();
				MethodInfo gmd = ((MethodInfo)method).GetGenericMethodDefinition ();
				method = gmd.MakeGenericMethod (genericArguments);
			}

			object oldContext = CallContext.SetCurrentCallContext (reqMsg.LogicalCallContext);
			
			try 
			{
				object [] out_args;
				object rval = InternalExecute (method, target, reqMsg.Args, out out_args);
			
				// Collect parameters with Out flag from the request message
				// FIXME: This can be done in the unmanaged side and will be
				// more efficient
				
				ParameterInfo[] parameters = method.GetParameters();
				object[] returnArgs = new object [parameters.Length];
				
				int n = 0;
				int noa = 0;
				foreach (ParameterInfo par in parameters)
				{
					if (par.IsOut && !par.ParameterType.IsByRef) 
						returnArgs [n++] = reqMsg.GetArg (par.Position);
					else if (par.ParameterType.IsByRef)
						returnArgs [n++] = out_args [noa++]; 
					else
						returnArgs [n++] = null; 
				}
				
				result = new ReturnMessage (rval, returnArgs, n, CallContext.CreateLogicalCallContext (true), reqMsg);
			} 
			catch (Exception e) 
			{
				result = new ReturnMessage (e, reqMsg);
			}
			
			CallContext.RestoreCallContext (oldContext);
			return result;
		}
コード例 #16
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage lMethodMsg = msg as IMethodCallMessage;
            IMessage           lMsgOut    = null;

            if (lMethodMsg is IConstructionCallMessage)
            {
                mTargetType = lMethodMsg.MethodBase.DeclaringType;
                mMethod     = lMethodMsg.MethodBase;
                mArgs       = lMethodMsg.Args;

                RealProxy lRealProxy = RemotingServices.GetRealProxy(mTarget);
                lRealProxy.InitializeServerObject((IConstructionCallMessage)lMethodMsg);

                MarshalByRefObject lTransparentProxy = (MarshalByRefObject)GetTransparentProxy();
                IMessage           lReturnMessage    = EnterpriseServicesHelper.CreateConstructionReturnMessage((IConstructionCallMessage)lMethodMsg, lTransparentProxy);

                return(lReturnMessage);
            }
            else
            {
                mMethod = lMethodMsg.MethodBase;
                mArgs   = lMethodMsg.Args;

                // Initialize variables AOP
                Initprocess(msg);

                try
                {
                    // Execute Preprocess AOP
                    Preprocess(msg);

                    try
                    {
                        if (string.Compare(mMethod.Name, "FieldGetter", true) == 0)
                        {
                            FieldInfo lFieldInfo = mTarget.GetType().GetField(lMethodMsg.Args[1] as string);
                            mReturnValue = lFieldInfo.GetValue(mTarget);
                        }
                        else
                        {
                            MethodInfo lMethodInfo = mTarget.GetType().GetMethod(mMethod.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
                            if (lMethodInfo == null)
                            {
                                lMethodInfo = mTarget.GetType().GetMethod(mMethod.Name, BindingFlags.Instance | BindingFlags.Public);
                            }
                            mReturnValue = lMethodInfo.Invoke(mTarget, mArgs);
                        }
                        lMsgOut = new ReturnMessage(mReturnValue, mArgs, lMethodMsg.ArgCount, lMethodMsg.LogicalCallContext, lMethodMsg);
                    }
                    catch (Exception e)
                    {
                        throw e.InnerException;
                    }

                    // Execute Preprocess AOP
                    Postprocess(msg, ref lMsgOut);
                }
                catch (Exception e)
                {
                    // Execute Preprocess AOP
                    Exceptionprocess(msg, e);

                    throw;
                }

                return(lMsgOut);
            }
        }
コード例 #17
0
        public override MarshalByRefObject CreateInstance(Type serverType)
        {
            // Platform.Assert(Platform.W2K, "ServicedComponent");

            RealProxy          rp = null;
            MarshalByRefObject mo = null;

            DBG.Info(DBG.SC, "SCPA.CreateInstance(" + serverType + ") for managed request");


            ServicedComponentProxy.CleanupQueues(true);

            // First check if the type is configured to be activated remotely or is a well
            // known remote type.
            if ((null != RemotingConfiguration.IsWellKnownClientType(serverType)) ||
                (null != RemotingConfiguration.IsRemotelyActivatedClientType(serverType)))
            {
                // It is configured for remote activation. Ask remoting services to do the
                // job of creating a remoting proxy and returning it.
                mo = base.CreateInstance(serverType);
                rp = RemotingServices.GetRealProxy(mo);
            }
            else
            {
                bool   bIsAnotherProcess = false;
                string uri         = "";
                bool   bEventClass = ServicedComponentInfo.IsTypeEventSource(serverType);
                IntPtr pUnk        = Thunk.Proxy.CoCreateObject(serverType, !bEventClass, ref bIsAnotherProcess, ref uri);
                if (pUnk != IntPtr.Zero)
                {
                    try {
                        // TODO:  Get rid of this useless foreknowledge requirement
                        // Is there a way we can tell by QI'ing this guy if he's
                        // an event class (or something else we need to artificially
                        // wrap?
                        if (bEventClass)
                        {
                            // events and queued components use RemoteServicedComponentProxy
                            // set up a TP & Remote ServicedComponentProxy pair
                            rp = new RemoteServicedComponentProxy(serverType, pUnk, true);
                            mo = (MarshalByRefObject)rp.GetTransparentProxy();
                        }
                        else
                        {
                            if (bIsAnotherProcess)              // a-ha, we know it should be a RSCP now !!!!
                            {
                                FastRSCPObjRef oref = new FastRSCPObjRef(pUnk, serverType, uri);
                                mo = (MarshalByRefObject)RemotingServices.Unmarshal(oref);

                                DBG.Assert(mo != null, "RemotingServices.Unmarshal returned null!");
                                DBG.Assert(RemotingServices.GetRealProxy(mo) is RemoteServicedComponentProxy, "RemotingServices.Unmarshal did not return an RSCP!");
                            }
                            else        // bummer, this will give us back a SCP
                            {
                                mo = (MarshalByRefObject)Marshal.GetObjectForIUnknown(pUnk);

                                DBG.Info(DBG.SC, "ret = " + mo.GetType());
                                DBG.Info(DBG.SC, "st = " + serverType);
                                DBG.Info(DBG.SC, "rt == sc = " + (mo.GetType() == serverType));
                                DBG.Info(DBG.SC, "instanceof = " + serverType.IsInstanceOfType(mo));

                                if (!(serverType.IsInstanceOfType(mo)))
                                {
                                    throw new InvalidCastException(Resource.FormatString("ServicedComponentException_UnexpectedType", serverType, mo.GetType()));
                                }

                                rp = RemotingServices.GetRealProxy(mo);
                                if (!(rp is ServicedComponentProxy) && !(rp is RemoteServicedComponentProxy))
                                {
                                    // in cross-appdomain scenario, we get back a RemotingProxy, SetCOMIUnknown has not been made on our server!
                                    ServicedComponent sc = (ServicedComponent)mo;
                                    sc.DoSetCOMIUnknown(pUnk);
                                }
                            }
                        }
                    }
                    finally
                    {
                        Marshal.Release(pUnk);
                    }
                }
            }

            if (rp is ServicedComponentProxy)
            {
                // Here, we tell the server proxy that it needs to filter out
                // constructor calls:  We only need to do this if
                // the proxy lives in the same context as the caller,
                // otherwise we'll get an Invoke call and can do the
                // filtering automagically:
                ServicedComponentProxy scp = (ServicedComponentProxy)rp;
                if (scp.HomeToken == Thunk.Proxy.GetCurrentContextToken())
                {
                    scp.FilterConstructors();
                }
            }

            DBG.Assert(mo is ServicedComponent, " CoCI returned an invalid object type");
            DBG.Info(DBG.SC, "SCPA.CreateInstance done.");
            return(mo);
        }
コード例 #18
0
ファイル: IORUtil.cs プロジェクト: arttsai/IIOP-dot-Net
 /// <summary>
 /// creates an IOR for an object hosted in the local appdomain.
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 internal static Ior CreateIorForObjectFromThisDomain(MarshalByRefObject obj)
 {
     return(CreateIorForObjectFromThisDomain(obj, obj.GetType(), false));
 }
コード例 #19
0
 public FilterRealProxyHandler(MarshalByRefObject target)
     : base(target.GetType())
 {
     this.target = target;
 }
コード例 #20
0
        private static MarshalByRefObject IsCurrentContextOK(RuntimeType serverType, object[] props, bool bNewObj)
        {
            MarshalByRefObject proxy = null;

            InitActivationServices();
            ProxyAttribute proxyAttribute = GetProxyAttribute(serverType);

            if (object.ReferenceEquals(proxyAttribute, DefaultProxyAttribute))
            {
                return(proxyAttribute.CreateInstanceInternal(serverType));
            }
            proxy = proxyAttribute.CreateInstance(serverType);
            if (((proxy != null) && !RemotingServices.IsTransparentProxy(proxy)) && !serverType.IsAssignableFrom(proxy.GetType()))
            {
                throw new RemotingException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Activation_BadObject"), new object[] { serverType }));
            }
            return(proxy);
        }
コード例 #21
0
        private static void VerifyIsOkToCallMethod(object server, IMethodMessage msg)
        {
            bool flag = false;
            MarshalByRefObject obj2 = server as MarshalByRefObject;

            if (obj2 != null)
            {
                bool     flag2;
                Identity identity = MarshalByRefObject.GetIdentity(obj2, out flag2);
                if (identity != null)
                {
                    ServerIdentity identity2 = identity as ServerIdentity;
                    if ((identity2 != null) && identity2.MarshaledAsSpecificType)
                    {
                        Type serverType = identity2.ServerType;
                        if (serverType != null)
                        {
                            MethodBase  methodBase    = GetMethodBase(msg);
                            RuntimeType declaringType = (RuntimeType)methodBase.DeclaringType;
                            if ((declaringType != serverType) && !declaringType.IsAssignableFrom(serverType))
                            {
                                throw new RemotingException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"), new object[] { methodBase.DeclaringType.FullName, serverType.FullName }));
                            }
                            if (declaringType.IsInterface)
                            {
                                VerifyNotIRemoteDispatch(declaringType);
                            }
                            flag = true;
                        }
                    }
                }
                if (!flag)
                {
                    RuntimeType reflectedType = (RuntimeType)GetMethodBase(msg).ReflectedType;
                    if (!reflectedType.IsInterface)
                    {
                        if (!reflectedType.IsInstanceOfType(obj2))
                        {
                            throw new RemotingException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"), new object[] { reflectedType.FullName, obj2.GetType().FullName }));
                        }
                    }
                    else
                    {
                        VerifyNotIRemoteDispatch(reflectedType);
                    }
                }
            }
        }
コード例 #22
0
 public MyProxy(MarshalByRefObject target) : base(target.GetType())
 {
     this.target = target;
 }
コード例 #23
0
ファイル: RemotingServices.cs プロジェクト: zhufengGNSS/mono
        internal static IMethodReturnMessage InternalExecuteMessage(
            MarshalByRefObject target, IMethodCallMessage reqMsg)
        {
            ReturnMessage result;

            Type       tt = target.GetType();
            MethodBase method;

            if (reqMsg.MethodBase.DeclaringType == tt ||
                reqMsg.MethodBase == FieldSetterMethod ||
                reqMsg.MethodBase == FieldGetterMethod)
            {
                method = reqMsg.MethodBase;
            }
            else
            {
                method = GetVirtualMethod(tt, reqMsg.MethodBase);

                if (method == null)
                {
                    throw new RemotingException(
                              String.Format("Cannot resolve method {0}:{1}", tt, reqMsg.MethodName));
                }
            }

            if (reqMsg.MethodBase.IsGenericMethod)
            {
                Type[]     genericArguments = reqMsg.MethodBase.GetGenericArguments();
                MethodInfo gmd = ((MethodInfo)method).GetGenericMethodDefinition();
                method = gmd.MakeGenericMethod(genericArguments);
            }

            var oldContext = CallContext.SetLogicalCallContext(reqMsg.LogicalCallContext);

            try
            {
                object [] out_args;
                object    rval = InternalExecute(method, target, reqMsg.Args, out out_args);

                // Collect parameters with Out flag from the request message
                // FIXME: This can be done in the unmanaged side and will be
                // more efficient

                ParameterInfo[] parameters = method.GetParameters();
                object[]        returnArgs = new object [parameters.Length];

                int n   = 0;
                int noa = 0;
                foreach (ParameterInfo par in parameters)
                {
                    if (par.IsOut && !par.ParameterType.IsByRef)
                    {
                        returnArgs [n++] = reqMsg.GetArg(par.Position);
                    }
                    else if (par.ParameterType.IsByRef)
                    {
                        returnArgs [n++] = out_args [noa++];
                    }
                    else
                    {
                        returnArgs [n++] = null;
                    }
                }

                var latestCallContext = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
                result = new ReturnMessage(rval, returnArgs, n, latestCallContext, reqMsg);
            }
            catch (Exception e)
            {
                result = new ReturnMessage(e, reqMsg);
            }

            CallContext.SetLogicalCallContext(oldContext);
            return(result);
        }
コード例 #24
0
        public override IMessage Invoke(IMessage msg)
        {
            MethodCallMessageWrapper mc    = new MethodCallMessageWrapper((IMethodCallMessage)msg);
            MarshalByRefObject       owner = GetUnwrappedServer();
            MethodInfo mi = (MethodInfo)mc.MethodBase;

            Log.Trace("OS Proxy class invoking method " + mi.Name + " in class " + _originalObject.GetType().FullName);

            object outVal = null;
            bool   isGet;

            if (mi.Name == "GetType")
            {
                outVal = _originalObject.GetType();
            }
            else
            {
                PropertyInfo pi = GetMethodProperty(mi, _originalObject, out isGet);
                if (pi != null)
                {
                    if (pi.GetCustomAttributes(typeof(OperatingSystemOverridablePropertyAttribute), false).Length > 0)
                    {
                        Log.Trace("Detected overridable property of " + pi.Name + " in type " + _originalObject.GetType().ToString());
                        if (_propertyOverrides.ContainsKey(pi.Name))
                        {
                            Log.Trace("Overriding property call " + pi.Name + " for class " + owner.GetType().FullName + " using class " + _propertyOverrides[pi.Name].OverrideClass.FullName);
                            Monitor.Enter(_producedClasses);
                            if (!_producedClasses.ContainsKey(_propertyOverrides[pi.Name].OverrideClass))
                            {
                                _producedClasses.Add(_propertyOverrides[pi.Name].OverrideClass,
                                                     _propertyOverrides[pi.Name].OverrideClass.GetConstructor(Type.EmptyTypes).Invoke(new object[0]));
                            }
                            owner = (MarshalByRefObject)_producedClasses[_propertyOverrides[pi.Name].OverrideClass];
                            Monitor.Exit(_producedClasses);
                            mi = (isGet ? _propertyOverrides[pi.Name].Property.GetGetMethod() : _propertyOverrides[pi.Name].Property.GetSetMethod());
                        }
                    }
                }
                else
                {
                    if (mi.GetCustomAttributes(typeof(OperatingSystemOverridableFunctionAttribute), false).Length > 0)
                    {
                        Log.Trace("Detected overridable method of " + mi.Name + " in type " + _originalObject.GetType().ToString());
                        if (_methodOverrides.ContainsKey(mi.Name))
                        {
                            foreach (sMethodOverride smo in _methodOverrides[mi.Name])
                            {
                                if (smo.IsMatchForMethod(mi))
                                {
                                    Log.Trace("Overriding method call " + mi.Name + " for class " + owner.GetType().FullName + " using class " + smo.OverrideClass.FullName);
                                    Monitor.Enter(_producedClasses);
                                    if (!_producedClasses.ContainsKey(smo.OverrideClass))
                                    {
                                        _producedClasses.Add(smo.OverrideClass,
                                                             smo.OverrideClass.GetConstructor(Type.EmptyTypes).Invoke(new object[0]));
                                    }
                                    owner = (MarshalByRefObject)_producedClasses[smo.OverrideClass];
                                    Monitor.Exit(_producedClasses);
                                    mi = smo.Method;
                                }
                            }
                        }
                    }
                }
                outVal = mi.Invoke(owner, mc.Args);
            }
            return(new ReturnMessage(outVal, mc.Args, mc.Args.Length, mc.LogicalCallContext, mc));
        }
コード例 #25
0
        [System.Security.SecurityCritical]  // auto-generated
        private static void VerifyIsOkToCallMethod(Object server, IMethodMessage msg)
        {
            bool bTypeChecked      = false;
            MarshalByRefObject mbr = server as MarshalByRefObject;

            if (mbr != null)
            {
                bool     fServer;
                Identity id = MarshalByRefObject.GetIdentity(mbr, out fServer);
                if (id != null)
                {
                    ServerIdentity srvId = id as ServerIdentity;
                    if ((srvId != null) && srvId.MarshaledAsSpecificType)
                    {
                        Type srvType = srvId.ServerType;
                        if (srvType != null)
                        {
                            MethodBase  mb            = GetMethodBase(msg);
                            RuntimeType declaringType = (RuntimeType)mb.DeclaringType;

                            // make sure that srvType is not more restrictive than method base
                            // (i.e. someone marshaled with a specific type or interface exposed)
                            if ((declaringType != srvType) &&
                                !declaringType.IsAssignableFrom(srvType))
                            {
                                throw new RemotingException(
                                          String.Format(
                                              CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"),
                                              mb.DeclaringType.FullName, srvType.FullName));
                            }
                            // Set flag so we don't repeat this work below.
                            if (declaringType.IsInterface)
                            {
                                VerifyNotIRemoteDispatch(declaringType);
                            }
                            bTypeChecked = true;
                        }
                    }
                }

                // We must always verify that the type corresponding to
                // the method being invoked is compatible with the real server
                // type.
                if (!bTypeChecked)
                {
                    MethodBase  mb            = GetMethodBase(msg);
                    RuntimeType reflectedType = (RuntimeType)mb.ReflectedType;
                    if (!reflectedType.IsInterface)
                    {
                        if (!reflectedType.IsInstanceOfType(mbr))
                        {
                            throw new RemotingException(
                                      String.Format(
                                          CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"),
                                          reflectedType.FullName,
                                          mbr.GetType().FullName));
                        }
                    }
                    // This code prohibits calls made to System.EnterpriseServices.IRemoteDispatch
                    // so that remote call cannot bypass lowFilterLevel logic in the serializers.
                    // This special casing should be removed in the future
                    else
                    {
                        VerifyNotIRemoteDispatch(reflectedType);
                    }
                }
            }
        } // VerifyIsOkToCallMethod
コード例 #26
0
ファイル: RemotingServices.cs プロジェクト: gustavo-melo/mono
		public static ObjRef Marshal (MarshalByRefObject Obj, string ObjURI, Type RequestedType)
		{
			if (IsTransparentProxy (Obj))
			{
				RealProxy proxy = RemotingServices.GetRealProxy (Obj);
				Identity identity = proxy.ObjectIdentity;

				if (identity != null)
				{
					if (proxy.GetProxiedType().IsContextful && !identity.IsConnected)
					{
						// Unregistered local contextbound object. Register now.
						ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
						if (ObjURI == null) ObjURI = NewUri();
						cboundIdentity.ObjectUri = ObjURI;
						RegisterServerIdentity (cboundIdentity);
						cboundIdentity.StartTrackingLifetime ((ILease)Obj.InitializeLifetimeService());
						return cboundIdentity.CreateObjRef (RequestedType);
					}
					else if (ObjURI != null)
						throw new RemotingException ("It is not possible marshal a proxy of a remote object.");

					ObjRef or = proxy.ObjectIdentity.CreateObjRef (RequestedType);
					TrackingServices.NotifyMarshaledObject (Obj, or);
					return or;
				}
			}

			if (RequestedType == null) RequestedType = Obj.GetType ();

			if (ObjURI == null) 
			{
				if (Obj.ObjectIdentity == null)
				{
					ObjURI = NewUri();
					CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
				}
			}
			else
			{
				ClientActivatedIdentity identity = GetIdentityForUri ("/" + ObjURI) as ClientActivatedIdentity;
				if (identity == null || Obj != identity.GetServerObject()) 
					CreateClientActivatedServerIdentity (Obj, RequestedType, ObjURI);
			}

			ObjRef oref;
			
			if (IsTransparentProxy (Obj))
				oref = RemotingServices.GetRealProxy (Obj).ObjectIdentity.CreateObjRef (RequestedType);
			else
				oref = Obj.CreateObjRef (RequestedType);
			
			TrackingServices.NotifyMarshaledObject (Obj, oref);
			return oref;
		}
コード例 #27
0
        internal void Init(object o, Identity idObj, RuntimeType requestedType)
        {
            this.uri = idObj.URI;
            MarshalByRefObject tporObject = idObj.TPOrObject;
            RuntimeType        runtimeType;

            if (!RemotingServices.IsTransparentProxy(tporObject))
            {
                runtimeType = (RuntimeType)tporObject.GetType();
            }
            else
            {
                runtimeType = (RuntimeType)RemotingServices.GetRealProxy(tporObject).GetProxiedType();
            }
            RuntimeType runtimeType2 = (null == requestedType) ? runtimeType : requestedType;

            if (null != requestedType && !requestedType.IsAssignableFrom(runtimeType) && !typeof(IMessageSink).IsAssignableFrom(runtimeType))
            {
                throw new RemotingException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidRequestedType"), requestedType.ToString()));
            }
            if (runtimeType.IsCOMObject)
            {
                DynamicTypeInfo dynamicTypeInfo = new DynamicTypeInfo(runtimeType2);
                this.TypeInfo = dynamicTypeInfo;
            }
            else
            {
                RemotingTypeCachedData reflectionCachedData = InternalRemotingServices.GetReflectionCachedData(runtimeType2);
                this.TypeInfo = reflectionCachedData.TypeInfo;
            }
            if (!idObj.IsWellKnown())
            {
                this.EnvoyInfo = System.Runtime.Remoting.EnvoyInfo.CreateEnvoyInfo(idObj as ServerIdentity);
                IChannelInfo channelInfo = new ChannelInfo();
                if (o is AppDomain)
                {
                    object[] channelData = channelInfo.ChannelData;
                    int      num         = channelData.Length;
                    object[] array       = new object[num];
                    Array.Copy(channelData, array, num);
                    for (int i = 0; i < num; i++)
                    {
                        if (!(array[i] is CrossAppDomainData))
                        {
                            array[i] = null;
                        }
                    }
                    channelInfo.ChannelData = array;
                }
                this.ChannelInfo = channelInfo;
                if (runtimeType.HasProxyAttribute)
                {
                    this.SetHasProxyAttribute();
                }
            }
            else
            {
                this.SetWellKnown();
            }
            if (ObjRef.ShouldUseUrlObjRef())
            {
                if (this.IsWellKnown())
                {
                    this.SetObjRefLite();
                    return;
                }
                string text = ChannelServices.FindFirstHttpUrlForObject(this.URI);
                if (text != null)
                {
                    this.URI = text;
                    this.SetObjRefLite();
                }
            }
        }
コード例 #28
0
        //
        //
        internal void Init(Object o, Identity idObj, Type requestedType)
        {
            Message.DebugOut("RemotingServices::FillObjRef: IN");
            BCLDebug.Assert(idObj != null, "idObj != null");

            // Set the URI of the object to be marshaled
            uri = idObj.URI;

            // Figure out the type
            MarshalByRefObject obj = idObj.TPOrObject;

            BCLDebug.Assert(null != obj, "Identity not setup correctly");

            // Get the type of the object
            Type serverType = null;

            if (!RemotingServices.IsTransparentProxy(obj))
            {
                serverType = obj.GetType();
            }
            else
            {
                serverType = RemotingServices.GetRealProxy(obj).GetProxiedType();
            }

            Type typeOfObj = (null == requestedType ? serverType : requestedType);

            // Make sure that the server and requested types are compatible
            //  (except for objects that implement IMessageSink, since we
            //   just hand off the message instead of invoking the proxy)
            if ((null != requestedType) &&
                !requestedType.IsAssignableFrom(serverType) &&
                (!typeof(IMessageSink).IsAssignableFrom(serverType)))
            {
                throw new RemotingException(
                          String.Format(
                              CultureInfo.CurrentCulture, Environment.GetResourceString(
                                  "Remoting_InvalidRequestedType"),
                              requestedType.ToString()));;
            }

            {
                RemotingTypeCachedData cache = (RemotingTypeCachedData)
                                               InternalRemotingServices.GetReflectionCachedData(typeOfObj);

                TypeInfo = (IRemotingTypeInfo)cache.TypeInfo;
            }

            if (!idObj.IsWellKnown())
            {
                // Create the envoy info
                EnvoyInfo = System.Runtime.Remoting.EnvoyInfo.CreateEnvoyInfo(idObj as ServerIdentity);

                // Create the channel info
                IChannelInfo chan = (IChannelInfo) new ChannelInfo();
                // Make sure the channelInfo only has x-appdomain data since the objref is agile while other
                // channelData might not be and regardless this data is useless for an appdomain proxy
                if (o is AppDomain)
                {
                    Object[] channelData       = chan.ChannelData;
                    int      channelDataLength = channelData.Length;
                    Object[] newChannelData    = new Object[channelDataLength];
                    Array.Copy(channelData, newChannelData, channelDataLength);
                    for (int i = 0; i < channelDataLength; i++)
                    {
                        if (!(newChannelData[i] is CrossAppDomainData))
                        {
                            newChannelData[i] = null;
                        }
                    }
                    chan.ChannelData = newChannelData;
                }
                ChannelInfo = chan;

                if (serverType.HasProxyAttribute)
                {
                    SetHasProxyAttribute();
                }
            }
            else
            {
                SetWellKnown();
            }

            // See if we should and can use a url obj ref?
            if (ShouldUseUrlObjRef())
            {
                if (IsWellKnown())
                {
                    // full uri already supplied.
                    SetObjRefLite();
                }
                else
                {
                    String httpUri = ChannelServices.FindFirstHttpUrlForObject(URI);
                    if (httpUri != null)
                    {
                        URI = httpUri;
                        SetObjRefLite();
                    }
                }
            }
        } // Init
コード例 #29
0
 /// <summary>
 /// 创建Aop代理基类
 /// </summary>
 /// <param name="obj">被代理对象</param>
 public AopProxyBase(MarshalByRefObject obj)
     : base(obj.GetType())
 {
     this.target = obj;
 }
コード例 #30
0
ファイル: RemotingServices.cs プロジェクト: zhufengGNSS/mono
        public static ObjRef Marshal(MarshalByRefObject Obj, string ObjURI, Type RequestedType)
        {
            if (IsTransparentProxy(Obj))
            {
                RealProxy proxy    = RemotingServices.GetRealProxy(Obj);
                Identity  identity = proxy.ObjectIdentity;

                if (identity != null)
                {
                    if (proxy.GetProxiedType().IsContextful&& !identity.IsConnected)
                    {
                        // Unregistered local contextbound object. Register now.
                        ClientActivatedIdentity cboundIdentity = (ClientActivatedIdentity)identity;
                        if (ObjURI == null)
                        {
                            ObjURI = NewUri();
                        }
                        cboundIdentity.ObjectUri = ObjURI;
                        RegisterServerIdentity(cboundIdentity);
                        cboundIdentity.StartTrackingLifetime((ILease)Obj.InitializeLifetimeService());
                        return(cboundIdentity.CreateObjRef(RequestedType));
                    }
                    else if (ObjURI != null)
                    {
                        throw new RemotingException("It is not possible marshal a proxy of a remote object.");
                    }

                    ObjRef or = proxy.ObjectIdentity.CreateObjRef(RequestedType);
                    TrackingServices.NotifyMarshaledObject(Obj, or);
                    return(or);
                }
            }

            if (RequestedType == null)
            {
                RequestedType = Obj.GetType();
            }

            if (ObjURI == null)
            {
                if (Obj.ObjectIdentity == null)
                {
                    ObjURI = NewUri();
                    CreateClientActivatedServerIdentity(Obj, RequestedType, ObjURI);
                }
            }
            else
            {
                ClientActivatedIdentity identity = GetIdentityForUri("/" + ObjURI) as ClientActivatedIdentity;
                if (identity == null || Obj != identity.GetServerObject())
                {
                    CreateClientActivatedServerIdentity(Obj, RequestedType, ObjURI);
                }
            }

            ObjRef oref;

            if (IsTransparentProxy(Obj))
            {
                oref = RemotingServices.GetRealProxy(Obj).ObjectIdentity.CreateObjRef(RequestedType);
            }
            else
            {
                oref = Obj.CreateObjRef(RequestedType);
            }

            TrackingServices.NotifyMarshaledObject(Obj, oref);
            return(oref);
        }
コード例 #31
0
 public PrevalentSystemProxy(PrevalenceEngine engine, MarshalByRefObject system) : base(system.GetType())
 {
     _engine = engine;
     _system = system;
 }
コード例 #32
0
ファイル: Aspect.cs プロジェクト: franknew/SOAFramework
        /// <summary>
        /// 获得类和方法里面的属性
        /// </summary>
        /// <param name="msg"></param>
        private void GetAttributeSettings(IMessage msg)
        {
            //获得类属性
            object[] objClassAttribute = this.mMro_ParentMethod.GetType().GetCustomAttributes(typeof(AOPClassAttribute), true);
            if (objClassAttribute == null || objClassAttribute.Length == 0)
            {
                return;
            }
            PropertyInfo piAttrArea = objClassAttribute[0].GetType().GetProperty("AttributeArea");

            mEnmu_AttrArea = (AOPAttributeArea)piAttrArea.GetValue(objClassAttribute[0], null);
            //转换成callmessage获得运行的方法名
            IMethodCallMessage imcmMessage = msg as IMethodCallMessage;

            //获得该方法上的AOP属性
            object[] objMethodAttribute = mMro_ParentMethod.GetType().GetMethod(imcmMessage.MethodName).GetCustomAttributes(typeof(AOPMethodAttribute), true);
            if (objMethodAttribute == null || objMethodAttribute.Length == 0)
            {
                mBl_HasMethodAttr = false;
                return;
            }
            mBl_HasMethodAttr = true;
            PropertyInfo[] arrProperties = objMethodAttribute[0].GetType().GetProperties();
            foreach (PropertyInfo piTemp in arrProperties)
            {
                object objValue = piTemp.GetValue(objMethodAttribute[0], null);
                string strValue = objValue == null ? "" : objValue.ToString();
                switch (piTemp.Name.ToLower())
                {
                case "custombeforemethodname":
                    mStr_BeforeMethodName = strValue;
                    break;

                case "customaftermethodname":
                    mStr_AfterMethodName = strValue;
                    break;

                case "customonexceptionmethodname":
                    mStr_OnExceptionName = strValue;
                    break;

                case "customaspectmethonamespace":
                    mStr_CustomAspectMethodNameSpace = strValue;
                    if (!string.IsNullOrEmpty(mStr_CustomAspectMethodNameSpace))
                    {
                        mStr_ClassName = mStr_CustomAspectMethodNameSpace.Substring(0, mStr_CustomAspectMethodNameSpace.IndexOf("."));
                    }
                    else
                    {
                        mStr_ClassName = mMro_ParentMethod.GetType().Namespace;
                    }
                    break;

                case "customdllfullfilename":
                    mStr_CustomDllFullFileName = strValue;
                    break;

                case "passargs":
                    mBl_HasMethodAttr = objValue == null ? false : Convert.ToBoolean(objValue);
                    break;
                }
            }
            if (string.IsNullOrEmpty(mStr_BeforeMethodName))
            {
            }
        }
コード例 #33
0
        private static void VerifyIsOkToCallMethod(object server, IMethodMessage msg)
        {
            bool flag = false;
            MarshalByRefObject marshalByRefObject = server as MarshalByRefObject;

            if (marshalByRefObject != null)
            {
                bool     flag2;
                Identity identity = MarshalByRefObject.GetIdentity(marshalByRefObject, out flag2);
                if (identity != null)
                {
                    ServerIdentity serverIdentity = identity as ServerIdentity;
                    if (serverIdentity != null && serverIdentity.MarshaledAsSpecificType)
                    {
                        Type serverType = serverIdentity.ServerType;
                        if (serverType != null)
                        {
                            MethodBase  methodBase  = StackBuilderSink.GetMethodBase(msg);
                            RuntimeType runtimeType = (RuntimeType)methodBase.DeclaringType;
                            if (runtimeType != serverType && !runtimeType.IsAssignableFrom(serverType))
                            {
                                throw new RemotingException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"), methodBase.DeclaringType.FullName, serverType.FullName));
                            }
                            if (runtimeType.IsInterface)
                            {
                                StackBuilderSink.VerifyNotIRemoteDispatch(runtimeType);
                            }
                            flag = true;
                        }
                    }
                }
                if (!flag)
                {
                    MethodBase  methodBase2  = StackBuilderSink.GetMethodBase(msg);
                    RuntimeType runtimeType2 = (RuntimeType)methodBase2.ReflectedType;
                    if (!runtimeType2.IsInterface)
                    {
                        if (!runtimeType2.IsInstanceOfType(marshalByRefObject))
                        {
                            throw new RemotingException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_InvalidCallingType"), runtimeType2.FullName, marshalByRefObject.GetType().FullName));
                        }
                    }
                    else
                    {
                        StackBuilderSink.VerifyNotIRemoteDispatch(runtimeType2);
                    }
                }
            }
        }