コード例 #1
0
        private void CompileHandlerMethods()
        {
            var type    = GetType();
            var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);

            foreach (var m in methods)
            {
                var mas = m.GetCustomAttributes().OfType <IRouteAttribute>().ToArray();
                if (mas.Length == 0)
                {
                    continue;
                }

                foreach (var a in mas.OfType <ITargetedAttribute>())
                {
                    a.InitForTarget(m);
                }

                var hm = new HandlerMethod {
                    _method  = m,
                    _invoker = ResolveHandlerInvoker(m),
                };
                hm._routes = mas.SelectMany(ma => ma.GetRoutes()).SelectMany(mar => {
                    var id = Guid.NewGuid();
                    _handlerMethodMap[id] = hm;

                    return(ResolveFullMethodRoutes(mar.route, mar.constraint, new { handlerMethodId = id }));
                });

                _handlerMethods.Add(hm);
            }
        }
コード例 #2
0
        protected virtual void ProcessHandlerMethodException(HandlerMethod handlerMethod, Exception exception, IMessage message)
        {
            var invocable = GetExceptionHandlerMethod(handlerMethod, exception);

            if (invocable == null)
            {
                // logger.error("Unhandled exception from message handler method", exception);
                return;
            }

            invocable.MessageMethodArgumentResolvers = MethodArgumentResolvers;

            try
            {
                var cause       = exception.InnerException;
                var returnValue = cause != null?
                                  invocable.Invoke(message, exception, cause, handlerMethod) :
                                      invocable.Invoke(message, exception, handlerMethod);

                var returnType = invocable.ReturnType;
                if (returnType.ParameterType == typeof(void))
                {
                    return;
                }

                MethodReturnValueHandlers.HandleReturnValue(returnValue, returnType, message);
            }
            catch (Exception)
            {
                // logger.error("Error while processing handler method exception", ex2);
            }
        }
コード例 #3
0
        protected virtual HandlerMethod CreateHandlerMethod(object handler, MethodInfo method)
        {
            HandlerMethod handlerMethod;

            handlerMethod = new HandlerMethod(handler, method);
            return(handlerMethod);
        }
コード例 #4
0
        protected virtual void HandleMatch(T mapping, HandlerMethod handlerMethod, string lookupDestination, IMessage message)
        {
            handlerMethod = handlerMethod.CreateWithResolvedBean();
            var invocable = new InvocableHandlerMethod(handlerMethod);

            invocable.MessageMethodArgumentResolvers = MethodArgumentResolvers;
            try
            {
                var returnValue = invocable.Invoke(message);
                var returnType  = handlerMethod.ReturnType;
                if (returnType.ParameterType == typeof(void))
                {
                    return;
                }

                if (returnValue != null && MethodReturnValueHandlers.IsAsyncReturnValue(returnValue, returnType))
                {
                    var task = returnValue as Task;

                    throw new NotImplementedException("Async still todo");
                }
                else
                {
                    MethodReturnValueHandlers.HandleReturnValue(returnValue, returnType, message);
                }
            }
            catch (Exception ex)
            {
                Exception handlingException =
                    new MessageHandlingException(message, "Unexpected handler method invocation error", ex);
                ProcessHandlerMethodException(handlerMethod, handlingException, message);
            }
        }
