Exemple #1
0
        private void Preprocess(IMessage msg)
        {
            //只处理方法调用
            if (!(msg is IMethodMessage))
            {
                return;
            }

            //获取方法中定义的 Task 属性,交给权限检查类去检查
            IMethodMessage call = msg as IMethodMessage;
            MethodBase     mb   = call.MethodBase;

            object[] attrObj = mb.GetCustomAttributes(typeof(OperationAttribute), false);
            Debug.WriteLine("current method Name : " + mb.Name);
            if (attrObj != null && attrObj.Length > 0)
            {
                OperationAttribute attr = (OperationAttribute)attrObj[0];

                if (!string.IsNullOrEmpty(attr.Name))
                {
                    if (!SecuritySession.IsAllowed(attr.Name))
                    {
                        throw new UnauthorizedException(attr.Description);
                    }
                }
                Debug.WriteLine("Operation Name: " + attr.Name);
            }
        }
Exemple #2
0
        public override IMessage Invoke(IMessage msg)
        {
            try
            {
                IMethodMessage     mm         = msg as IMethodMessage;
                IMethodCallMessage methodCall = (IMethodCallMessage)msg;
                if (mm.MethodName == "GetType")
                {
                    return(new ReturnMessage(
                               typeof(INotifyCollection <T>),
                               null, 0, mm.LogicalCallContext,
                               (IMethodCallMessage)msg));
                }

                MethodInfo method = (MethodInfo)mm.MethodBase;
                object[]   args   = mm.Args;

                object ret = CurrentDispatcher.Invoke(() =>
                {
                    return(method.Invoke(Collection, methodCall.InArgs));
                });

                return(new ReturnMessage(
                           ret, null, 0, mm.LogicalCallContext, (IMethodCallMessage)msg));
            }
            catch (Exception e)
            {
                throw;
            }
        }
        private static object[] ProcessEvent(HandleExternalEventActivity activity, ActivityExecutionContext context, object msg, Type interfaceType, string operation)
        {
            IMethodMessage message = msg as IMethodMessage;

            if (message == null)
            {
                Exception excp = msg as Exception;
                if (excp != null)
                {
                    throw excp;
                }
                throw new InvalidOperationException(SR.GetString(SR.Error_InvalidLocalServiceMessage));
            }

            CorrelationService.InvalidateCorrelationToken(activity, interfaceType, operation, message.Args);

            IdentityContextData identityData =
                (IdentityContextData)message.LogicalCallContext.GetData(IdentityContextData.IdentityContext);

            ValidateRoles(activity, identityData.Identity);

            if (ProcessEventParameters(activity.ParameterBindings, message, interfaceType, operation))
            {
                return(message.Args);
            }

            return(null);
        }
 private static bool IsGetHashCodeMethod(IMethodMessage mcm)
 {
     if (mcm.MethodName != "GetHashCode") return false;
     Type[] argTypes = mcm.MethodSignature as Type[];
     if (argTypes == null) return false;
     return (argTypes.Length == 0);
 }
Exemple #5
0
        public IMessage SyncProcessMessage(IMessage msg)
        {
            IMethodCallMessage methodCallMessage = msg as IMethodCallMessage;
            IMethodMessage     methodMessage     = msg as IMethodMessage;

            int numberOfRetries = 5;

            while (true)
            {
                try
                {
                    return(SerializeAndProcessMessage(msg, methodCallMessage));
                }
                catch (WebException ex)
                {
                    if (--numberOfRetries == 0 || !CanRetryMethod(methodMessage))
                    {
                        return(new ReturnMessage(ex, methodCallMessage));
                    }
                }
                catch (Exception ex)
                {
                    return(new ReturnMessage(ex, methodCallMessage));
                }
            }
        }
            public override IMessage Invoke(IMessage message)
            {
                IMethodMessage myMethodMessage = (IMethodMessage)message;

                if (myMethodMessage.MethodSignature is Array)
                {
                    foreach (Type t in (Array)myMethodMessage.MethodSignature)
                    {
                        if (t.IsByRef)
                        {
                            throw new NotSupportedException("ByRef parameters are not supported");
                        }
                    }
                }

                MethodInfo mi = myMethodMessage.MethodBase as MethodInfo;

                if (mi != null)
                {
                    BinaryFormatter.PopulateFromType(mi.ReturnType);
                }

                MessageCall call = MessageCall.CreateFromIMethodMessage(myMethodMessage);

                object returnValue = m_from.SendMessage(m_to, 60 * 1000, call);

                // Build the return message to pass back to the transparent proxy.
                return(new ReturnMessage(returnValue, null, 0, null, (IMethodCallMessage)message));
            }
Exemple #7
0
 private void DoPInvoke(IMethodMessage msg)
 {
     if (null != _pinvoker)
     {
         _pinvoker.CallMethod(msg.MethodName, msg.Args);
     }
 }
