예제 #1
0
 public static void Raise <TSender, TArgs>(this CustomEventHandler <TSender, TArgs> eventHandler, TSender sender, TArgs args)
 {
     if (eventHandler != null)
     {
         eventHandler(sender, args);
     }
 }
        private async void SendRequest(Uri url, EventHandler successEvent, CustomEventHandler <string> errorEvent)
        {
            var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            webRequest.Method      = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(_request));

            byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);

            // Write the channel URI to the request stream.
            Stream requestStream = await webRequest.GetRequestStreamAsync();

            requestStream.Write(requestBytes, 0, requestBytes.Length);

            try
            {
                // Get the response from the server.
                WebResponse response = await webRequest.GetResponseAsync();

                StreamReader requestReader = new StreamReader(response.GetResponseStream());
                String       webResponse   = requestReader.ReadToEnd();

                string errorMessage = String.Empty;

                Debug.WriteLine("Response: " + webResponse);

                JObject jRoot = JObject.Parse(webResponse);
                int     code  = JsonHelpers.GetStatusCode(jRoot);
                if (code == 200 || code == 103)
                {
                    if (successEvent != null)
                    {
                        successEvent(this, null);
                    }
                }
                else
                {
                    errorMessage = JsonHelpers.GetStatusMessage(jRoot);
                }

                if (!String.IsNullOrEmpty(errorMessage) && errorEvent != null)
                {
                    Debug.WriteLine("Error: " + errorMessage);
                    errorEvent(this, new CustomEventArgs <string> {
                        Result = errorMessage
                    });
                }
            }

            catch (Exception ex)
            {
                var errorMessage = ex.Message;
                Debug.WriteLine("Error: " + errorMessage);
                errorEvent(this, new CustomEventArgs <string> {
                    Result = errorMessage
                });
            }
        }
        }  //RaiseCustomEvent

        protected virtual void RaiseDivBy2Event(CustomEventArgs e)
        {
            CustomEventHandler handler = DivBy2EventHandler;
            if (handler != null)
            {
                handler(this, e);
            }
        }  //RaiseDivBy2Event
예제 #4
0
        public static void RemoveEventListener(string _eventType, CustomEventHandler _listener)
        {
            CustomEventWrapper eWrapper = null;

            if (events.TryGetValue(_eventType, out eWrapper))
            {
                eWrapper.OnHandler -= _listener;
            }
        }
예제 #5
0
        private void OnRaiseCustomEvent(CustomEventArgs eventArgs)
        {
            CustomEventHandler raiseEvent = RaiseCustomEvent;

            if (raiseEvent != null)
            {
                raiseEvent(this, eventArgs);
            }
        }
예제 #6
0
 public override void PrepareForReuse()
 {
     base.PrepareForReuse();
     if (HandlerForButton != null)
     {
         EditButton.TouchUpInside -= ButtonPressed;
     }
     HandlerForButton = null;
 }
예제 #7
0
        protected virtual void OnRaiseCustomEvent(SomeEvent e)
        {
            CustomEventHandler handler = RaiseCustomEvent;

            if (handler != null)
            {
                e.Message += String.Format(" at {0}", DateTime.Now);
                handler(this, e);
            }
        }
예제 #8
0
파일: Program.cs 프로젝트: It672/Find-max
        static void Main(string[] args)
        {
            _show += new CustomEventHandler(Dog);
            _show += new CustomEventHandler(Cat);
            _show += new CustomEventHandler(Mouse);
            _show += new CustomEventHandler(Mouse);

            _show -= new CustomEventHandler(Cat);
            _show.Invoke();
        }
예제 #9
0
    public bool Unsubscribe(CustomEventHandler handler, string channelName = DefaultChannel)
    {
        bool result = (Channels.ContainsKey(channelName));

        if (result)
        {
            Channels [channelName] -= handler;
        }
        return(result);
    }