コード例 #5
0
        static void Main(string[] args)
        {
            HandlerMethod handlerMammals = MammalsHandler;

            // Covariance enables this assignment
            HandlerMethod handlerDogs = DogsHandler;
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: callofduty890/Delegate
        static void Main(string[] args)
        {
            //正常的匹配 返回父类 输入形参:无
            HandlerMethod handler1 = FirstHandler;

            handler1();
            //协变 返回值Dog默认转换为Mammal(父类中装子类)
            HandlerMethod handler2 = SecondHandler;

            handler2();

            //创建父类的对象
            Manmal m = new Manmal();
            //正常匹配 无返回值,输入的形参为父类
            HandleModthod1 handler11 = ThirdHandler;

            handler11(m);


            //创建子类的对象
            Dog d = new Dog();
            //逆变,参数Dog默认可以转换成为Mammal
            HandleModthod2 handle33 = ThirdHandler;

            handle33(d);
        }
コード例 #7
0
ファイル: form1.cs プロジェクト: wzchua/docs
        static void Test()
        {
            HandlerMethod handlerMammals = MammalsHandler;

            // Covariance enables this assignment.
            HandlerMethod handlerDogs = DogsHandler;
        }
コード例 #8
0
        private void CreateViewHandler(HandlerMethod method)
        {
            if (method == HandlerMethod.ADD_HANDLERS)
            {
                TBL.SP_Object.StateChanged += SP_Object_StateChanged;

                c.BTN_CRED.Click                += CREDENTIAL_BTN_Click;
                c.CARD_HINT_RETRY_BTN.Click     += CARD_HINT_RETRY_Click;
                c.CARD_HINT_ENTERCRED_BTN.Click += CREDENTIAL_BTN_Click;

                c.SPINNER_TIME.ItemSelected += SPINNER_TIME_ItemSelected;

                c.CHECK_NOTIFY_NEWFEED.CheckedChange          += CHECK_NOTIFY_CHANGED;
                c.CHECK_NOTIFY_NEWSHIFTS.CheckedChange        += CHECK_NOTIFY_CHANGED;
                c.CHECK_NOTIFY_NEWSHIFTSVERSION.CheckedChange += CHECK_NOTIFY_CHANGED;

                c.NOTIFICATION_LINK.Click += NOTIFICATION_LINK_Click;
            }
            else
            {
                TBL.SP_Object.StateChanged -= SP_Object_StateChanged;

                c.BTN_CRED.Click                -= CREDENTIAL_BTN_Click;
                c.CARD_HINT_RETRY_BTN.Click     -= CARD_HINT_RETRY_Click;
                c.CARD_HINT_ENTERCRED_BTN.Click -= CREDENTIAL_BTN_Click;

                c.SPINNER_TIME.ItemSelected -= SPINNER_TIME_ItemSelected;

                c.CHECK_NOTIFY_NEWFEED.CheckedChange          -= CHECK_NOTIFY_CHANGED;
                c.CHECK_NOTIFY_NEWSHIFTS.CheckedChange        -= CHECK_NOTIFY_CHANGED;
                c.CHECK_NOTIFY_NEWSHIFTSVERSION.CheckedChange -= CHECK_NOTIFY_CHANGED;

                c.NOTIFICATION_LINK.Click -= NOTIFICATION_LINK_Click;
            }
        }
コード例 #9
0
        public void Bind <T>(HandlerMethod <T> method) where T : ITW.Protocol.Packet
        {
            if (bindedMethods.ContainsKey(typeof(T)) == false)
            {
                bindedMethods.Add(typeof(T), new List <object>());
            }

            bindedMethods[typeof(T)].Add(method);
        }
コード例 #10
0
 public override bool Equals(object obj)
 {
     if (obj is EventHandlingInfos infos)
     {
         return(infos.HandlerMethod.ToString() == HandlerMethod.ToString() &&
                new TypeEqualityComparer().Equals(infos.HandlerMethod.ReflectedType, HandlerMethod.ReflectedType));
     }
     return(false);
 }
コード例 #11
0
        public void Match_QueryMethod_Does_Not_Match_IncorrectMethodName()
        {
            var methodObject = new HandlerMethod(typeof(HandlerMethodTests).GetMethod("GetCrayons"), TypeMapper);

            Assert.That(
                methodObject.Match(HttpMethod.Get,
                                   PathNodeType.Collection,
                                   TypeMapper.FromType(typeof(Critter))),
                Is.Null);
        }
コード例 #12
0
        public void Match_QueryMethod_PrefixedWithQuery_Matches_CorrectSignature()
        {
            var methodObject = new HandlerMethod(typeof(HandlerMethodTests).GetMethod("QueryCritters"), TypeMapper);

            Assert.That(
                methodObject.Match(HttpMethod.Get,
                                   PathNodeType.Collection,
                                   TypeMapper.FromType(typeof(Critter))),
                Is.Not.Null);
        }
コード例 #13
0
    protected override IEnumerator RespondToCommandInternal(string command)
    {
        IEnumerator handler = (IEnumerator)HandlerMethod.Invoke(CommandComponent, new object[] { command });

        CancelBool?.SetValue(CommandComponent, false);
        while (handler.MoveNext())
        {
            yield return(handler.Current);
        }
    }
コード例 #14
0
ファイル: Program.cs プロジェクト: shyboylpf/csharpBeginToEnd
        static void Main(string[] args)
        {
            HandlerMethod handler = FirstHandler;

            Console.WriteLine(handler().GetType());

            HandlerMethod handler2 = SecondHandler;

            Console.WriteLine(handler2().GetType());
            Console.WriteLine("Hello World!");
        }
コード例 #15
0
        public void Match_ChildResource_Takes_ParentResource()
        {
            var methodObject = new HandlerMethod(typeof(HandlerMethodTests).GetMethod("GetPlanetarySystems"),
                                                 TypeMapper);

            Assert.That(
                methodObject.Match(HttpMethod.Get,
                                   PathNodeType.Collection,
                                   TypeMapper.FromType(typeof(PlanetarySystem))),
                Is.Not.Null);
        }
コード例 #16
0
    protected override IEnumerator RespondToCommandInternal(string command)
    {
        KMSelectable[] selectables = (KMSelectable[])HandlerMethod.Invoke(CommandComponent, new object[] { command });
        if (selectables == null)
        {
            yield break;
        }
        yield return(null);

        yield return(selectables);
    }
コード例 #17
0
 private void CreateViewHandler(HandlerMethod method)
 {
     if (method == HandlerMethod.ADD_HANDLERS)
     {
         _currentAttachmentAdapter.EntrySelected           += AttachmentAdapter_EntrySelected;
         _currentAttachmentAdapter.AttachmentRetrieveError += AttachmentAdapter_AttachmentRetrieveError;
     }
     else
     {
         _currentAttachmentAdapter.EntrySelected           -= AttachmentAdapter_EntrySelected;
         _currentAttachmentAdapter.AttachmentRetrieveError -= AttachmentAdapter_AttachmentRetrieveError;
     }
 }
コード例 #18
0
            public async Task <IActionResult> Execute(Page page)
            {
                var handler = HandlerMethod.Create(Method);

                var arguments = new object[handler.Parameters.Length];

                for (var i = 0; i < handler.Parameters.Length; i++)
                {
                    var parameter = handler.Parameters[i];
                    arguments[i] = await page.Binder.BindModelAsync(page.PageContext, parameter.Type, parameter.DefaultValue, parameter.Name);
                }

                var result = await handler.Execute(page, arguments);

                return(result);
            }
コード例 #19
0
            public Handler(object handler, IEventAggregator eventAggregator, string filter)
            {
                _eventAggregator = eventAggregator;
                reference        = new WeakReference(handler, true);
                var interfaces = handler.GetType().GetInterfaces()
                                 .Where(x => typeof(IHandle).IsAssignableFrom(x) && x.IsGenericType());

                foreach (var @interface in interfaces)
                {
                    var type   = @interface.GetGenericArguments()[0];
                    var method = @interface.GetMethod("Handle", new[] { type });
                    //Debug.WriteLine("Added Reference: "+reference.Target.GetType().Name+" Type: "+type.Name);
                    if (method != null)
                    {
                        supportedHandlers[type] = new HandlerMethod(method, filter);
                    }
                }
            }
コード例 #20
0
            public async Task <IActionResult> Execute(Page page, object model)
            {
                var handler = HandlerMethod.Create(Method);

                var receiver = Method.DeclaringType.IsAssignableFrom(page.GetType()) ? page : model;

                var arguments = new object[handler.Parameters.Length];

                for (var i = 0; i < handler.Parameters.Length; i++)
                {
                    var parameter = handler.Parameters[i];
                    arguments[i] = await page.Binder.BindModelAsync(page.PageContext, parameter.Type, parameter.DefaultValue, parameter.Name);
                }

                var result = await handler.Execute(receiver, arguments);

                return(result);
            }
コード例 #21
0
        static void pMain()
        {
            //正常匹配:委托和方法一致
            HandlerMethod handler1 = FirstHandler;

            handler1();
            //协变:返回Dog值默认可以转换成Memmal
            HandlerMethod handler2 = SecondHandler;

            handler2();
            //正常匹配
            HandlerMethod1 handler3 = ThirdHandler;

            handler3(new Mammal());
            //逆变:参数Dog默认可以转换成Mammal(父类)
            HandlerMethod2 handler4 = ThirdHandler;

            handler4(new Dog());
            Console.ReadKey();
        }
コード例 #22
0
        protected virtual InvocableHandlerMethod GetExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception)
        {
            var beanType = handlerMethod.BeanType;

            _exceptionHandlerCache.TryGetValue(beanType, out var resolver);
            if (resolver == null)
            {
                resolver = CreateExceptionHandlerMethodResolverFor(beanType);
                _exceptionHandlerCache[beanType] = resolver;
            }

            var method = resolver.ResolveMethod(exception);

            if (method != null)
            {
                return(new InvocableHandlerMethod(handlerMethod.Bean, method));
            }

            return(null);
        }