Exemple #8
0
        private void Preprocess(IMessage msg)
        {
            // We only want to process method calls
            if (!(msg is IMethodMessage))
            {
                return;
            }

            IMethodMessage call = msg as IMethodMessage;
            Type           type = Type.GetType(call.TypeName);

            m_typeAndName = type.Name + "." + call.MethodName;
            Console.Write("PreProcessing: " + m_typeAndName + "(");

            // Loop through the [in] parameters
            for (int i = 0; i < call.ArgCount; ++i)
            {
                if (i > 0)
                {
                    Console.Write(", ");
                }
                Console.Write(call.GetArgName(i) + " = " + call.GetArg(i));
            }
            Console.WriteLine(")");
        }
        public static string GetMethodName(IMethodMessage methodMessage)
        {
            string methodName = methodMessage.MethodName;
            switch (methodName)
            {
                case ".ctor":
                    {
                        return "Constructor";
                    }
                case "FieldGetter":
                case "FieldSetter":
                    {
                        IMethodCallMessage methodCallMessage = (IMethodCallMessage)methodMessage;
                        return (string)methodCallMessage.InArgs[1];
                    }
            }
            if (methodName.EndsWith("Item"))
            {
                return methodName;
            }

            if (methodName.StartsWith("get_") || methodName.StartsWith("set_"))
            {
                return methodName.Substring(4);
            }
            if (methodName.StartsWith("add_"))
            {
                return methodName.Substring(4) + "+=";
            }
            if (methodName.StartsWith("remove_"))
            {
                return methodName.Substring(7) + "-=";
            }
            return methodName;
        }
Exemple #10
0
        internal static object[] CoerceArgs(IMethodMessage m)
        {
            MethodBase methodBase = m.MethodBase;
            RemotingMethodCachedData reflectionCachedData = InternalRemotingServices.GetReflectionCachedData(methodBase);

            return(Message.CoerceArgs(m, reflectionCachedData.Parameters));
        }
Exemple #11
0
        private static void FinishExecution(bool logEnabled,
                                            IMethodMessage methodCall,
                                            MethodInfo methodInfo,
                                            string resultTypeName,
                                            object result,
                                            ILog logger,
                                            Stopwatch watch,
                                            string taskId = null)
        {
            watch.Stop();

            if (logEnabled)
            {
                logger.Info($"{taskId}Finished executing '{methodCall.MethodName}'. Time: {watch.ElapsedMilliseconds} ms.");
            }

            if (logEnabled && !string.Equals(methodInfo.ReturnType.FullName, "System.Void"))
            {
                var responseMessage = result as HttpResponseMessage;
                if (responseMessage != null)
                {
                    logger.Debug($"{taskId}{methodCall.MethodName} result: {resultTypeName}={WriteHttpResponseMessage(responseMessage)}");
                }
                else
                {
                    logger.Debug($"{taskId}{methodCall.MethodName} result: {resultTypeName}={result};");
                }
            }
        }
        private void TryRaisePropertyChanged(IMethodMessage methodMessage)
        {
            if (methodMessage.MethodName.StartsWith("set_"))
            {
                var propertyName = methodMessage.MethodName.Substring(4);
                var type = Type.GetType(methodMessage.TypeName);
                var pi = type.GetProperty(propertyName);

                // check that we have the attribute defined
                if (Attribute.GetCustomAttribute(pi, typeof(NotifyAttribute)) != null)
                {
                    // get the field storing the delegate list that are stored by the event.
                    FieldInfo info = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
                        .Where(f => f.FieldType == typeof(PropertyChangedEventHandler))
                        .FirstOrDefault();

                    if (info != null)
                    {
                        // get the value of the field
                        var handler = info.GetValue(_target) as PropertyChangedEventHandler;

                        // invoke the delegate if it's not null (aka empty)
                        if (handler != null)
                            handler.Invoke(_target, new PropertyChangedEventArgs(propertyName));
                    }
                }
            }
        }