예제 #10
0
 public void RemoveListener(int eventId, CustomEventHandler eventHandlerDele)
 {
     if (id2DeleDict.TryGetValue(eventId, out CustomEventHandler oldDele))
     {
         oldDele -= eventHandlerDele;
         if (oldDele == null)
         {
             id2DeleDict.Remove(eventId);
         }
     }
 }
        private async void SendRequest(Uri url, EventHandler successEvent, CustomEventHandler<string> errorEvent)
        {
            var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(_request));

            byte[] requestBytes = System.Text.Encoding.UTF8.GetBytes(request);

			try
			{
				// Write the channel URI to the request stream.
				Stream requestStream = await webRequest.GetRequestStreamAsync();
				requestStream.Write(requestBytes, 0, requestBytes.Length);

                // Get the response from the server.
                WebResponse response = await webRequest.GetResponseAsync();
                StreamReader requestReader = new StreamReader(response.GetResponseStream());
                String webResponse = requestReader.ReadToEnd();

                string errorMessage = String.Empty;

                Debug.WriteLine("Response: " + webResponse);

                JObject jRoot = JObject.Parse(webResponse);
                int code = JsonHelpers.GetStatusCode(jRoot);
                if (code == 200 || code == 103)
                {
                    if (successEvent != null)
                    {
                        successEvent(this, null);
                    }
                }
                else
                    errorMessage = JsonHelpers.GetStatusMessage(jRoot);

                if (!String.IsNullOrEmpty(errorMessage) && errorEvent != null)
                {
                    Debug.WriteLine("Error: " + errorMessage);
                    errorEvent(this, new CustomEventArgs<string> { Result = errorMessage });
                }
            }

            catch (Exception ex)
            {
                var errorMessage = ex.Message;
                Debug.WriteLine("Error: " + errorMessage);
				if(errorEvent != null)
				{
					errorEvent(this, new CustomEventArgs<string> { Result = errorMessage });
				}
            }
        }
예제 #12
0
        protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
        {
            CustomEventHandler handler = RaiseCustomEvent;

            if (handler != null)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Current monster hp is {0}", e.HP);
                Console.ResetColor();
                handler(this, e);
            }
        }
예제 #13
0
        /// <summary>
        /// Lisää vapaamuotoisen tapahtumankäsittelijän.
        /// </summary>
        /// <param name="condition">Ehto josta tapahtuma laukeaa.</param>
        /// <param name="handler">Kutsuttava funktio.</param>
        public CustomEventHandler AddCustomHandler(Func <bool> condition, Action handler)
        {
            if (handlers == null)
            {
                handlers = new SynchronousList <CustomEventHandler>();
            }

            var handlerObj = new CustomEventHandler(condition, handler);

            handlers.Add(handlerObj);
            return(handlerObj);
        }
        }  //Count

        // Wrap event invocations inside a protected virtual method to allow derived classes to override the invocation behavior
        protected virtual void RaiseGeneralEvent(CustomEventArgs e)
        {
            // Use a copy of the event, to avoid a race condition if the last subscriber unsubscribes between null check and raise.
            CustomEventHandler handler = GeneralEventHandler;

            // Event will be null if there are no subscribers
            if (handler != null)
            {
                // Here you can add a bit to the message before publishing it
                e.Message += String.Format(" at {0}", DateTime.Now.ToString());

                // Raise the event!
                handler(this, e);
            }
        }  //RaiseCustomEvent
예제 #15
0
 public void AddListener(int eventId, CustomEventHandler eventHandleDele)
 {
     if (id2DeleDict.TryGetValue(eventId, out CustomEventHandler eventDele))
     {
         Delegate[] delegates = eventHandleDele.GetInvocationList();
         if (Array.IndexOf(delegates, eventHandleDele) == -1)
         {
             eventDele += eventHandleDele;
         }
     }
     else
     {
         id2DeleDict.Add(eventId, eventHandleDele);
     }
 }
예제 #16
0
        public static void AddEventListener(string _eventType, CustomEventHandler _listener)
        {
            CustomEventWrapper eWrapper = null;

            if (!events.TryGetValue(_eventType, out eWrapper))
            {
                eWrapper            = new CustomEventWrapper();
                eWrapper.OnHandler += _listener;
                events.Add(_eventType, eWrapper);
            }
            else
            {
                eWrapper.OnHandler += _listener;
            }
        }
