Ejemplo n.º 1
0
        public static Func <object[], object> RegisterDelegate <T>(string id, Expression <T> expression) where T : Delegate
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException(nameof(id));
            }

            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            var methodInfo = MethodUtil.GetMethodInfo(expression);

            Func <object[], object> func;

            if (methodInfo.ReturnType != typeof(void))
            {
                func = DelegateFactory.CreateValueDelegate(expression, methodInfo);
            }
            else
            {
                var dge = DelegateFactory.CreateVoidDelegate(expression, methodInfo);
                func = (args) => {
                    dge.Invoke(args);
                    return(null);
                };
            }

            RegisterMethod(id, func);
            return(func);
        }
        // ===============================================================================
        //                                                          ConditionBean Override
        //                                                          ======================
        protected override void SetupSelectMethodByAuto(MethodInfo methodInfo)
        {
            if (SetupInternalSelectMethodSequenceNextVal(methodInfo))
            {
                return;
            }

            // Assert unsupported
            String query = _annotationReader.GetQuery(methodInfo.Name);

            AssertQueryAnnotationUnsupported(methodInfo, query);

            IDataReaderHandler handler = CreateDataReaderHandler(methodInfo);

            String[]             argNames = MethodUtil.GetParameterNames(methodInfo);
            Type[]               argTypes = MethodUtil.GetParameterTypes(methodInfo);
            SelectDynamicCommand cmd      = CreateSelectDynamicCommand(handler);

            if (argTypes.Length == 1 && ValueTypes.GetValueType(argTypes[0]) == ValueTypes.OBJECT)
            {
                argNames = new String[] { "pmb" };
                AssertAutoQueryByDtoUnsupported(methodInfo, argTypes);
                S2DaoSelectDynamicCommand dynamicCommand = CreateCustomizeSelectDynamicCommand(handler);
                cmd = dynamicCommand;
            }
            else
            {
                HandleAutoQueryByArgsAnnotationUnsupported(methodInfo, argNames);
            }
            cmd.ArgNames = argNames;
            cmd.ArgTypes = argTypes;
            _sqlCommands[methodInfo.Name] = cmd;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// senderに指定のプロパティが存在するか調べます。
        /// </summary>
        private void VerifyProperty(object sender,
                                    PropertyChangedEventArgs e)
        {
            if (sender == null)
            {
                throw new ArgumentNullException("sender");
            }

            if (e == null || string.IsNullOrEmpty(e.PropertyName))
            {
                throw new ArgumentException(
                          "プロパティ名がありません。", "e");
            }

#if !RGN_DYNAMICVIEWMODEL
            // 変更通知の対象となるプロパティを取得します。
            var propertyDic = MethodUtil.GetPropertyDic(sender.GetType());
            if (propertyDic == null)
            {
                throw new RagnarokException(
                          "プロパティリストが取得できませんでした。");
            }

            if (!propertyDic.ContainsKey(e.PropertyName))
            {
                throw new InvalidOperationException(
                          string.Format(
                              "型'{0}'にプロパティ'{1}'は存在しません。",
                              sender.GetType(), e.PropertyName));
            }
#endif
        }
Ejemplo n.º 4
0
        public static Method Register(
            string methodId,
            Expression<Action> implementExpression){

            if (implementExpression == null) {
                throw new ArgumentNullException(nameof(implementExpression));
            }

            var method = MethodUtil.GetMethodInfo(implementExpression);

            if (typeof(Delegate).IsAssignableFrom(method.DeclaringType)) {
                throw new ArgumentException($"{nameof(implementExpression)}不能为Delegate!");
            }

            Func<object[], object> func = null;

            if (method.IsStatic) {
                if (method.ReturnType == typeof(void)) {
                    func = RpcRegister.RegisterStaticVoidMethod(methodId, method);
                } else {
                    func = RpcRegister.RegisterStaticValueMethod(methodId, method);
                }
            } else {
                if (method.ReturnType == typeof(void)) {
                    func = RpcRegister.RegisterVoidMethod(methodId, GetObject(implementExpression), method);
                } else {
                    func = RpcRegister.RegisterValueMethod(methodId, GetObject(implementExpression), method);
                }
            }

            return new Method { Id = methodId, Function = func }; 
        }
Ejemplo n.º 5
0
        private static void InstanceTests()
        {
            MethodBase[] methods =
            {
                typeof(InstanceClassA).GetMethod("A", BindingFlags.Instance | BindingFlags.Public),
                typeof(InstanceClassA).GetMethod("B", BindingFlags.Instance | BindingFlags.Public),
                typeof(InstanceClassB).GetMethod("A", BindingFlags.Instance | BindingFlags.Public),
                typeof(InstanceClassB).GetMethod("B", BindingFlags.Instance | BindingFlags.Public)
            };



            // Jit TestStaticReplaceJited
            RuntimeHelpers.PrepareMethod(
                typeof(Program).GetMethod("TestInstanceReplaceJited", BindingFlags.Static | BindingFlags.NonPublic).MethodHandle);

            // Replace StaticClassA.A() with StaticClassB.A()
            Console.WriteLine("Replacing InstanceClassA.A() with InstanceClassB.A()");
            MethodUtil.ReplaceMethod(methods[2], methods[0]);

            // Call StaticClassA.A() from a  method that has already been jited
            Console.WriteLine("Call InstanceClassA.A() from a  method that has already been jited");
            TestInstanceReplaceJited();

            // Call StaticClassA.A() from a  method that has not been jited
            Console.WriteLine("Call InstanceClassA.A() from a  method that has not been jited");
            TestInstanceReplace();
        }
        // ===============================================================================
        //                                                             OutsideSql Override
        //                                                             ===================
        // -------------------------------------------------
        //                            Traditional OutsideSql
        //                            ----------------------
        protected override void SetupSelectMethodByManual(MethodInfo mi, string sql)
        {
            string[] parameterNames         = MethodUtil.GetParameterNames(mi);
            Type[]   parameterTypes         = MethodUtil.GetParameterTypes(mi);
            string[] filteredParameterNames = null;
            Type[]   filteredParameterTypes = null;
            if (parameterTypes != null && parameterTypes.Length > 0 &&
                typeof(CursorHandler).IsAssignableFrom(parameterTypes[parameterTypes.Length - 1]))
            {
                filteredParameterNames = new string[parameterTypes.Length - 1];
                filteredParameterTypes = new Type[parameterTypes.Length - 1];
                for (int i = 0; i < parameterTypes.Length - 1; i++)
                {
                    filteredParameterNames[i] = parameterNames[i];
                    filteredParameterTypes[i] = parameterTypes[i];
                }
            }
            else
            {
                filteredParameterNames = parameterNames;
                filteredParameterTypes = parameterTypes;
            }
            IBeanMetaData      myMetaData          = GetOutsideSqlBeanMetaData(mi, _dbMetaData, _dbms);
            IDataReaderHandler myDataReaderHandler = CreateDataReaderHandler(mi, myMetaData);

            RegisterSqlCommand(mi.Name, mi, sql, filteredParameterNames, filteredParameterTypes, myDataReaderHandler);
        }
Ejemplo n.º 7
0
        public void MoveBlackTest1()
        {
            var board = MakeBoard1(BWType.Black);

            var move = BoardMove.CreateMove(
                BWType.Black, new Square(8, 3), new Square(8, 2),
                new Piece(PieceType.Kyo, false), true);

            Assert.True(board.CanMove(move));

            // 駒が設定されてないと動けません。
            MethodUtil.SetPropertyValue(move, "MovePiece", new Piece());
            Assert.False(board.CanMove(move));
            MethodUtil.SetPropertyValue(move, "MovePiece", new Piece(PieceType.Kyo, false));

            // 84の駒は移動できません。
            MethodUtil.SetPropertyValue(move, "SrcSquare", new Square(8, 4));
            Assert.False(board.CanMove(move));
            MethodUtil.SetPropertyValue(move, "SrcSquare", new Square(8, 3));

            CanMoveTo(board, move, new List <Tuple <Square, bool> >
            {
                Tuple.Create(new Square(8, 2), false),
                Tuple.Create(new Square(8, 1), true),
            });
        }
Ejemplo n.º 8
0
 /// <summary>
 /// ViewModelの状態を元に戻します。
 /// </summary>
 public void RollbackViewModel()
 {
     lock (this.oldPropertyValueDic)
     {
         this.oldPropertyValueDic.ForEach(_ =>
                                          MethodUtil.SetPropertyValue(ViewModel, _.Key, _.Value));
     }
 }
Ejemplo n.º 9
0
        private void KillProfiler()
        {
            var keenStart = typeof(MySimpleProfiler).GetMethod("Begin");
            var keenEnd   = typeof(MySimpleProfiler).GetMethod("End");
            var ourStart  = typeof(Server).GetMethod("Begin");
            var ourEnd    = typeof(Server).GetMethod("End");

            MethodUtil.ReplaceMethod(ourStart, keenStart);
            MethodUtil.ReplaceMethod(ourEnd, keenEnd);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 他プロパティに依存しているプロパティを計算します。
        /// </summary>
        private MultiMap <TypeProperty, string> MakeDependPropertyMap(
            Type targetType)
        {
            const BindingFlags flags =
                BindingFlags.Instance |
                BindingFlags.GetProperty |
                BindingFlags.SetProperty |
                BindingFlags.Public |
                BindingFlags.NonPublic;
            var propertyList = MethodUtil.GetThisAndInheritClasses(targetType)
                               .SelectMany(klass => klass.GetProperties(flags));

            var result = new MultiMap <TypeProperty, string>(
                new TypePropertyComparer());

            // このクラスのプロパティから、DependOnPropertyAttributeを持つ
            // ものを抜き出します。
            //
            // 作成するものがMultiMapなので、Linqは使いにくいです。
            foreach (var property in propertyList)
            {
                var attrList = property.GetCustomAttributes(
                    typeof(DependOnPropertyAttribute), true);

                foreach (var attr in attrList)
                {
                    var dependAttr = attr as DependOnPropertyAttribute;
                    if (dependAttr == null)
                    {
                        continue;
                    }

                    // 依存先の型がないときは自分の型と同じになります。
                    var dependType =
                        (dependAttr.DependType ?? targetType);

                    // 依存先プロパティの名前がないときは、
                    // 依存先のプロパティ名は依存元と同じになります。
                    var dependName =
                        (!string.IsNullOrEmpty(dependAttr.DependName)
                        ? dependAttr.DependName
                        : property.Name);

                    // 依存元のプロパティに依存先のプロパティを紐つけます。
                    result.Add(
                        new TypeProperty(dependType, dependName),
                        property.Name);
                }
            }

            return(result);
        }
Ejemplo n.º 11
0
        public static void Run()
        {
            // I think at a lower level this call uses the one below so may not be necessary
            MethodBase checkMethod        = typeof(GraphicsAdapter).GetMethod("IsProfileSupported", BindingFlags.Instance | BindingFlags.Public);
            MethodBase replaceCheckMethod = typeof(GraphicsAdapterReplacement).GetMethod("IsProfileSupported", BindingFlags.Instance | BindingFlags.Public);

            MethodUtil.ReplaceMethod(replaceCheckMethod, checkMethod);

            // Disable the profile capabilities check
            MethodBase profileMethod        = typeof(GraphicsAdapter).GetMethod("IsProfileSupported", BindingFlags.Instance | BindingFlags.NonPublic);
            MethodBase replaceProfileMethod = typeof(GraphicsAdapterReplacement).GetMethod("IsProfileSupported", BindingFlags.Instance | BindingFlags.NonPublic);

            MethodUtil.ReplaceMethod(replaceProfileMethod, profileMethod);
        }
Ejemplo n.º 12
0
        private void MyPropertyChanging(object sender, PropertyChangingEventArgs e)
        {
            lock (this.oldPropertyValueDic)
            {
                // ViewModelの状態を元すため、プロパティの元の値を保存します。
                if (!this.oldPropertyValueDic.ContainsKey(e.PropertyName))
                {
                    this.oldPropertyValueDic[e.PropertyName] =
                        MethodUtil.GetPropertyValue(sender, e.PropertyName);
                }
            }

            base.OnPropertyChanging(e);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// オブジェクトが持つ全プロパティの変更を通知します。
        /// </summary>
        /// <remarks>
        /// 重複したプロパティに対して通知が出されることがあります。
        /// </remarks>
        public void RaiseAllPropertyChanged(object target)
        {
            var properties = MethodUtil.GetPropertyDic(target.GetType());

            foreach (var property in properties)
            {
                if (target == this)
                {
                    this.RaisePropertyChanged(property.Key);
                }
                else
                {
                    this.DependModel_PropertyChanged(
                        target, new PropertyChangedEventArgs(property.Key));
                }
            }
        }
Ejemplo n.º 14
0
        public static string GetId <T>(Expression <T> expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            var method   = MethodUtil.GetMethodInfo(expression);
            var response = method.GetCustomAttribute <RpcResponseAttribute>();

            if (response == null)
            {
                throw new MissingAttributeException($"{method.Name}缺少{nameof(RpcResponseAttribute)}属性");
            }

            return(response.GetId());
        }
Ejemplo n.º 15
0
        /// <summary>
        /// プロパティ名から依存プロパティを検索します。
        /// </summary>
        private static DependencyProperty GetDepPropertyImpl(Type sourceType,
                                                             string propertyName)
        {
            const BindingFlags flags =
                BindingFlags.Static |
                BindingFlags.GetField |
                BindingFlags.Public;

            var classes = MethodUtil.GetThisAndInheritClasses(sourceType);

            var propertyList = classes
                               .SelectMany(_ => _.GetFields(flags))
                               .Select(_ => _.GetValue(null) as DependencyProperty)
                               .Where(_ => _ != null);

            return(propertyList.FirstOrDefault(_ => _.Name == propertyName));
        }
Ejemplo n.º 16
0
        public static Method Register<TDelegate>(
            string methodId,
            Expression<TDelegate> implementExpression) where TDelegate : Delegate {

            if (implementExpression == null) {
                throw new ArgumentNullException(nameof(implementExpression));
            }

            var method = MethodUtil.GetMethodInfo(implementExpression);

            if (!typeof(Delegate).IsAssignableFrom(method.DeclaringType)) {
                throw new ArgumentException($"{nameof(implementExpression)}不是delegate类型!");
            }

            var func = RpcRegister.RegisterDelegate(methodId, implementExpression);
            return new Method { Id = methodId, Function = func };
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 駒の各移動先に対して、その手が指せるのかどうかをチェックします。
        /// </summary>
        private void CanMoveTo(Board board, BoardMove move,
                               List <Tuple <Square, bool> > availables)
        {
            for (var file = 1; file <= Board.BoardSize; ++file)
            {
                for (var rank = 1; rank <= Board.BoardSize; ++rank)
                {
                    var sq    = new Square(file, rank);
                    var avail = availables.FirstOrDefault(_ => _.Item1 == sq);

                    MethodUtil.SetPropertyValue(move, "DstSquare", sq);
                    if (avail != null)
                    {
                        if (avail.Item2)
                        {
                            // 成りが必須の場合
                            move.IsPromote = false;
                            Assert.False(board.CanMove(move));

                            move.IsPromote = true;
                            Assert.True(board.CanMove(move));
                        }
                        else
                        {
                            // 成りが必須でない場合
                            move.IsPromote = false;
                            Assert.True(board.CanMove(move));

                            move.IsPromote = true;
                            Assert.AreEqual(Board.CanPromote(move), board.CanMove(move));
                        }
                    }
                    else
                    {
                        // そもそも移動できる場所ではない
                        move.IsPromote = false;
                        Assert.False(board.CanMove(move));

                        move.IsPromote = true;
                        Assert.False(board.CanMove(move));
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public static void Init()
        {
            //ApplicationLog.BaseLog.Warn("Skipping profiler init");
            //return;
            var entType = typeof(MyEntities);

            m_entitiesForUpdate    = (MyDistributedUpdater <CachingList <MyEntity>, MyEntity>)entType.GetField("m_entitiesForUpdate", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
            m_entitiesForUpdate10  = (MyDistributedUpdater <CachingList <MyEntity>, MyEntity>)entType.GetField("m_entitiesForUpdate10", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
            m_entitiesForUpdate100 = (MyDistributedUpdater <CachingList <MyEntity>, MyEntity>)entType.GetField("m_entitiesForUpdate100", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);
            m_creationThread       = (MyEntityCreationThread)entType.GetField("m_creationThread", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null);

            var keenBefore = entType.GetMethod("UpdateBeforeSimulation");
            var ourBefore  = typeof(ProfilerInjection).GetMethod("UpdateBeforeSimulation");
            var keenAfter  = entType.GetMethod("UpdateAfterSimulation");
            var ourAfter   = typeof(ProfilerInjection).GetMethod("UpdateAfterSimulation");

            //using (var md5 = MD5.Create())
            //{
            //    var body = keenBefore.GetMethodBody().GetILAsByteArray();
            //    var hash = md5.ComputeHash(body);
            //    string compStr = Convert.ToBase64String(hash).ToUpper();
            //    if (compStr!= "YXXKWK+W+OHP+LNOGGM32A==" || body.Length != 238)
            //    {
            //        BaseLog.Warn("UpdateBeforeSimulation signature has changed! Cannot load profiler injector!");
            //        BaseLog.Error($"{compStr}:{body.Length}");
            //        return;
            //    }

            //    body = keenAfter.GetMethodBody().GetILAsByteArray();
            //    hash = md5.ComputeHash(body);
            //    compStr = Convert.ToBase64String(hash).ToUpper();
            //    if (compStr!= "7ZKFYWZRON9U3G43AV4QRA==" || body.Length != 220)
            //    {
            //        BaseLog.Warn("UpdateAfterSimulation signature has changed! Cannot load profiler injector!");
            //        BaseLog.Error($"{compStr}:{body.Length}");
            //        return;
            //    }
            //}
            BaseLog.Info("Replacing UpdateBeforeSimulation");
            MethodUtil.ReplaceMethod(ourBefore, keenBefore);
            BaseLog.Info("Replacing UpdateAfterSimulation");
            MethodUtil.ReplaceMethod(ourAfter, keenAfter);
        }
Ejemplo n.º 19
0
        public void Set(Func <T, TResult> func)
        {
            if (victim.IsStatic && !func.Method.IsStatic)
            {
                func = Clone(func);
            }
            curFunc = func;

            Action curUnhook;

            if (!MethodUtil.HookMethod(victim, func.Method, out curUnhook))
            {
                throw new InvalidOperationException(String.Format("Unable to hook method '{0}'", Formatter.Format(victim)));
            }
            if (unhook == null)
            {
                unhook = curUnhook;
            }
        }
Ejemplo n.º 20
0
        private Object ApplyGetters(Object target, String getters)
        {
            if (getters == null || getters.Equals(""))
            {
                return(target);
            }
            int firstDot = getters.IndexOf('.');

            if (firstDot == -1)
            {
                firstDot = getters.Length();
            }
            String first = getters.Substring(0, firstDot);
            String rest  = getters.Substring(System.Math.Min(firstDot + 1, getters.Length()));

            try
            {
                Method getter = null;
                if (target != null)
                {
                    getter = Statement.GetMethod(target.GetType(), "get" + NameGenerator.Capitalize(first), new Class[] {});
                    if (getter == null)
                    {
                        getter = Statement.GetMethod(target.GetType(), "is" + NameGenerator.Capitalize(first), new Class[] {});
                    }
                    if (getter == null)
                    {
                        getter = Statement.GetMethod(target.GetType(), first, new Class[] {});
                    }
                }
                if (getter == null)
                {
                    throw new RuntimeException("No method called: " + first + " defined on " + target);
                }
                Object newTarget = MethodUtil.invoke(getter, target, new Object[] {});
                return(ApplyGetters(newTarget, rest));
            }
            catch (Exception e)
            {
                throw new RuntimeException("Failed to call method: " + first + " on " + target, e);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This default implementation of the <code>instantiate</code> method returns
        /// an expression containing the predefined method name "new" which denotes a
        /// call to a constructor with the arguments as specified in
        /// the <code>DefaultPersistenceDelegate</code>'s constructor.
        /// </summary>
        /// <param name="oldInstance"> The instance to be instantiated. </param>
        /// <param name="out"> The code output stream. </param>
        /// <returns> An expression whose value is <code>oldInstance</code>.
        /// </returns>
        /// <exception cref="NullPointerException"> if {@code out} is {@code null}
        ///                              and this value is used in the method
        /// </exception>
        /// <seealso cref= #DefaultPersistenceDelegate(String[]) </seealso>
        protected internal override Expression Instantiate(Object oldInstance, Encoder @out)
        {
            int   nArgs = Constructor.Length;
            Class type  = oldInstance.GetType();

            Object[] constructorArgs = new Object[nArgs];
            for (int i = 0; i < nArgs; i++)
            {
                try
                {
                    Method method = FindMethod(type, this.Constructor[i]);
                    constructorArgs[i] = MethodUtil.invoke(method, oldInstance, new Object[0]);
                }
                catch (Exception e)
                {
                    @out.ExceptionListener.ExceptionThrown(e);
                }
            }
            return(new Expression(oldInstance, oldInstance.GetType(), "new", constructorArgs));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public BindingData(Binding binding)
        {
            Binding = binding;

            this.targetPropertyObject = MethodUtil.GetPropertyObject(
                Binding.BindableTarget.GetType(), Binding.BindingPropertyName);
            if (this.targetPropertyObject == null)
            {
                throw new ArgumentException(
                          Binding.BindingPropertyName + ": 指定のプロパティが存在しません。");
            }

            this.sourcePropertyObject = MethodUtil.GetPropertyObject(
                Binding.DataSource.GetType(), Binding.DataSourcePropertyName);
            if (this.sourcePropertyObject == null)
            {
                throw new ArgumentException(
                          Binding.DataSourcePropertyName + ": 指定のプロパティが存在しません。");
            }
        }
Ejemplo n.º 23
0
        public void MoveWhiteTest1()
        {
            var board = MakeBoard1(BWType.White);

            var move = BoardMove.CreateMove(
                BWType.White, new Square(9, 7), new Square(9, 8),
                new Piece(PieceType.Hu, false), true);

            Assert.True(board.CanMove(move));

            // 84の駒は移動できません。
            MethodUtil.SetPropertyValue(move, "SrcSquare", new Square(8, 4));
            Assert.False(board.CanMove(move));
            MethodUtil.SetPropertyValue(move, "SrcSquare", new Square(9, 7));

            CanMoveTo(board, move, new List <Tuple <Square, bool> >
            {
                Tuple.Create(new Square(9, 8), false),
            });
        }
Ejemplo n.º 24
0
        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage methodMessage = new MethodCallMessageWrapper((IMethodCallMessage)msg);
            var args = methodMessage.Args;

            Type[]     argumentTypes  = MethodUtil.GetArgTypes(args);
            MethodInfo targetMethod   = GetMethodInfoForMethodBase(methodMessage, argumentTypes);
            object     objReturnValue = null;

            if (targetMethod != null)
            {
                if (targetMethod.Name.Equals("Equals") && argumentTypes != null && argumentTypes.Length == 1 && argumentTypes[0].IsAssignableFrom((typeof(Object))))
                {
                    objReturnValue = false;
                }
                else if (targetMethod.Name.Equals("GetHashCode") && argumentTypes.Length == 0)
                {
                    objReturnValue = _proxyType.GetHashCode();
                }
                else if (targetMethod.Name.Equals("ToString") && argumentTypes.Length == 0)
                {
                    objReturnValue = "[Proxy " + _proxyType.Name + "]";
                }
                else if (targetMethod.Name.Equals("GetType") && argumentTypes.Length == 0)
                {
                    objReturnValue = _proxyType;
                }
                else
                {
                    objReturnValue = DoMethodCall(args, argumentTypes, targetMethod);
                }
            }
            else
            {
                if (targetMethod.Name.Equals("GetType") && (args.Length == 0))
                {
                    objReturnValue = _proxyType;
                }
            }
            return(new ReturnMessage(objReturnValue, methodMessage.Args, methodMessage.ArgCount, methodMessage.LogicalCallContext, methodMessage));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// プロパティ値の取得・設定用オブジェクトを取得します。
        /// </summary>
        private IPropertyObject GetPropertyObject(object target)
        {
            var pobj = MethodUtil.GetPropertyObject(
                target.GetType(), TargetProperty);

            if (pobj == null)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "{0}.{1}: プロパティ名が正しくありません。",
                              target.GetType(), TargetProperty));
            }

            if (!pobj.PropertyType.Equals(TargetPropertyType))
            {
                throw new InvalidOperationException(
                          string.Format(
                              "{0}.{1}: プロパティの型が正しくありません。",
                              target.GetType(), TargetProperty));
            }

            if (!pobj.CanRead)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "{0}.{1}: このプロパティは読み込みできません。",
                              target.GetType(), TargetProperty));
            }

            if (!pobj.CanWrite)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "{0}.{1}: このプロパティには書き込みできません。",
                              target.GetType(), TargetProperty));
            }

            return(pobj);
        }
Ejemplo n.º 26
0
        protected override object Invoke(MethodInfo targetMethod, object[] args)
        {
            Type[] argumentTypes  = MethodUtil.GetArgTypes(args);
            object objReturnValue = null;

            if (targetMethod != null)
            {
                if (targetMethod.Name.Equals("Equals") && argumentTypes != null && argumentTypes.Length == 1 && argumentTypes[0].IsAssignableFrom((typeof(Object))))
                {
                    objReturnValue = false;
                }
                else if (targetMethod.Name.Equals("GetHashCode") && argumentTypes.Length == 0)
                {
                    objReturnValue = _proxyType.GetHashCode();
                }
                else if (targetMethod.Name.Equals("ToString") && argumentTypes.Length == 0)
                {
                    objReturnValue = "[Proxy " + _proxyType.Name + "]";
                }
                else if (targetMethod.Name.Equals("GetType") && argumentTypes.Length == 0)
                {
                    objReturnValue = _proxyType;
                }
                else
                {
                    objReturnValue = DoMethodCall(args, argumentTypes, targetMethod);
                }
            }
            else
            {
                if (targetMethod.Name.Equals("GetType") && (args.Length == 0))
                {
                    objReturnValue = _proxyType;
                }
            }
            return(objReturnValue);
        }
Ejemplo n.º 27
0
        public static void Main(string[] args)
        {
            var method = typeof(FileStream).GetMethod("Init", BindingFlags.Instance | BindingFlags.NonPublic);
            var body   = MethodBody.Read(method, true);

            body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldarg_1));
            var debugWriteLineMethod = typeof(Debug).GetMethod("WriteLine", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null);

            body.Instructions.Insert(1, Instruction.Create(OpCodes.Call, debugWriteLineMethod));
            Console.WriteLine(body);

            var    parameterTypes = new [] { method.DeclaringType }.Concat(method.GetParameters().Select(p => p.ParameterType)).ToArray();
            var    del = body.CreateDelegate(method.ReturnType, parameterTypes);
            Action unhook;

            if (!MethodUtil.HookMethod(method, del.Method, out unhook))
            {
                throw new InvalidOperationException("Unable to hook method");
            }
            File.WriteAllText(@"c:\temp\test.txt", "test");

            using (var mock = new Mock <int, int[]>(x => DataReader.Read(x)))
            {
                //mock.Set(MockedMethod);
                mock.Set(x =>
                {
                    if (x == 42)
                    {
                        return new[] { 1, 4, 7, 8 }
                    }
                    ;
                    throw new InvalidOperationException();
                });
                var dataProcessor = new DataProcessor();
                Assert.AreEqual(5, dataProcessor.FindAverage(42));
            }
        }
Ejemplo n.º 28
0
        public static MethodTuple CreateMethodTuple <T>(Expression <T> expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            var method   = MethodUtil.GetMethodInfo(expression);
            var response = method.GetCustomAttribute <RpcRequestAttribute>();

            if (response == null)
            {
                throw new MissingAttributeException($"{method.Name}缺少{nameof(RpcRequestAttribute)}属性");
            }

            var dge        = CreateDelegate(expression);
            var methodTupe = new MethodTuple()
            {
                RpcMethod = response,
                Action    = dge
            };

            return(methodTupe);
        }
Ejemplo n.º 29
0
        private static void DynamicTests()
        {
            // Create dynamic method C in StaticClassA
            var dynamicMethod = CreateTestMethod(typeof(StaticClassA), "C");

            // Get methodbase for class
            MethodBase method = typeof(StaticClassA).GetMethod("B", BindingFlags.Static | BindingFlags.Public);

            // Jit TestStaticReplaceJited
            RuntimeHelpers.PrepareMethod(typeof(Program)
                                         .GetMethod("TestDynamicReplaceJited", BindingFlags.Static | BindingFlags.NonPublic).MethodHandle);

            // Replace StaticClassA.B() with dynamic StaticClassA.C()
            Console.WriteLine("Replacing StaticClassA.B() with dynamic StaticClassA.C()");
            MethodUtil.ReplaceMethod(dynamicMethod, method);

            // Call StaticClassA.B() from a  method that has already been jited
            Console.WriteLine("Call StaticClassA.B() from a  method that has already been jited");
            TestDynamicReplaceJited();

            // Call StaticClassA.B() from a  method that has not been jited
            Console.WriteLine("Call StaticClassA.B() from a  method that has not been jited");
            TestDynamicReplace();
        }
Ejemplo n.º 30
0
        public static void HookDevenv()
        {
            var method = typeof(FileStream).GetMethod("Init", BindingFlags.Instance | BindingFlags.NonPublic);
            var body   = MethodBody.Read(method, true);

            body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldstr, "TRACING: "));
            body.Instructions.Insert(1, Instruction.Create(OpCodes.Ldarg_1));
            var stringConcatMethod = typeof(string).GetMethod("Concat", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string), typeof(string) }, null);

            body.Instructions.Insert(2, Instruction.Create(OpCodes.Call, stringConcatMethod));
            var debugWriteLineMethod = typeof(Debug).GetMethod("WriteLine", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(string) }, null);

            body.Instructions.Insert(3, Instruction.Create(OpCodes.Call, debugWriteLineMethod));

            var parameterTypes = new[] { method.DeclaringType }.Concat(method.GetParameters().Select(p => p.ParameterType)).ToArray();

            del = body.CreateDelegate(method.ReturnType, parameterTypes);
            Action unhook;

            if (!MethodUtil.HookMethod(method, del.Method, out unhook))
            {
                Debug.WriteLine("Unable to hook method");
            }
        }