Exemple #13
0
        // This check if the call-site on the TP is in our own AD
        // It also handles the special case where the TP is on
        // a well-known object and we cannot do stack-blting
        internal bool IsOKToStackBlt(IMethodMessage mcMsg, Object server)
        {
            bool    bOK = false;
            Message msg = mcMsg as Message;

            if (null != msg)
            {
                IInternalMessage iiMsg = (IInternalMessage)msg;

                // If there is a frame in the message we can always
                // Blt it (provided it is not a proxy to a well-known
                // object in our own appDomain)!
                // The GetThisPtr == server test allows for people to wrap
                // our proxy with their own interception .. in that case
                // we should not blt the stack.
                if (msg.GetFramePtr() != IntPtr.Zero &&
                    msg.GetThisPtr() == server
                    &&
                    (iiMsg.IdentityObject == null ||
                     (iiMsg.IdentityObject != null &&
                      iiMsg.IdentityObject == iiMsg.ServerIdentityObject
                     )
                    )
                    )
                {
                    bOK = true;
                }
            }

            return(bOK);
        }
    // Overriding the Invoke method of RealProxy.
    public override IMessage Invoke(IMessage message)
    {
        IMethodMessage myMethodMessage = (IMethodMessage)message;

        Console.WriteLine("**** Begin Invoke ****");
        Console.WriteLine("\tType is : " + myType);
        Console.WriteLine("\tMethod name : " + myMethodMessage.MethodName);

        for (int i = 0; i < myMethodMessage.ArgCount; i++)
        {
            Console.WriteLine("\tArgName is : " + myMethodMessage.GetArgName(i));
            Console.WriteLine("\tArgValue is: " + myMethodMessage.GetArg(i));
        }

        if (myMethodMessage.HasVarArgs)
        {
            Console.WriteLine("\t The method have variable arguments!!");
        }
        else
        {
            Console.WriteLine("\t The method does not have variable arguments!!");
        }

        // Dispatch the method call to the real object.
        Object returnValue = myType.InvokeMember(myMethodMessage.MethodName, BindingFlags.InvokeMethod, null,
                                                 myObjectInstance, myMethodMessage.Args);

        Console.WriteLine("**** End Invoke ****");

        // Build the return message to pass back to the transparent proxy.
        ReturnMessage myReturnMessage = new ReturnMessage(returnValue, null, 0, null,
                                                          (IMethodCallMessage)message);

        return(myReturnMessage);
    }
        private static bool ProcessEventParameters(WorkflowParameterBindingCollection parameters, IMethodMessage message, Type interfaceType, string operation)
        {
            bool isKnownSignature = false;
            if (parameters == null)
                return isKnownSignature;

            EventInfo eventInfo = interfaceType.GetEvent(operation);
            MethodInfo methodInfo = eventInfo.EventHandlerType.GetMethod("Invoke");
            int index = 0;

            foreach (ParameterInfo formalParameter in methodInfo.GetParameters())
            {
                if ((typeof(ExternalDataEventArgs).IsAssignableFrom(formalParameter.ParameterType)))
                {
                    if (index == 1)
                        isKnownSignature = true;
                }

                if (parameters.Contains(formalParameter.Name))
                {
                    WorkflowParameterBinding binding = parameters[formalParameter.Name];
                    binding.Value = message.Args[index];
                }
                index++;
            }
            return isKnownSignature;
        }
        public static string GetAssemblyName(IMethodMessage methodMessage)
        {
            string fullTypeName = methodMessage.TypeName;

            string[] arr = fullTypeName.Split(new Char[] { ',', ',' });
            return(arr[1]);
        }
Exemple #17
0
        private void Preprocess(IMessage msg)
        {
            // 仅仅处理方法调用
            if (!(msg is IMethodMessage))
            {
                return;
            }

            IMethodMessage call = msg as IMethodMessage;

            Type type = Type.GetType(call.TypeName);

            mTypeAndName = type.Name + "." + call.MethodName;
            if (!FilterMethodName(msg))
            {
                return;
            }
            string logText = "PreProcessing: " + mTypeAndName + "( ";

            // 遍历参数
            for (int i = 0; i < call.ArgCount; ++i)
            {
                if (i > 0)
                {
                    logText += ", ";
                }
                logText += call.GetArgName(i) + " = " + call.GetArg(i);
            }
            logText += " )";
            Logger.Log.Info(logText);
        }
Exemple #18
0
 protected static int StoreUserPropertiesForMethodMessage(IMethodMessage msg, ref ArrayList argsToSerialize)
 {
     IDictionary properties = msg.Properties;
       MessageDictionary messageDictionary = properties as MessageDictionary;
       if (messageDictionary != null)
       {
     if (!messageDictionary.HasUserData())
       return 0;
     int num = 0;
     foreach (DictionaryEntry @internal in messageDictionary.InternalDictionary)
     {
       if (argsToSerialize == null)
     argsToSerialize = new ArrayList();
       argsToSerialize.Add((object) @internal);
       ++num;
     }
     return num;
       }
       int num1 = 0;
       foreach (DictionaryEntry dictionaryEntry in properties)
       {
     if (argsToSerialize == null)
       argsToSerialize = new ArrayList();
     argsToSerialize.Add((object) dictionaryEntry);
     ++num1;
       }
       return num1;
 }
Exemple #19
0
        private void Preprocess(IMessage msg)
        {
            // We only want to process method calls
            if (!(msg is IMethodMessage))
            {
                return;
            }

            IMethodMessage call = msg as IMethodMessage;

            MethodBase mb = call.MethodBase;

            object[] attrObj = mb.GetCustomAttributes(typeof(Task), false);

            if (attrObj != null)
            {
                Task attr = (Task)attrObj[0];

                if (!string.IsNullOrEmpty(attr.Name))
                { //check permission here
                    //HttpContext.Current.Response.Write(attr.Name);
                    AuthorityManager.PermissionCheck(attr.Name);
                }
            }
        }
Exemple #20
0
        /// <summary>
        /// Call the current method being intercepted
        /// </summary>
        private object InvokeOriginalMethod(IMethodMessage methodMessage, bool abort, bool tryWrap = false)
        {
            try
            {
                if (abort)
                {
                    return(null);
                }

                if (methodMessage.MethodBase.IsConstructor && tryWrap)
                {
                }

                var result = methodMessage.MethodBase.Name == "GetType"
                    ? typeof(TInterface)
                    : methodMessage.MethodBase.Invoke(_target, methodMessage.Args);

                return(result);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                throw;
            }
        }