예제 #17
0
 // 主线程循环
 internal static void MainThreadUpdate()
 {
     FocusEventHandler.MainThreadUpdate();
     ScreenResizeEventHandler.MainThreadUpdate();
     CollisionEventHandler.MainThreadUpdate();
     TriggerEventHandler.MainThreadUpdate();
     PointerEventHandlerForScreen.MainThreadUpdate();
     PointerEventHandlerForUI.MainThreadUpdate();
     PointerEventHandlerForMesh.MainThreadUpdate();
     KeyboardEventHandler.MainThreadUpdate();
     FrameLoopEventHandler.MainThreadUpdate();
     IntervalEventHandler.MainThreadUpdate();
     CustomEventHandler.MainThreadUpdate();
     TraceEventHandler.MainThreadUpdate();
 }
예제 #18
0
파일: World.cs 프로젝트: ndech/Alpha
 public void SetNewRealmHandler(CustomEventHandler <RealmToken> function)
 {
     if (!_tokenAcquired)
     {
         NewRealm      += function;
         _tokenAcquired = true;
     }
     else
     {
         throw new InvalidOperationException("The NewRealm handler has already been acquired.");
     }
     foreach (Realm realm in RealmManager.Realms)
     {
         NewRealm.Invoke(new RealmToken(realm));
     }
 }
예제 #19
0
            // Wrap event invocations inside a protected virtual method
            // to allow derived classes to override the event invocation behavior
            protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
            {
                // Make a temporary copy of the event to avoid possibility of
                // a race condition if the last subscriber unsubscribes
                // immediately after the null check and before the event is raised.
                CustomEventHandler handler = raiseCustomEvent;

                // Event will be null if there are no subscribers
                if (handler != null)
                {
                    // Format the string to send inside the CustomEventArgs parameter
                    e.Message += String.Format(" at {0}", DateTime.Now.ToString());

                    // Use the () operator to raise the event.
                    handler(this, e);  //this will call the function of Subscriber.HandleCustomEvent(object sender,CustomoEventArgs e)
                }
            }
        private void SendRequest(Uri url, EventHandler successEvent, CustomEventHandler <string> errorEvent)
        {
            var webClient = new WebClient();

            webClient.UploadStringCompleted += (sender, args) =>
            {
                string errorMessage = String.Empty;

                if (args.Error != null)
                {
                    errorMessage = args.Error.Message;
                }
                else
                {
                    Debug.WriteLine("Response: " + args.Result);

                    JObject jRoot = JObject.Parse(args.Result);
                    int     code  = JsonHelpers.GetStatusCode(jRoot);
                    if (code == 200 || code == 103)
                    {
                        if (successEvent != null)
                        {
                            successEvent(this, null);
                        }
                    }
                    else
                    {
                        errorMessage = JsonHelpers.GetStatusMessage(jRoot);
                    }
                }

                if (!String.IsNullOrEmpty(errorMessage) && errorEvent != null)
                {
                    Debug.WriteLine("Error: " + errorMessage);
                    errorEvent(this, new CustomEventArgs <string> {
                        Result = errorMessage
                    });
                }
            };

            string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(_request));

            Debug.WriteLine("Sending request: " + request);

            webClient.UploadStringAsync(url, request);
        }
예제 #21
0
        /// <summary>
        /// 基本驱动事件 示例
        /// 注册,触发,注销
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public JsonResult DoEvent([FromBody] CacheParam param)
        {
            //触发事件
            _eventBus.Trigger(this, new CustomEventData {
                CacheParamModel = param
            });

            #region 还可以通过注册来实现
            CustomEventHandler customEventHandler = new CustomEventHandler();
            //注册
            _eventBus.Register <CustomEventData>(customEventHandler.SetHandleEvent);
            //触发事件
            _eventBus.Trigger(this, new CustomEventData {
                CacheParamModel = param
            });
            //注销
            _eventBus.Unregister <CustomEventData>(customEventHandler.SetHandleEvent);
            #endregion
            return(Json(param));
        }
        private void initSDK()
        {
            // 初始化短信SDK
            SMSSDK.InitSDK(this, APPKEY, APPSECRET, true);
            if (APPKEY.Equals("f3fc6baa9ac4", StringComparison.InvariantCultureIgnoreCase))
            {
                Toast.MakeText(this, "此APPKEY仅供测试使用,且不定期失效,请到mob.com后台申请正式APPKEY", ToastLength.Short).Show();
            }

            var eventHandler = new CustomEventHandler(new Handler(this));

            // 注册回调监听接口
            SMSSDK.RegisterEventHandler(eventHandler);
            ready = true;

            // 获取新好友个数
            showDialog();
            SMSSDK.GetNewFriendsCount();
            gettingFriends = true;
        }