コード例 #23
0
        private MulticastDelegate CreateHandlerDelegate()
        {
            // Required Handler Parameters:
            var paramTypes = new List <Type>
            {
                ConsumerType,
                QueryType
            };

            // Optional Handler Parameters:
            if (IsCancellable)
            {
                paramTypes.Add(typeof(CancellationToken));
            }

            paramTypes.Add(HandlerMethod.ReturnType);

            var dispatchType = Expression.GetDelegateType(paramTypes.ToArray());

            return((MulticastDelegate)HandlerMethod.CreateDelegate(dispatchType));
        }
コード例 #24
0
        /// <summary>
        ///     Information about a lambda function that can be invoked.
        /// </summary>
        /// <param name="name">
        ///     The name of the function.
        /// </param>
        /// <param name="functionType">
        ///     The lambda function type that will be activate.
        /// </param>
        /// <param name="handlerMethod">
        ///     The lambda function method that will be invoked.
        /// </param>
        /// <param name="reservedConcurrency">
        ///     The reserved concurrency.
        /// </param>
        public LambdaFunctionInfo(
            string name,
            Type functionType,
            string handlerMethod,
            int?reservedConcurrency = null)
        {
            Name = name;
            Type = functionType;

            HandlerMethod = functionType.GetMethod(handlerMethod, BindingFlags.Public | BindingFlags.Instance) !;

            // Search to see if a Lambda serializer is registered.
            var attribute = HandlerMethod.GetCustomAttribute(typeof(LambdaSerializerAttribute)) as LambdaSerializerAttribute ??
                            functionType.Assembly.GetCustomAttribute(typeof(LambdaSerializerAttribute)) as LambdaSerializerAttribute;

            if (attribute != null)
            {
                Serializer = (Activator.CreateInstance(attribute.SerializerType) as ILambdaSerializer) !;
            }

            ReservedConcurrency = reservedConcurrency;

            HandlerString = $"{functionType.Assembly.GetName().Name}::{functionType.FullName}::{handlerMethod}";
        }