Exemple #21
0
        private bool FilterMethodName(IMessage msg)
        {
            IMethodMessage call = msg as IMethodMessage;

            // 过滤构造函数
            if (call.MethodName.Contains("ctor"))
            {
                return(false);
            }

            // 检测方法是否包含特性
            Type       type       = Type.GetType(call.TypeName);
            MethodInfo methodInfo = type.GetMethod(call.MethodName);

            if (methodInfo == null)
            {
                return(false);
            }
            object[] attrs = methodInfo.GetCustomAttributes(typeof(LoggerAttribute), false);
            foreach (object attr in attrs)
            {
                if (attr is LoggerAttribute)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #22
0
        } // CreateBinaryFormatter

        internal static void SerializeSoapMessage(IMessage msg, Stream outputStream, bool includeVersions)
        {
            // create soap formatter
            SoapFormatter fmt = CreateSoapFormatter(true, includeVersions);

            //check for special options if this is the SoapFormatter
            IMethodMessage methodMsg = msg as IMethodMessage;

            if (methodMsg != null)
            {
                MethodBase mb = methodMsg.MethodBase;
                if (mb != null)
                {
                    Type type = methodMsg.MethodBase.DeclaringType;
                    SoapTypeAttribute cache =
                        (SoapTypeAttribute)InternalRemotingServices.GetCachedSoapAttribute(type);
                    if ((cache.SoapOptions & SoapOption.AlwaysIncludeTypes) == SoapOption.AlwaysIncludeTypes)
                    {
                        fmt.TypeFormat |= FormatterTypeStyle.TypesAlways;
                    }
                    if ((cache.SoapOptions & SoapOption.XsdString) == SoapOption.XsdString)
                    {
                        fmt.TypeFormat |= FormatterTypeStyle.XsdString;
                    }
                }
            }
            // end of set special options for SoapFormatter

            Header[] h = GetSoapHeaders(msg);

            // this is to make messages within a  message serialize correctly
            // and not use the fake type
            ((RemotingSurrogateSelector)fmt.SurrogateSelector).SetRootObject(msg);
            fmt.Serialize(outputStream, msg, h);
        } // SerializeSoapMessage
 MethodBase GetRealMethod(IMethodMessage mm)
 {
     if (Platform.IsWindows)
     {
         // HACK: When running on .NET, mm.MethodBase returns the method for the type of the proxy
         // instead of the target type. There is no legal way of getting the target type, so we have
         // to use reflection here.
         FieldInfo fi = mm.GetType().GetField("_ID", BindingFlags.NonPublic | BindingFlags.Instance);
         if (fi != null)
         {
             object       id = fi.GetValue(mm);
             PropertyInfo pi = id.GetType().GetProperty("ServerType", BindingFlags.NonPublic | BindingFlags.Instance);
             if (pi != null)
             {
                 Type       t   = (Type)pi.GetValue(id, null);
                 MethodBase met = t.GetMethod(mm.MethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, (Type[])mm.MethodSignature, null);
                 if (met != null)
                 {
                     return(met);
                 }
             }
         }
     }
     return(mm.MethodBase);
 }
Exemple #24
0
        /// <summary>
        /// 获取相关的Aspects
        /// </summary>
        /// <param name="msg">IMessage,包含有关方法调用的信息。</param>
        /// <param name="position">拦截的位置</param>
        /// <returns>Aspect数组</returns>
        public IInjection[] GetAspect(IMessage msg, AspectActionPosition position)
        {
            IMethodMessage    mmsg           = msg as IMethodMessage;
            List <IInjection> al             = new List <IInjection>();
            string            fullMethodInfo = mmsg.MethodBase.ReflectedType.FullName + "--" + mmsg.MethodName;

            for (int i = 0; i < _Aspects.Count; i++)
            {
                string key = GetMatchHashKey(mmsg, _Aspects[i], position);
                if (!_AspectsMatch.ContainsKey(key))
                {
                    lock (_AspectsMatch) {
                        if (!_AspectsMatch.ContainsKey(key))
                        {
                            AddAspectMatch(mmsg, _Aspects[i], position);
                        }
                    }
                }
                if (_AspectsMatch[key])
                {
                    IInjection asp;
                    if (_Aspects[i].DeployModell.Equals("Singleton"))
                    {
                        asp = _Aspects[i].SingletonAspect;
                    }
                    else
                    {
                        asp = Activator.CreateInstance(_Aspects[i].AssemblyName, _Aspects[i].ClassName).Unwrap() as IInjection;
                    }
                    al.Add(asp);
                }
            }
            return((IInjection[])al.ToArray());
        }
Exemple #25
0
        public static bool IsMethodOverloaded(IMethodMessage msg)
        {
            const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
            RuntimeType        type   = (RuntimeType)msg.MethodBase.DeclaringType;

            return(type.GetMethodsByName(msg.MethodName, bfinst, false, type).Length > 1);
        }
Exemple #26
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodMessage methodMessage = msg as IMethodMessage;
            MethodInfo     methodInfo    = (MethodInfo)methodMessage.MethodBase;

            if (EventsByAddMethods.ContainsKey(methodInfo))
            {
                EventInfo eventInfo = EventsByAddMethods[methodInfo];
                if (!_eventHandlers.ContainsKey(eventInfo))
                {
                    _eventHandlers[eventInfo] = new List <Delegate>();
                }
                _eventHandlers[eventInfo].Add((Delegate)methodMessage.Args[0]);
            }
            else if (EventsByRemoveMethods.ContainsKey(methodInfo))
            {
                EventInfo eventInfo = EventsByRemoveMethods[methodInfo];
                if (_eventHandlers.ContainsKey(eventInfo))
                {
                    _eventHandlers[eventInfo].Remove((Delegate)methodMessage.Args[0]);
                }
            }

            return(RemotingServices.ExecuteMessage(_targetObject, (IMethodCallMessage)msg));
        }
        public CADMethodRef(IMethodMessage msg)
        {
            MethodBase method = msg.MethodBase;

            typeName   = method.DeclaringType.AssemblyQualifiedName;
            ctor       = method.IsConstructor;
            methodName = method.Name;

            if (!ctor && method.IsGenericMethod)
            {
                var ga = method.GetGenericArguments();
                generic_arg_names = new string [ga.Length];
                for (int i = 0; i < ga.Length; ++i)
                {
                    generic_arg_names [i] = ga [i].AssemblyQualifiedName;
                }

                method = ((MethodInfo)method).GetGenericMethodDefinition();
            }

            var param_types = method.GetParameters();

            param_names = new string [param_types.Length];
            for (int i = 0; i < param_types.Length; ++i)
            {
                param_names [i] = param_types [i].ParameterType.AssemblyQualifiedName;
            }
        }