예제 #23
0
파일: Program.cs 프로젝트: dealen/70-483
        public static void EventsCalls()
        {
            IRun run = new EventsBasics();

            run.Run();

            IRun evt = new CustomEventHandler();

            evt.Run();

            IRun custom = new CustomEventAccess();

            custom.Run();

            IRun exp = new EventsWithExceptions();

            exp.Run();

            IRun eh = new EventsWithExceptionhandling();

            eh.Run();
        }
예제 #24
0
        public void AddEvents()
        {
            CustomEvent += new CustomEventHandler <EventArgs>((o, a) =>
            {
                Console.WriteLine("new CustomEventHandler((o, a) => {})");
            });

            CustomEvent += (o, a) =>
            {
                Console.WriteLine("Anonimous (o, a) => {}");
            };

            CustomEvent += EventHandlerDefault;

            CustomEvent += EventHandlerDefaultStatic;             // Use static when add evenhandler in static context

            // Weak Event Pattern Implementation
            WeakEventManager <WeakEventPatternExample, EventArgs> .AddHandler(this, nameof(CustomEventForWeak), (o, a) =>
            {
                Console.WriteLine("WeakEventManager<WeakEventPatternExample, EventArgs>.AddHandler(example, nameof(CustomEventForWeak), (o, a) =>{}");
            });
        }
예제 #25
0
        private void SendRequest(Uri url, EventHandler successEvent, CustomEventHandler<string> errorEvent)
        {
            var webClient = new WebClient();
            webClient.UploadStringCompleted += (sender, args) =>
                                                   {
                                                       string errorMessage = String.Empty;

                                                       if (args.Error != null)
                                                           errorMessage = args.Error.Message;
                                                       else
                                                       {
                                                           Debug.WriteLine("Response: " + args.Result);

                                                           JObject jRoot = JObject.Parse(args.Result);
                                                           int code = JsonHelpers.GetStatusCode(jRoot);
                                                           if (code == 200 || code == 103)
                                                           {
                                                               if (successEvent != null)
                                                               {
                                                                   successEvent(this, null);
                                                               }
                                                           }
                                                           else
                                                               errorMessage = JsonHelpers.GetStatusMessage(jRoot);
                                                       }

                                                       if (!String.IsNullOrEmpty(errorMessage) && errorEvent != null)
                                                       {
                                                           Debug.WriteLine("Error: " + errorMessage);
                                                           errorEvent(this, new CustomEventArgs<string> {Result = errorMessage});
                                                       }
                                                   };

            string request = String.Format("{{ \"request\":{0}}}", JsonConvert.SerializeObject(_request));
            Debug.WriteLine("Sending request: " + request);

            webClient.UploadStringAsync(url, request);
        }
예제 #26
0
    /// <summary>
    /// Subscribe the specified handler and channelName.
    ///
    /// This can be improved by having custom option like subscribe only to action event or notification event,
    /// so that other ends don't need to do any checking (like type == action those boring stuffs)
    /// </summary>
    /// <param name="handler">Handler.</param>
    /// <param name="channelName">Channel name.</param>
    public bool Subscribe(CustomEventHandler handler, string channelName = DefaultChannel, bool createIfNotExist = false)
    {
        if (createIfNotExist)
        {
            bool result = (Channels.ContainsKey(channelName));
            if (result)
            {
                Channels [channelName] += handler;
            }
            return(result);
        }
        else
        {
            bool result = (Channels.ContainsKey(channelName));
            if (result == false)
            {
                CreateChannel(channelName);
            }
            Channels [channelName] += handler;

            return(true);
        }
    }
예제 #27
0
        public async Task CanPublishUsingInMemoryBus()
        {
            //arrange
            var eventHandlerFactory = new DefaultEventHandlerFactory();
            var eventBus            = new InMemoryEventBus(eventHandlerFactory);
            var eventPublisher      = new EventPublisher(eventBus);
            var eventHandler        = new CustomEventHandler();

            eventHandlerFactory.RegisterHandler(eventHandler);

            var evt = new CustomEvent("Test message");

            //act
            await eventPublisher.PublishAsync(evt).ConfigureAwait(false);

            //Wait for events to propagate/tasks to finish
            await Task.Delay(100).ConfigureAwait(false);

            //assert
            Assert.Single(eventHandler.Events);
            Assert.Equal(evt.Id, eventHandler.Events[0].Id);
            Assert.Equal(evt.EventId, eventHandler.Events[0].EventId);
            Assert.Equal(evt.Message, eventHandler.Events[0].Message);
        }
