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
public static void RemoveEventListener(string _eventType, CustomEventHandler _listener) { CustomEventWrapper eWrapper = null; if (events.TryGetValue(_eventType, out eWrapper)) { eWrapper.OnHandler -= _listener; } }
private void OnRaiseCustomEvent(CustomEventArgs eventArgs) { CustomEventHandler raiseEvent = RaiseCustomEvent; if (raiseEvent != null) { raiseEvent(this, eventArgs); } }
public override void PrepareForReuse() { base.PrepareForReuse(); if (HandlerForButton != null) { EditButton.TouchUpInside -= ButtonPressed; } HandlerForButton = null; }
protected virtual void OnRaiseCustomEvent(SomeEvent e) { CustomEventHandler handler = RaiseCustomEvent; if (handler != null) { e.Message += String.Format(" at {0}", DateTime.Now); handler(this, e); } }
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(); }
public bool Unsubscribe(CustomEventHandler handler, string channelName = DefaultChannel) { bool result = (Channels.ContainsKey(channelName)); if (result) { Channels [channelName] -= handler; } return(result); }
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 }); } } }
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); } }
/// <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
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); } }
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; } }
// 主线程循环 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(); }
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)); } }
// 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); }
/// <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; }
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(); }
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) =>{}"); }); }
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); }
/// <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); } }
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); }
internal void GetCell(int position, CustomEventHandler handler) { HandlerForButton = handler; EditButton.TouchUpInside += ButtonPressed; }
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)); }
public IconButton(IContext context, string id, CustomEventHandler action) : this(context, id) { Clicked += action; }
protected override void DisposeItem() { _text.Dispose(); _plainRectangle.Dispose(); OnSubmit = null; }
/// <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); } }
public IconButton(IContext context, string id, CustomEventHandler action) : this(context, id) { Clicked += action; }
public void Unsubscribe(CustomEventHandler handler) { m_delegate -= handler; }