Exemple #28
0
        /// In the Invoke Method we do our interception work.
        public override IMessage Invoke(IMessage msg)
        {
            IMethodMessage returnMsg = null;

            if (msg is IConstructionCallMessage)
            {
                _realObject = GetInstance(msg as IConstructionCallMessage, ref returnMsg);
                _objType    = ((IConstructionCallMessage)msg).ActivationType;
                //SetStubData(this, _realObject);
            }
            else
            {
                if (!_isInit)
                {
                    DoObjectInitialize(_target);
                    _isInit = true;
                }

                ///the MethodCallMessageWrapper provides read/write access to the method call arguments.
                MethodCallMessageWrapper methodCallMsg = new MethodCallMessageWrapper((IMethodCallMessage)msg);
                ///This is the reflected method base of the called method.
                MethodInfo methodInfo = (MethodInfo)methodCallMsg.MethodBase;

                ///This is the object we are proxying.
                MarshalByRefObject owner = _target;
                //MarshalByRefObject owner = _realObject as MarshalByRefObject;
                ///Some basic initializations for later use
                if (owner != null)
                {
                    ChoMemberInfo memberInfo = new ChoMemberInfo(owner, _objType, methodCallMsg);
                    if (!ChoType.IsValidObjectMember(memberInfo.Info))
                    {
                        //|| ChoType.GetAttribute<ChoPropertyInfoAttribute>(memberInfo.Info, false) == null)
                        return(RemotingServices.ExecuteMessage(owner, methodCallMsg));
                    }

                    return(ExecuteMethod(ref returnMsg, methodCallMsg, owner, memberInfo));

                    //if (methodCallMsg.LogicalCallContext.GetData("CallerId") != null)
                    //    return ExecuteMethod(ref returnMsg, methodCallMsg, owner, memberInfo);
                    //else
                    //{
                    //    methodCallMsg.LogicalCallContext.SetData("CallerId", ChoRandom.NextRandom());
                    //    IChoAsyncResult result = ChoQueuedExecutionService.Global.Enqueue(() =>
                    //        {
                    //            return ExecuteMethod(ref returnMsg, methodCallMsg, owner, memberInfo);
                    //        });

                    //    return (IMessage)result.EndInvoke();
                    //}
                }
                else
                {
                    return(new ReturnMessage(new NullReferenceException("Missing target object."), methodCallMsg));
                }
            }

            return(returnMsg);
        }
Exemple #29
0
 private static bool IsEqualsMethod(IMethodMessage mcm)
 {
     if (mcm.MethodName != "Equals") return false;
     Type[] argTypes = mcm.MethodSignature as Type[];
     if (argTypes == null) return false;
     if (argTypes.Length == 1 && argTypes[0] == typeof(object)) return true;
     return false;
 }
Exemple #30
0
        /// <summary>
        /// ポリシーイベントハンドラを実行する。
        /// </summary>
        /// <param name="applyTargetClass">ハンドラ絞り込みオプション(ポリシーの適用対象クラス)</param>
        /// <param name="msg">メソッド呼び出し時のメッセージ</param>
        /// <param name="timings">ハンドラ絞り込みオプション(実行タイミング)</param>
        public void ExecuteHandler(Type applyTargetClass, IMethodMessage msg, params ExecuteTiming[] timings)
        {
            var events = ApplyPolicies.SelectMany(policy => policy.EventsBy(timings));

            foreach (var evt in events)
            {
                evt.Handler(applyTargetClass, null);
            }
        }