예제 #28
0
 internal void GetCell(int position, CustomEventHandler handler)
 {
     HandlerForButton          = handler;
     EditButton.TouchUpInside += ButtonPressed;
 }
예제 #29
0
파일: World.cs 프로젝트: ndech/Alpha
 public void SetNewRealmHandler(CustomEventHandler<RealmToken> function )
 {
     if (!_tokenAcquired)
     {
         NewRealm += function;
         _tokenAcquired = true;
     }
     else
         throw new InvalidOperationException("The NewRealm handler has already been acquired.");
     foreach (Realm realm in RealmManager.Realms)
         NewRealm.Invoke(new RealmToken(realm));
 }
예제 #30
0
 public IconButton(IContext context, string id, CustomEventHandler action)
     : this(context, id)
 {
     Clicked += action;
 }
예제 #31
0
파일: TextInput.cs 프로젝트: ndech/Alpha
 protected override void DisposeItem()
 {
     _text.Dispose();
     _plainRectangle.Dispose();
     OnSubmit = null;
 }
예제 #32
0
    /// <summary>
    /// Fixed update because I do not want to be dependant on frame-rate.
    /// Every tick, we do the following
    /// if height > -100
    ///     1: For each block in children
    ///             Find velocity, and raycast from it to the block.
    ///             if the block is hit (i.e. nothing was in the way)
    ///                 find the velocity in the axis perpendicular to the normal hit.
    ///                 calculate the drag of that velocity
    ///                 apply that force opposite the normal
    ///     2: For each block in thrusters
    ///             If fuel amount > 0
    ///                 add force to facing = fuelForce;
    ///                 fuel amount -= fuel burn
    ///    height = max(height, transform.position)
    /// else
    ///     set individuals height to our maxheight
    ///     kill this script
    /// </summary>
    public void FixedUpdate()
    {
        if (this.Equals(null))
        {
            return;
        }
        if (transform.position.y > -50)
        {
            foreach (GameObject body in children)
            {
                Vector3    v = me.GetRelativePointVelocity(body.transform.position);
                RaycastHit hit;
                ///if we hit something (pretty much impossible not to)
                if (Physics.Raycast(v * 30, -v, out hit))
                {
                    ///Calculating the force of drag on the collider
                    Vector3 norm  = hit.normal;
                    float   theta = Vector3.Angle(norm, v);
                    Vector3 dragV = v * (Mathf.Cos(theta));
                    dragV *= dragV.magnitude;
                    Vector3 oppForce = -dragV / 2;

                    ///Applying that force opposite to the normal
                    me.AddForceAtPosition(oppForce, body.transform.position);
                }
            }
            ///For each thruster, we add a force
            foreach (GameObject body in thruster)
            {
                if (fuelAmount > 0)
                {
                    PropelThruster(body);
                    fuelAmount -= fuelBurn;
                }
            }
            maxheight = Mathf.Max(transform.position.y, maxheight);
            if (this.Equals(null))
            {
                return;
            }
            if (myParent.Equals(null))
            {
                return;
            }
            myParent.timeInAir += 1;
        }
        ///If we're done, we signal to kill ourselves to the event handler
        else
        {
            if (this.Equals(null))
            {
                return;
            }
            if (myParent.Equals(null))
            {
                return;
            }
            myParent.maxHeight = maxheight;
            IndividualFunctions.ScoreIndividual(myParent);
            CustomEventHandler.SelfDestruct(this.gameObject);
        }
    }
예제 #33
0
파일: IconButton.cs 프로젝트: ndech/Alpha
 public IconButton(IContext context, string id, CustomEventHandler action)
     : this(context, id)
 {
     Clicked += action;
 }
예제 #34
0
 public void Unsubscribe(CustomEventHandler handler)
 {
     m_delegate -= handler;
 }