コード例 #25
0
 public DefaultHandlerMethodInvoker(HandlerMethod method)
     : base(method)
 {
 }
コード例 #26
0
 public InvocableHandlerMethod(HandlerMethod handlerMethod)
     : base(handlerMethod)
 {
 }
コード例 #27
0
 public Match(T mapping, HandlerMethod handlerMethod)
 {
     Mapping       = mapping;
     HandlerMethod = handlerMethod;
 }
コード例 #28
0
 protected static Webhook BuildWebhook <T>(ActivityPayload payload) where T : ICanHandleGitHubWebhooks
 {
     return(new Webhook(HandlerMethod.GetUsableHandlerMethodsFrom(typeof(T)).First(), payload));
 }
コード例 #29
0
    public IEnumerator RespondToCommand(string userNickName, string cmdStr, bool isWhisper, IEnumerator processCommand = null)
    {
        if (HandlerMethod == null && processCommand == null)
        {
            IRCConnection.SendMessage("Sorry @{0}, this holdable is not supported by Twitch Plays.", userNickName, !isWhisper, userNickName);
            yield break;
        }

        _disableOnStrike     = false;
        Strike               = false;
        StrikeCount          = 0;
        _currentUserNickName = userNickName;

        FloatingHoldable.HoldStateEnum holdState = Holdable.HoldState;

        if (holdState != FloatingHoldable.HoldStateEnum.Held)
        {
            if (TwitchGame.BombActive)
            {
                BombCommands.Drop(TwitchGame.Instance.Bombs[TwitchGame.Instance._currentBomb == -1 ? 0 : TwitchGame.Instance._currentBomb]);
            }
            IEnumerator holdCoroutine = Hold();
            while (holdCoroutine.MoveNext() && !Strike)
            {
                yield return(holdCoroutine.Current);
            }
        }

        DebugHelper.Log("Running RespondToCommandInternal()");
        if (HandlerMethod != null && processCommand == null)
        {
            processCommand = MakeCoroutine(HandlerMethod.Invoke(CommandComponent, new object[] { cmdStr }));
        }

        bool cancelled  = false;
        bool parseError = false;
        bool cancelling = false;

        if (processCommand == null || !processCommand.MoveNext())
        {
            if (!Strike)
            {
                SendToChat(null, userNickName, isWhisper, ref parseError);
            }
        }
        else
        {
            ProcessIEnumerators.Push(processCommand);
            ProcessIEnumerators.Push(FirstItem(processCommand.Current));
        }

        do
        {
            try
            {
                bool result = false;
                while (!result && !Strike)
                {
                    if (ProcessIEnumerators.Count > 0)
                    {
                        processCommand = ProcessIEnumerators.Pop();
                        result         = processCommand.MoveNext();
                        if (result)
                        {
                            ProcessIEnumerators.Push(processCommand);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                if (Strike)
                {
                    DebugHelper.Log("A strike was caused by the command. Invocation will not continue.");
                }
                if (!result || Strike)
                {
                    break;
                }
            }
            catch (Exception ex)
            {
                DebugHelper.LogException(ex, "Error processing command due to an exception. Invocation will not continue.:");
                break;
            }

            switch (processCommand.Current)
            {
            case IEnumerator iEnumerator:
                if (iEnumerator != null)
                {
                    ProcessIEnumerators.Push(iEnumerator);
                }
                continue;

            case KMSelectable kmSelectable when kmSelectable != null:
                if (HeldSelectables.Contains(kmSelectable))
                {
                    DoInteractionEnd(kmSelectable);
                    HeldSelectables.Remove(kmSelectable);
                }
                else
                {
                    DoInteractionStart(kmSelectable);
                    HeldSelectables.Add(kmSelectable);
                }
                break;

            case KMSelectable[] kmSelectables:
                foreach (KMSelectable selectable in kmSelectables)
                {
                    if (selectable != null)
                    {
                        yield return(DoInteractionClick(selectable));

                        if (Strike)
                        {
                            break;
                        }
                    }
                    else
                    {
                        yield return(new WaitForSeconds(0.1f));
                    }
                }

                break;

            case Quaternion quaternion:
                RotateByLocalQuaternion(quaternion);
                break;

            case string currentString when !string.IsNullOrEmpty(currentString):
                if (currentString.Equals("trycancel", StringComparison.InvariantCultureIgnoreCase) &&
                    CoroutineCanceller.ShouldCancel)
                {
                    CoroutineCanceller.ResetCancel();
                    cancelled = true;
                }
                else if (currentString.ToLowerInvariant().EqualsAny("elevator music", "hold music", "waiting music"))
                {
                    if (_musicPlayer == null)
                    {
                        _musicPlayer = MusicPlayer.StartRandomMusic();
                    }
                }
                else if (currentString.EqualsIgnoreCase("cancelled") && cancelling)
                {
                    CancelBool?.SetValue(CommandComponent, false);
                    CoroutineCanceller.ResetCancel();
                    cancelled = true;
                }
                else if (currentString.StartsWith("strikemessage ",
                                                  StringComparison.InvariantCultureIgnoreCase) &&
                         !string.IsNullOrEmpty(currentString.Substring(14).Trim()))
                {
                    StrikeMessage = currentString.Substring(14);
                }
                else if (currentString.Equals("strike", StringComparison.InvariantCultureIgnoreCase))
                {
                    _delegatedStrikeUserNickName = _currentUserNickName;
                }
                else if (currentString.Equals("multiple strikes", StringComparison.InvariantCultureIgnoreCase))
                {
                    _disableOnStrike = true;
                }
                else if (currentString.ToLowerInvariant().EqualsAny("detonate", "explode") && TwitchGame.BombActive)
                {
                    var bomb = TwitchGame.Instance.Bombs[0];
                    AwardStrikes(_currentUserNickName, bomb.StrikeLimit - bomb.StrikeCount);
                    bomb.CauseExplosionByModuleCommand(string.Empty,
                                                       ID);
                    Strike = true;
                }
                else if (currentString.EqualsIgnoreCase("show front"))
                {
                    ProcessIEnumerators.Push(Hold());
                }
                else if (currentString.EqualsIgnoreCase("show back"))
                {
                    ProcessIEnumerators.Push(Hold(false));
                }
                else
                {
                    SendToChat(currentString, userNickName, isWhisper, ref parseError);
                }

                break;

            case string[] currentStrings:
                if (currentStrings.Length >= 1)
                {
                    if (currentStrings[0].ToLowerInvariant().EqualsAny("detonate", "explode") &&
                        TwitchGame.BombActive)
                    {
                        TwitchBomb bombs = TwitchGame.Instance.Bombs[0];
                        AwardStrikes(_currentUserNickName, bombs.StrikeLimit - bombs.StrikeCount);
                        switch (currentStrings.Length)
                        {
                        case 2:
                            bombs.CauseExplosionByModuleCommand(currentStrings[1], ID);
                            break;

                        case 3:
                            bombs.CauseExplosionByModuleCommand(currentStrings[1], currentStrings[2]);
                            break;

                        default:
                            bombs.CauseExplosionByModuleCommand(string.Empty, ID);
                            break;
                        }
                    }
                }

                break;

            case Dictionary <string, bool> permissions:
                foreach (KeyValuePair <string, bool> pair in permissions)
                {
                    if (TwitchPlaySettings.data.ModPermissions.ContainsKey(pair.Key))
                    {
                        continue;
                    }
                    TwitchPlaySettings.data.ModPermissions.Add(pair.Key, pair.Value);
                    TwitchPlaySettings.WriteDataToFile();
                }
                break;

            case KMMission mission:
                TwitchPlaysService.Instance.RunMission(mission);
                break;

            case object[] objects:
                if (objects == null)
                {
                    break;
                }
                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (objects.Length)
                {
                case 3 when objects[0] is string objstr:
                    if (IsAskingPermission(objstr, userNickName, out bool permissionGranted))
                    {
                        if (permissionGranted)
                        {
                            switch (objects[1])
                            {
                            case Action actionTrue:
                                actionTrue.Invoke();
                                break;

                            case IEnumerator iEnumerator when iEnumerator != null:
                                ProcessIEnumerators.Push(iEnumerator);
                                yield return(null);

                                continue;
                            }
                        }
                        else
                        {
                            switch (objects[2])
                            {
                            case Action actionFalse:
                                actionFalse.Invoke();
                                break;

                            case string objStr2 when !string.IsNullOrEmpty(objStr2):
                                SendToChat(objStr2, userNickName, isWhisper, ref parseError);
                                break;

                            case IEnumerator iEnumerator when iEnumerator != null:
                                ProcessIEnumerators.Push(iEnumerator);
                                yield return(null);

                                continue;
                            }
                        }
                    }
                    break;
                }
                break;
            }
コード例 #30
0
 public override int GetHashCode()
 => HandlerMethod.ToString().GetHashCode();