Exemple #31
0
        protected override void OnPostAopMethodFilter(IMessage msg)
        {
            IMethodMessage call    = msg as IMethodMessage;
            Type           type    = Type.GetType(call.TypeName);
            string         callStr = type.Name + "." + call.MethodName;
            var            args    = call.Args;

            Console.WriteLine("在exception异常后拦截到" + callStr);
        }
 internal IMessage ActivateRemoteObject(IMethodMessage request)
 {
     if (this._ctorCall == null)
     {
         return(new ConstructionResponse(this, null, (IMethodCallMessage)request));
     }
     this._ctorCall.CopyFrom(request);
     return(ActivationServices.Activate(this, this._ctorCall));
 }
Exemple #33
0
        protected override void OnPreAopMethodFilter(IMessage msg, ref bool Cancel)
        {
            IMethodMessage call    = msg as IMethodMessage;
            Type           type    = Type.GetType(call.TypeName);
            string         callStr = type.Name + "." + call.MethodName;
            var            args    = call.Args;

            Console.WriteLine("在执行前拦截到" + callStr);
        }
Exemple #34
0
        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
Exemple #35
0
 internal IMessage ActivateRemoteObject(IMethodMessage request)
 {
     if (_ctorCall == null)                                                         // It must be a WKO
     {
         return(new ConstructionResponse(this, null, (IMethodCallMessage)request)); // Ignore constructor call for WKOs
     }
     _ctorCall.CopyFrom(request);
     return(ActivationServices.Activate(this, _ctorCall));
 }
Exemple #36
0
 /// <summary>
 /// 开始事务
 /// </summary>
 /// <param name="attributes"></param>
 /// <param name="message"></param>
 private static void OnBegin(IEnumerable<object> attributes, IMethodMessage message)
 {
     foreach (var attr in attributes)
     {
         if (attr.GetType() == typeof(TransactionAttribute))
         {
             var tran = attr as TransactionAttribute;
             if (tran != null) tran.OnBegin();
         }
     }
 }
 internal ArgMapper(IMethodMessage mm, bool fOut)
 {
     this._mm = mm;
     MethodBase methodBase = this._mm.MethodBase;
     this._methodCachedData = InternalRemotingServices.GetReflectionCachedData(methodBase);
     if (fOut)
     {
         this._map = this._methodCachedData.MarshalResponseArgMap;
     }
     else
     {
         this._map = this._methodCachedData.MarshalRequestArgMap;
     }
 }
Exemple #38
0
        RequestMessage CreateRequest(IMethodMessage methodCall)
        {
            var activityId = Guid.NewGuid();

            var method = ((MethodInfo) methodCall.MethodBase);
            var request = new RequestMessage
            {
                Id = contractType.Name + "::" + method.Name + "[" + Interlocked.Increment(ref callId) + "] / " + activityId,
                ActivityId = activityId,
                Destination = endPoint,
                MethodName = method.Name,
                ServiceName = contractType.Name,
                Params = methodCall.Args
            };
            return request;
        }
 private static bool ProcessEventParameters(WorkflowParameterBindingCollection parameters, IMethodMessage message, Type interfaceType, string operation)
 {
     bool flag = false;
     if (parameters != null)
     {
         MethodInfo method = interfaceType.GetEvent(operation).EventHandlerType.GetMethod("Invoke");
         int index = 0;
         foreach (ParameterInfo info3 in method.GetParameters())
         {
             if (typeof(ExternalDataEventArgs).IsAssignableFrom(info3.ParameterType) && (index == 1))
             {
                 flag = true;
             }
             if (parameters.Contains(info3.Name))
             {
                 WorkflowParameterBinding binding = parameters[info3.Name];
                 binding.Value = message.Args[index];
             }
             index++;
         }
     }
     return flag;
 }
 [System.Security.SecurityCritical]  // auto-generated_required
 public static String GetSessionIdForMethodMessage(IMethodMessage msg)
 {
     return msg.Uri; 
 } // GetSessionIdForMessage
        [System.Security.SecurityCritical]  // auto-generated 
        private static MethodBase GetMethodBase(IMethodMessage msg, Type t, Type[] signature) 
        {
            MethodBase mb = null; 

            // Get the reflection object depending on whether it is a
            // constructor call or a method call.
            if((msg is IConstructionCallMessage) || 
               (msg is IConstructionReturnMessage))
            { 
                if((null == signature)) 
                {
                    BCLDebug.Trace("REMOTE", "RemotingServices.MethodBaseFromMethodCallMessage with null sig ", msg.MethodName); 
                    ConstructorInfo[] ci;
                    RuntimeType rt = t as RuntimeType;
                    if (rt == null)
                        ci = t.GetConstructors(); 
                    else
                        ci = rt.GetConstructors(); 
 
                    if(1 != ci.Length)
                    { 
                        // There is more than one constructor defined but
                        // we do not have a signature to differentiate between
                        // them.
                                throw new AmbiguousMatchException( 
                                    Environment.GetResourceString(
                                        "Remoting_AmbiguousCTOR")); 
                    } 
                    mb = ci[0];
                } 
                else
                {
                    BCLDebug.Trace("REMOTE", "RemotingServices.MethodBaseFromMethodCallMessage with non-null sig ", msg.MethodName, " ", signature.Length);
                    RuntimeType rt = t as RuntimeType; 
                    if (rt == null)
                        mb = t.GetConstructor(signature); 
                    else 
                        mb = rt.GetConstructor(signature);
                } 
            }
            else if((msg is IMethodCallMessage) || (msg is IMethodReturnMessage))
            {
                // We demand reflection permission in the api that calls this 
                // for non-public types
                if(null == signature) 
                { 
                    BCLDebug.Trace("REMOTE", "RemotingServices.MethodBaseFromMethodCallMessage with null sig ", msg.MethodName);
                    RuntimeType rt = t as RuntimeType; 
                    if (rt == null)
                        mb = t.GetMethod(msg.MethodName, RemotingServices.LookupAll);
                    else
                        mb = rt.GetMethod(msg.MethodName, RemotingServices.LookupAll); 
                }
                else 
                { 
                    BCLDebug.Trace("REMOTE", "RemotingServices.MethodBaseFromMethodCallMessage with non-null sig ", msg.MethodName, " ", signature.Length);
                    RuntimeType rt = t as RuntimeType; 
                    if (rt == null)
                        mb = t.GetMethod(msg.MethodName, RemotingServices.LookupAll, null, signature, null);
                    else
                        mb = rt.GetMethod(msg.MethodName, RemotingServices.LookupAll, null, CallingConventions.Any, signature, null); 
                }
 
            } 

            return mb; 
        }
        [System.Security.SecurityCritical]  // auto-generated_required
        public static bool IsMethodOverloaded(IMethodMessage msg) 
        { 
            RemotingMethodCachedData cache =
                InternalRemotingServices.GetReflectionCachedData(msg.MethodBase); 

            return cache.IsOverloaded();
        } // IsMethodOverloaded
Exemple #43
0
		public static bool IsMethodOverloaded(IMethodMessage msg)
		{
			const BindingFlags bfinst = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
			MonoType type = (MonoType) msg.MethodBase.DeclaringType;
			return type.GetMethodsByName (msg.MethodName, bfinst, false, type).Length > 1;
		}
Exemple #44
0
		public CADMessageBase (IMethodMessage msg) {
			CADMethodRef methodRef = new CADMethodRef (msg);
			serializedMethod = CADSerializer.SerializeObject (methodRef).GetBuffer ();
		}
Exemple #45
0
		protected void SaveLogicalCallContext (IMethodMessage msg, ref ArrayList serializeList)
		{
			if (msg.LogicalCallContext != null && msg.LogicalCallContext.HasInfo) 
			{
				if (serializeList == null)
					serializeList = new ArrayList();

				_callContext = new CADArgHolder (serializeList.Count);
				serializeList.Add (msg.LogicalCallContext);
			}
		}
        [System.Security.SecurityCritical]  // auto-generated
        private static MethodBase GetMethodBase(IMethodMessage msg) 
        {
            MethodBase mb = msg.MethodBase; 
            if(null == mb) 
            {
                BCLDebug.Trace("REMOTE", "Method missing w/name ", msg.MethodName); 
                    throw new RemotingException(
                        String.Format(
                            CultureInfo.CurrentCulture, Environment.GetResourceString(
                                "Remoting_Message_MethodMissing"), 
                            msg.MethodName,
                            msg.TypeName)); 
            } 

            return mb; 
        }
        [System.Security.SecurityCritical]  // auto-generated
        private static Object[] StoreUserPropertiesForMethodMessage(IMethodMessage msg)
        {
            ArrayList argsToSerialize = null;
            IDictionary properties = msg.Properties;

            if (properties == null)
                return null;

            MessageDictionary dict = properties as MessageDictionary;
            if (dict != null)
            {
                if (dict.HasUserData())
                {
                    int co = 0;
                    foreach (DictionaryEntry entry in dict.InternalDictionary)
                    {
                        if (argsToSerialize == null)
                            argsToSerialize = new ArrayList();
                        argsToSerialize.Add(entry);
                        co++;
                    }

                    return argsToSerialize.ToArray();
                }
                else
                {
                    return null;
                }
            }
            else
            {
                // <


                int co = 0;
                foreach (DictionaryEntry entry in properties)
                {
                    if (argsToSerialize == null)
                        argsToSerialize = new ArrayList();
                    argsToSerialize.Add(entry);
                    co++;
                }

                if (argsToSerialize != null)
                    return argsToSerialize.ToArray();
                else
                    return null;
            }

        } // StoreUserPropertiesForMethodMessage
Exemple #48
0
		internal void CopyFrom (IMethodMessage call)
		{
			_uri = call.Uri;
			_typeName = call.TypeName;
			_methodName = call.MethodName;
			_args = call.Args;
			_methodSignature = (Type[]) call.MethodSignature;
			_methodBase = call.MethodBase;
			_callContext = call.LogicalCallContext;
			Init();
		}
Exemple #49
0
		public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
		{
			Type type = Type.GetType (msg.TypeName);
			if (type == null)
				throw new RemotingException ("Type '" + msg.TypeName + "' not found.");

			return GetMethodBaseFromName (type, msg.MethodName, (Type[]) msg.MethodSignature);
		}
Exemple #50
0
		public static string GetSessionIdForMethodMessage(IMethodMessage msg)
		{
			// It seems that this it what MS returns.
			return msg.Uri;
		}
 public static MessageCall CreateFromIMethodMessage(IMethodMessage message)
 {
     return new MessageCall(message.MethodName, message.Args);
 }
		MethodBase GetRealMethod (IMethodMessage mm)
		{
			if (Platform.IsWindows) {
				// HACK: When running on .NET, mm.MethodBase returns the method for the type of the proxy
				// instead of the target type. There is no legal way of getting the target type, so we have
				// to use reflection here.
				FieldInfo fi = mm.GetType ().GetField ("_ID", BindingFlags.NonPublic | BindingFlags.Instance);
				if (fi != null) {
					object id = fi.GetValue (mm);
					PropertyInfo pi = id.GetType ().GetProperty ("ServerType", BindingFlags.NonPublic | BindingFlags.Instance);
					if (pi != null) {
						Type t = (Type) pi.GetValue (id, null);
						MethodBase met = t.GetMethod (mm.MethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, (Type[])mm.MethodSignature, null);
						if (met != null)
							return met;
					}
				}
			}
			return mm.MethodBase;
		}
        [System.Security.SecurityCritical]  // auto-generated 
        internal bool IsOKToStackBlt(IMethodMessage mcMsg, Object server)
        { 
            bool bOK = false;
            Message msg = mcMsg as Message;
            if(null != msg)
            { 
                IInternalMessage iiMsg = (IInternalMessage) msg;
 
                // If there is a frame in the message we can always 
                // Blt it (provided it is not a proxy to a well-known
                // object in our own appDomain)! 
                // The GetThisPtr == server test allows for people to wrap
                // our proxy with their own interception .. in that case
                // we should not blt the stack.
                if (msg.GetFramePtr() != IntPtr.Zero 
                    && msg.GetThisPtr() == server
                    && 
                    (   iiMsg.IdentityObject == null || 
                        (  iiMsg.IdentityObject != null
                            && iiMsg.IdentityObject == iiMsg.ServerIdentityObject 
                        )
                    )
                )
                { 
                    bOK = true;
                } 
            } 

            return bOK; 
        }
Exemple #54
0
        [System.Security.SecurityCritical]  // auto-generated
        protected static int StoreUserPropertiesForMethodMessage( 
            IMethodMessage msg, 
            ref ArrayList argsToSerialize)
        { 
            IDictionary properties = msg.Properties;
            MessageDictionary dict = properties as MessageDictionary;
            if (dict != null)
            { 
                if (dict.HasUserData())
                { 
                    int co = 0; 
                    foreach (DictionaryEntry entry in dict.InternalDictionary)
                    { 
                        if (argsToSerialize == null)
                            argsToSerialize = new ArrayList();
                        argsToSerialize.Add(entry);
                        co++; 
                    }
 
                    return co; 
                }
                else 
                {
                    return 0;
                }
            } 
            else
            { 
                // < 

                int co = 0; 
                foreach (DictionaryEntry entry in properties)
                {
                    if (argsToSerialize == null)
                        argsToSerialize = new ArrayList(); 
                    argsToSerialize.Add(entry);
                    co++; 
                } 

                return co; 
            }
        } // StoreUserPropertiesForMethodMessage
        [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 
 [System.Security.SecurityCritical]  // auto-generated_required 
 public static MethodBase GetMethodBaseFromMethodMessage(IMethodMessage msg)
 {
     MethodBase mb = InternalGetMethodBaseFromMethodMessage(msg);
     return mb; 
 }
Exemple #57
0
		public CADMethodRef (IMethodMessage msg)
		{
			MethodHandlePtr = msg.MethodBase.MethodHandle.Value;
			FullTypeName = msg.MethodBase.DeclaringType.AssemblyQualifiedName;
		}
        [System.Security.SecurityCritical]  // auto-generated 
        internal static MethodBase InternalGetMethodBaseFromMethodMessage(IMethodMessage msg)
        { 
            if(null == msg)
            {
                return null;
            } 

            Type t = RemotingServices.InternalGetTypeFromQualifiedTypeName(msg.TypeName); 
            if (t == null) 
            {
                throw new RemotingException( 
                    String.Format(
                        CultureInfo.CurrentCulture, Environment.GetResourceString(
                            "Remoting_BadType"),
                        msg.TypeName)); 

            } 
 
            // Use the signature, type and method name to determine the
            // methodbase via reflection. 
            Type[] signature = (Type[])msg.MethodSignature;
            return GetMethodBase(msg, t, signature);
        }
        private bool HandleEquals(IMethodMessage mm)
        {
            var arg1 = mm.Args[0];
            if (arg1 == null)
                return false;

            var proxyOperation = arg1 as IRemotingProxyOperation;
            if (proxyOperation != null)
            {
                proxyOperation.Process(this);
                return false;
            }

            return ReferenceEquals(GetTransparentProxy(), arg1);
        }
Exemple #60
0
		public void SetTestMessage (IMessage msg)
		{
			_testMsg = (IMethodMessage)msg;
			_testMsg.Properties["__Uri"] = _uri;
		}