public static void HandlingEvent(ILogger <Renderer> logger, ulong eventHandlerId, EventArgs?eventArgs) { if (logger.IsEnabled(LogLevel.Debug)) // This is almost always false, so skip the evaluations { HandlingEvent(logger, eventHandlerId, eventArgs?.GetType().Name ?? "null"); } }
public bool runTest() { Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; String strValue = String.Empty; try { EventArgs ea = new EventArgs(); iCountTestcases++; if(ea == null) { iCountErrors++; printerr( "Error_987ya! EventArgs not constructed"); } iCountTestcases++; if(!ea.GetType().FullName.Equals("System.EventArgs")) { iCountErrors++; printerr("Error_498cy! Incorrect type"); } iCountTestcases++; } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
private static void GetMessageHeaders(EventArgs?eventArgs, out ServiceRemotingRequestEventArgs?requestEventArgs, out IServiceRemotingRequestMessageHeader?messageHeaders) { requestEventArgs = eventArgs as ServiceRemotingRequestEventArgs; try { if (requestEventArgs == null) { Log.Warning("Unexpected EventArgs type: {0}", eventArgs?.GetType().FullName ?? "null"); } messageHeaders = requestEventArgs?.Request?.GetHeader(); if (messageHeaders == null) { Log.Warning("Cannot access request headers."); } } catch (Exception ex) { Log.Error(ex, "Error accessing request headers."); messageHeaders = null; } }
private void AlertUser_ExecuteCode(object sender, EventArgs e) { Console.WriteLine(e.GetType().ToString()); Console.WriteLine("Sending Alert to " + this.AssignedTo); }
/// <summary> /// Test event handler for <see cref="_testHumanPlayer"/> /// </summary> /// <param name="sender">Event source</param> /// <param name="e">Event data</param> private void HumanPlayer_Round(object sender, EventArgs e) { Console.WriteLine("Handler HumanPlayer_Round() running."); Assert.AreEqual(typeof(RoundEventArgs), e.GetType()); Assert.AreEqual(_testHumanPlayer.Id, ((RoundEventArgs)e).PlayerId); }
private void buttonTransmit_Click(object sender, EventArgs e) { System.Runtime.GCSettings.LatencyMode = GCLatencyMode.LowLatency; if (activitiesTempStorage == null) { MessageBox.Show("There's nothing to transmit"); return; } DisableFilterBox(); DisableButtons(); var sync = SynchronizationContext.Current; if (!this.sender.Authorized && e.GetType() != typeof(LoginPasswordEventArgs)) { Task.Factory.StartNew(() => { LoginWithForm(sync); }); return; } string login = string.Empty, password = string.Empty; if (!this.sender.Authorized) { login = (e as LoginPasswordEventArgs).Login; password = (e as LoginPasswordEventArgs).Password; if (login == string.Empty || password == string.Empty) { EnableButtons(); EnableFilterBox(); return; } } Task authorizationTask = new Task(() => { if (!this.sender.Authorized) // after first 'if' data was obtained as EventArgs { HttpStatusCode authorizationStatusCode; bool success; try { success = this.sender.Authorize(login, password, out authorizationStatusCode); } catch (WebException ex) { MessageBox.Show($"An error occured while authorization\n{ex.Message}"); return; } if (!success) { int authCode = (int)authorizationStatusCode; MessageBox.Show($"Authorization failed. Code {authCode}: {authorizationStatusCode}"); EnableButtonsFromAnotherTask(sync); EnableFilterBoxFromAnotherTask(sync); } } }); authorizationTask.Start(); authorizationTask.Wait(); if (!this.sender.Authorized) { return; } Task <List <Report> > splittingActivitiesListTask = new Task <List <Report> >(() => { List <Report> r = new List <Report>(); while (activitiesTempStorage.Count > 0) { var a = activitiesTempStorage.Take(activitiesToSendAtOneTime).ToList(); r.Add(new Report() { Activities = a }); activitiesTempStorage.RemoveRange(0, a.Count); } return(r); }); splittingActivitiesListTask.Start(); List <Report> reports = splittingActivitiesListTask.Result; var tokenSource = new CancellationTokenSource(); var cancellation = tokenSource.Token; SendingProgressForm sendingProgressForm = ShowProgressForm(sync, reports.Count, tokenSource); Task sendingTask = new Task((token) => { CancellationToken cancellationToken = (CancellationToken)token; while (reports.Any()) { cancellationToken.ThrowIfCancellationRequested(); var report = reports.First(); HttpStatusCode sendStatusCode; string result; try { result = this.sender.SendActivities(report, out sendStatusCode); } catch (Exception ex) { MessageBox.Show($"An error occured while sending activities\n{ex.Message}"); return; } int code = (int)sendStatusCode; if (sendStatusCode == HttpStatusCode.Created) { reports.Remove(report); IncrementProgress(sync, sendingProgressForm); } } processor.MarkRegistriesAsProcessed(activitiesTempStorage.RegistriesIds); }, cancellation, TaskCreationOptions.LongRunning); Task continuation = sendingTask.ContinueWith((obj) => { if (cancellation.IsCancellationRequested) { StopProgressOnCancel(sync, sendingProgressForm); } else { CompleteProgress(sync, sendingProgressForm); } activitiesTempStorage = null; EnableFilterBoxFromAnotherTask(sync); EnableButtonsFromAnotherTask(sync); ClearDataFromAnotherTask(sync); }); sendingTask.Start(); }
protected void btnSave_Click(object sender, EventArgs e) { try { Session.Timeout = int.Parse(txtSessionTimeOut.Text); } catch(Exception ex) { Session["ModuleName"] = " 系统信息参数设置"; Session["FunctionName"] = "btnSave_Click"; Session["ExceptionalType"] = e.GetType().FullName; Session["ExceptionalDescription"] = ex.Message; Response.Redirect("~/Common/MistakesPage.aspx"); } SaveData(); //新的保存方法 }
public override void Application_Start(object sender, EventArgs e) { base.Application_Start(sender, e); //execute the initializer method. ApplicationInitialization.Execute(); #region mono #if MONO Kooboo.HealthMonitoring.Log.Logger = (exception) => { string msgFormat = @" Event message: {0} Event time: {1} Event time {2} Exception information: Exception type: {3} Exception message: {0} Request information: Request URL: {4} User host address: {5} User: {6} Is authenticated: {7} Thread information: Thread ID: {8} Stack trace: {9} "; string[] args = new string[13]; args[0] = exception.Message; args[1] = DateTime.Now.ToString(System.Globalization.CultureInfo.InstalledUICulture); args[2] = DateTime.UtcNow.ToString(System.Globalization.CultureInfo.InstalledUICulture); args[3] = e.GetType().ToString(); if (System.Web.HttpContext.Current != null) { var request = HttpContext.Current.Request; args[4] = request.RawUrl; args[5] = request.UserHostAddress; args[6] = HttpContext.Current.User.Identity.Name; args[7] = HttpContext.Current.User.Identity.IsAuthenticated.ToString(); } args[8] = System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(); args[9] = exception.StackTrace; Kooboo.CMS.Web.HealthMonitoring.TextFileLogger.Log(string.Format(msgFormat, args)); }; #endif #endregion // ControllerBuilder.Current.SetControllerFactory(new Kooboo.CMS.Sites.CMSControllerFactory()); #region MVC Inject DependencyResolver.SetResolver(new Kooboo.CMS.Common.DependencyResolver(EngineContext.Current, DependencyResolver.Current)); #endregion //ViewEngine for module. ViewEngines.Engines.Insert(0, new Kooboo.CMS.Sites.Extension.ModuleArea.ModuleRazorViewEngine()); ViewEngines.Engines.Insert(1, new Kooboo.CMS.Sites.Extension.ModuleArea.ModuleWebFormViewEngine()); ViewEngines.Engines.Insert(2, new CustomRazorViewEngine()); AreaRegistration.RegisterAllAreas(); #region Binders ModelBinders.Binders.DefaultBinder = new JsonModelBinder(); ModelBinders.Binders.Add(typeof(DynamicDictionary), new DynamicDictionaryBinder()); ModelBinders.Binders.Add(typeof(Kooboo.CMS.Sites.DataRule.IDataRule), new Kooboo.CMS.Web.Areas.Sites.ModelBinders.DataRuleBinder()); ModelBinders.Binders.Add(typeof(Kooboo.CMS.Sites.DataRule.DataRuleBase), new Kooboo.CMS.Web.Areas.Sites.ModelBinders.DataRuleBinder()); ModelBinders.Binders.Add(typeof(Kooboo.CMS.Sites.Models.PagePosition), new Kooboo.CMS.Web.Areas.Sites.ModelBinders.PagePositionBinder()); ModelBinders.Binders.Add(typeof(Kooboo.CMS.Sites.Models.Parameter), new Kooboo.CMS.Web.Areas.Sites.ModelBinders.ParameterBinder()); #endregion RegisterRoutes(RouteTable.Routes); Kooboo.CMS.Content.Persistence.Providers.RepositoryProvider.TestDbConnection(); }
protected void OnHscale1ValueChanged(object sender, EventArgs e) { sender.ToString(); Console.WriteLine("Slider changed " + e.GetType()); }
public void RaiseEvent(EventArgs args) { Registractions[args.GetType()].RaiseEvent(args); }
public static void Client_ConnectionClosed(object sender, EventArgs e) { Console.WriteLine("On Disconnect: {0} {1}", e.GetType(), sender); }
private static void Print(object sender, EventArgs e) { WriteLineColor($@"{e.GetType().Name} {e.ToString()}", ConsoleColor.DarkGray); }
private void toolSave_Click(object sender, EventArgs e) { //判断是否设置快递单号输入框的逻辑标记 bool boolIsFlag = false; string strSql = null; //表示单据类型代码的字符串 string strBillTypeCode = dgvrBillType.Cells["BillTypeCode"].Value.ToString(); //List<T>泛型 List <string> strSqls = new List <string>(); List <CTextBox> ctxts = this.GetCTextBoxes(this); foreach (CTextBox ctxt in ctxts) { //查找被设置为快递单号的控件 if (ctxt.IsFlag == "1") { boolIsFlag = true; } //判断控件的新旧 if (ctxt.ControlId == 0) //若该控件为新添加的 { strSql = "INSERT INTO tb_BillTemplate(BillTypeCode,X,Y,Width,Height,IsFlag,ControlName,DefaultValue,TurnControlName) VALUES( '" + strBillTypeCode + "','" + ctxt.Location.X + "','" + ctxt.Location.Y + "','" + ctxt.Width + "','" + ctxt.Height + "','" + ctxt.IsFlag + "','" + ctxt.ControlName + "','" + ctxt.DefaultValue + "','" + ctxt.TurnControlName + "')"; } else //若该控件为旧的控件 { strSql = "Update tb_BillTemplate Set BillTypeCode = '" + strBillTypeCode + "',X = '" + ctxt.Location.X + "',Y='" + ctxt.Location.Y + "',Width = '" + ctxt.Width + "',Height = '" + ctxt.Height + "',IsFlag = '" + ctxt.IsFlag + "',ControlName = '" + ctxt.ControlName + "',DefaultValue = '" + ctxt.DefaultValue + "',TurnControlName = '" + ctxt.TurnControlName + "' Where ControlId = '" + ctxt.ControlId + "'"; } strSqls.Add(strSql); } //判断快递单号输入框 if (!boolIsFlag) { if (e.GetType() == typeof(FormClosingEventArgs)) //若是关闭操作调用的保存处理 { ((FormClosingEventArgs)e).Cancel = true; //禁止关闭 } MessageBox.Show("请设置快递单号输入框,否则程序无法保存!", "软件提示"); return; } //判断快递单号输入框 if (strSqls.Count > 0) { if (MessageBox.Show("确定要保存吗?", "软件提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { if (dataOper.ExecDataBySqls(strSqls)) { DisposeAllCTextBoxes(this); //清除现有的控件布局 InitTemplate(strBillTypeCode); //重新加载窗体上面的控件布局 MessageBox.Show("保存模板成功!", "软件提示"); } else { MessageBox.Show("保存模板失败!", "软件提示"); } } } else { MessageBox.Show("未添加输入框,无需保存!", "软件提示"); } }
public async void CheckSignUp(object sender, EventArgs e) { if (string.IsNullOrEmpty(fName.Text)) { await DisplayAlert("Alert", "Required First Name", "OK"); return; } if (string.IsNullOrEmpty(lName.Text)) { await DisplayAlert("Alert", "Required Last Name", "OK"); return; } if (string.IsNullOrEmpty(emailAddress.Text)) { await DisplayAlert("Alert", "Required Email Address", "OK"); return; } if (!BaseFunctions.IsValidEmail(emailAddress.Text)) { await DisplayAlert("Alert", "Enter a valid email", "OK"); return; } if (string.IsNullOrEmpty(password.Text)) { await DisplayAlert("Alert", "Required Password", "OK"); return; } if (string.IsNullOrEmpty(retypePassword.Text)) { await DisplayAlert("Alert", "Please Re-type Password", "OK"); return; } if (password.Text != retypePassword.Text) { await DisplayAlert("Alert", "Password doesn't match", "OK"); return; } bool retry = false; do { try { string address = "http://www.myeventit.com/PHP/RegisterUser.php/"; var client = App.serverData.GetHttpClient(); ServerUser user = new ServerUser(); user.userFirstName = fName.Text; user.userLastName = lName.Text; user.userEmail = emailAddress.Text.ToLower(); user.userPrivacy = "False"; user.userBookmarks = new BookMark(); user.userBookmarks.speakers = new List <string>(); user.userBookmarks.exhibitors = new List <string>(); user.userBookmarks.sponsors = new List <string>(); user.userBookmarks.people = new List <string>(); user.userBookmarks.session = new List <string>(); user.userNotes = new List <string>(); user.userAddress = ""; user.userCompany = ""; user.userDescription = ""; user.userID = ""; user.userImage = ""; user.userPhone = ""; user.userWebsite = ""; user.userFacebook = ""; user.userTwitter = ""; user.userGplus = ""; user.userLinkedIn = ""; user.userCustomerID = new List <string>(); //user.userCustomerTokenList = new List<UserCard>(); var userString = JsonConvert.SerializeObject(user); var postData = new List <KeyValuePair <string, string> >(); postData.Add(new KeyValuePair <string, string>("user", userString)); postData.Add(new KeyValuePair <string, string>("password", password.Text)); HttpContent content = new FormUrlEncodedContent(postData); CancellationToken c = new CancellationToken(); HttpResponseMessage result = await client.PostAsync(address, content, c); var isRegistered = await result.Content.ReadAsStringAsync(); if (isRegistered.ToString() == "exists") { await DisplayAlert("Alert", emailAddress.Text + " is already registered!!", "OK"); return; } else if (isRegistered.ToString() == "false") { await DisplayAlert("Alert", "Registration failed", "OK"); return; } else if (isRegistered.ToString() == "mailFail") { var k = await DisplayAlert("Alert", "Confirmation link sending failed", "Resend Confirmation Link", "OK"); if (k) { await App.serverData.ResendVerficationEmail(user.userEmail); } return; } else { await DisplayAlert("Success", "You are successfully registered. A Confirmation link will be sent to your email.", "Ok"); Application.Current.MainPage = new LoginPage(); } } catch (Exception ex) { if (e.GetType() == typeof(System.Net.WebException)) { retry = await App.Current.MainPage.DisplayAlert("Alert", "No internet connection found. Please check your internet.", "Retry", "Cancel"); } else { retry = true; } if (!retry) { App.AppHaveInternet = false; if (App.Current.MainPage.GetType() != typeof(LoginPage)) { App.Current.MainPage = new LoginPage(); } } } } while (retry); }
private void EventTrace(object sender, EventArgs e) => OnEvent?.Invoke(_decorated, EventItem.Info($"{(!string.IsNullOrWhiteSpace(TraceState.State.OrderNumber) ? ($"[{TraceState.State.OrderNumber}] ") : string.Empty)}" + $"An event occured:{Environment.NewLine}\t>>> {(e.GetType().Name.EndsWith("EventArgs") ? (e.GetType().Name.Substring(0, e.GetType().Name.Length - 9)) : e.GetType().Name)} {e}"));
void _OnSelectedFoodChanged(EventArgs args) { EventArgs_FoodType selectedFoodArgs = args as EventArgs_FoodType; if (selectedFoodArgs != null) { _eSelFoodType = selectedFoodArgs.eFoodType; string path = FoodItem.GetPrefabPath(_eSelFoodType); GameObject prefab = Resources.Load <GameObject>(path); if (prefab != null) { if (_foodModel != null) { // 如果之前的食物还没扔出去,就删除掉,再重新创建一个 Projectile p = _foodModel.GetComponent <Projectile>(); if (!p.Move) { Destroy(_foodModel); _foodModel = null; } } _foodModel = Instantiate(prefab); Vector3 originPos = _foodModel.transform.localPosition; _foodModel.transform.parent = transform; _foodModel.transform.localPosition = originPos; _projectile = _foodModel.GetComponent <Projectile>(); } else { Debug.LogErrorFormat("Can NOT Load object in path: {0}", path); } } else { Debug.LogErrorFormat("Error: FoodModel::OnSelectedFoodChanged args type is {0}", args.GetType().ToString()); } }
private void download_button_Click(object sender, EventArgs e) { if (this.download_button.Text == "Pause") { Utility.TaskBarProgressState(true); this.PauseDownload = true; Utility.ReconnectDownload = false; this.download_button.Text = "Download"; } else { if (e != null && e.GetType() == typeof(Form1.DownloadEventArgs) && ((Form1.DownloadEventArgs)e).isReconnect && (this.download_button.Text == "Pause" || !Utility.ReconnectDownload)) { return; } if (this.PauseDownload) { Logger.WriteLog("Download thread is still running. Please wait.", false); } else if (string.IsNullOrEmpty(this.file_textbox.Text)) { Logger.WriteLog("No file to download. Please check for update first.", false); } else { if (e.GetType() != typeof(Form1.DownloadEventArgs) || !((Form1.DownloadEventArgs)e).isReconnect) { if (this.SaveFileDialog) { string str = Path.GetExtension(Path.GetFileNameWithoutExtension(this.FW.Filename)) + Path.GetExtension(this.FW.Filename); this.saveFileDialog1.SupportMultiDottedExtensions = true; this.saveFileDialog1.OverwritePrompt = false; this.saveFileDialog1.FileName = this.FW.Filename.Replace(str, ""); this.saveFileDialog1.Filter = "Firmware|*" + str; if (this.saveFileDialog1.ShowDialog() != DialogResult.OK) { Logger.WriteLog("Aborted.", false); return; } if (!this.saveFileDialog1.FileName.EndsWith(str)) { this.saveFileDialog1.FileName += str; } else { this.saveFileDialog1.FileName = this.saveFileDialog1.FileName.Replace(str + str, str); } Logger.WriteLog("Filename: " + this.saveFileDialog1.FileName, false); this.destinationfile = this.saveFileDialog1.FileName; if (System.IO.File.Exists(this.destinationfile)) { switch (new customMessageBox("The destination file already exists.\r\nWould you like to append it (resume download)?", "Append", DialogResult.Yes, "Overwrite", DialogResult.No, "Cancel", DialogResult.Cancel, (Image)SystemIcons.Warning.ToBitmap()).ShowDialog()) { case DialogResult.Cancel: Logger.WriteLog("Aborted.", false); return; case DialogResult.No: System.IO.File.Delete(this.destinationfile); break; } } } else { this.destinationfile = this.FW.Filename; } } Utility.TaskBarProgressState(false); BackgroundWorker backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += (DoWorkEventHandler)((o, _e) => { try { this.ControlsEnabled(false); Utility.ReconnectDownload = false; this.download_button.Invoke((Delegate)((Action)(() => { this.download_button.Enabled = true; this.download_button.Text = "Pause"; }))); if (this.FW.Filename == this.destinationfile) { Logger.WriteLog("Trying to download " + this.FW.Filename, false); } else { Logger.WriteLog("Trying to download " + this.FW.Filename + " to " + this.destinationfile, false); } Command.Download(this.FW.Path, this.FW.Filename, this.FW.Version, this.FW.Region, this.FW.Model_Type, this.destinationfile, this.FW.Size, true); if (this.PauseDownload) { Logger.WriteLog("Download paused", false); this.PauseDownload = false; if (Utility.ReconnectDownload) { Logger.WriteLog("Reconnecting...", false); Utility.Reconnect(new Action <object, EventArgs>(this.download_button_Click)); } } else { Logger.WriteLog("Download finished", false); if (this.checkbox_crc.Checked) { if (this.FW.CRC == null) { Logger.WriteLog("Unable to check CRC. Value not set by Samsung", false); } else { Logger.WriteLog("\nChecking CRC32...", false); if (!Utility.CRCCheck(this.destinationfile, this.FW.CRC)) { Logger.WriteLog("Error: CRC does not match. Please redownload the file.", false); System.IO.File.Delete(this.destinationfile); goto label_15; } else { Logger.WriteLog("Success: CRC match!", false); } } } this.decrypt_button.Invoke((Delegate)((Action)(() => this.decrypt_button.Enabled = true))); if (this.checkbox_autodecrypt.Checked) { this.decrypt_button_Click(o, (EventArgs)null); } } label_15: if (!Utility.ReconnectDownload) { this.ControlsEnabled(true); } this.download_button.Invoke((Delegate)((Action)(() => this.download_button.Text = "Download"))); } catch (Exception ex) { Logger.WriteLog(ex.Message, false); Logger.WriteLog(ex.ToString(), false); } }); backgroundWorker.RunWorkerAsync(); } } }
}// deactivateMText /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public static void mTxt_Erased(object sender, EventArgs e) { MessageBox.Show(e.GetType().ToString()); }// mTxt_Erased
/// <summary> /// Fires the specified topic directly on the <see cref="IEventBroker"/> without a real publisher. /// This is useful when temporarily created objects need to fire events. /// The event is fired globally but can be matched with <see cref="Matchers.ISubscriptionMatcher"/>. /// </summary> /// <param name="topic">The topic URI.</param> /// <param name="publisher">The publisher (for event flow and logging).</param> /// <param name="handlerRestriction">The handler restriction.</param> /// <param name="sender">The sender (passed to the event handler).</param> /// <param name="eventArgs">The <see cref="System.EventArgs"/> instance containing the event data.</param> public void Fire(string topic, object publisher, HandlerRestriction handlerRestriction, object sender, EventArgs eventArgs) { Ensure.ArgumentNotNull(eventArgs, "eventArgs"); IEventTopic eventTopic = this.eventTopicHost.GetEventTopic(topic); using (var spontaneousPublication = new SpontaneousPublication(eventTopic, publisher, eventArgs.GetType(), handlerRestriction, new List <IPublicationMatcher>())) { eventTopic.AddPublication(spontaneousPublication); eventTopic.Fire(sender, eventArgs, spontaneousPublication); eventTopic.RemovePublication(publisher, SpontaneousPublication.SpontaneousEventName); } }
/// <summary> /// Write log to file, event name and type will be dumped /// </summary> /// <param name="sender">Event sender.</param> /// <param name="args">EventArgs of this event.</param> public void WriteLogFile(Object sender, EventArgs args) { Trace.WriteLine("*********************************************************"); if (null == args) { return; } // get this eventArgs's runtime type. Type type = args.GetType(); String eventName = GetEventsName(type); Trace.WriteLine("Raised " + sender.GetType().ToString() + "." + eventName); Trace.WriteLine("---------------------------------------------------------"); // 1: output sender's information Trace.WriteLine(" Start to dump Sender and EventAgrs of Event...\n"); if (null != sender) { // output the type of sender Trace.WriteLine(" [Event Sender]: " + sender.GetType().FullName); } else { Trace.WriteLine(" Sender is null, it's unexpected!!!"); } // 2: Output event argument // get all properties info of this argument. PropertyInfo[] propertyInfos = type.GetProperties(); // output some typical property's name and value. (for example, Cancelable, Cancel,etc) foreach (PropertyInfo propertyInfo in propertyInfos) { try { if (!propertyInfo.CanRead) { continue; } else { Object propertyValue; String propertyName = propertyInfo.Name; switch (propertyName) { case "Document": case "Cancellable": case "Cancel": case "Status": case "DocumentType": case "Format": propertyValue = propertyInfo.GetValue(args, null); // Dump current property value Trace.WriteLine(" [Property]: " + propertyInfo.Name); Trace.WriteLine(" [Value]: " + propertyValue.ToString()); break; } } } catch (Exception ex) { // Unexpected exception Trace.WriteLine(" [Property Exception]: " + propertyInfo.Name + ", " + ex.Message); } } }
/// <summary>Hit when the client is finished connecting and logging in.</summary> /// <param name="sender">The client that called it.</param> /// <param name="e">Event Args.</param> private void client_FinishConnecting(object sender, EventArgs e) { try { ImportExport client = (ImportExport)sender; string eType = e.GetType().ToString(); eType = eType.Substring(eType.LastIndexOf('.') + 1); switch (eType) { case "Connection_Authenticate2CompletedEventArgs": { //Connect finished. Connection_Authenticate2CompletedEventArgs evt = (Connection_Authenticate2CompletedEventArgs)e; ObjectState evtObj = (ObjectState)evt.UserState; if (evt.Error == null) { client.System_GetProductVersionAsync(evtObj); } else { //Set error to node. TreeViewItem oldNode = (TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]; this.trvProject.Items.RemoveAt(evtObj.NodeNumber); this.trvProject.Items.Insert(evtObj.NodeNumber, this.changeNodeImage(oldNode, "imgError")); ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).ToolTip = new TextBlock() { Text = evt.Error.Message }; ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).Items.Clear(); //Error, clean up. removeClient(client); } } break; case "System_GetProductVersionCompletedEventArgs": { //Connect finished. System_GetProductVersionCompletedEventArgs evt = (System_GetProductVersionCompletedEventArgs)e; ObjectState evtObj = (ObjectState)evt.UserState; if (evt.Error == null) { evtObj.ClientVersion = evt.Result; client.Connection_ConnectToProjectAsync(evtObj.Project.ProjectID, evtObj); } else { //Set error to node. TreeViewItem oldNode = (TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]; this.trvProject.Items.RemoveAt(evtObj.NodeNumber); this.trvProject.Items.Insert(evtObj.NodeNumber, this.changeNodeImage(oldNode, "imgError")); ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).ToolTip = new TextBlock() { Text = evt.Error.Message }; ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).Items.Clear(); //Error, clean up. removeClient(client); } } break; case "Connection_ConnectToProjectCompletedEventArgs": { //Connect finished. Connection_ConnectToProjectCompletedEventArgs evt = (Connection_ConnectToProjectCompletedEventArgs)e; ObjectState evtObj = (ObjectState)evt.UserState; if (evt.Error == null) { evtObj.curSearchIsMine = true; RemoteFilter[] filters = GenerateFilter(evtObj.Project.UserID, this.btnShowClosed.IsChecked.Value, "IN"); RemoteSort sort = GenerateSort(); client.Incident_RetrieveAsync(filters, sort, 1, 9999999, evtObj); } else { //Set error to node. TreeViewItem oldNode = (TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]; this.trvProject.Items.RemoveAt(evtObj.NodeNumber); this.trvProject.Items.Insert(evtObj.NodeNumber, this.changeNodeImage(oldNode, "imgError")); ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).ToolTip = new TextBlock() { Text = evt.Error.Message }; ((TreeViewItem)this.trvProject.Items[evtObj.NodeNumber]).Items.Clear(); //Error, clean up. removeClient(client); } } break; } } catch (Exception ex) { Connect.logEventMessage("wpfProjectTree::client_FinishConnecting", ex, System.Diagnostics.EventLogEntryType.Error); } }
// If MonoGame is in use, we can easily take advantage of its build-in input handler private static void TextInputHandler(object s, EventArgs e) { CharReceived?.Invoke((char)e.GetType().GetField("Character").GetValue(e)); }
/// <summary> /// Test event handler for <see cref="_testGame"/> /// </summary> /// <param name="sender">Event source</param> /// <param name="e">Event data</param> private void Game_Complete(object sender, EventArgs e) { Console.WriteLine("Handler Game_GameComplete() running."); Assert.AreEqual(typeof(GameCompleteEventArgs), e.GetType()); Assert.AreEqual(_testGame.Id, ((GameCompleteEventArgs)e).GameId); }
/// <summary> /// Write log to file: which event occurred in which document. /// </summary> /// <param name="args">Event arguments that contains the event data.</param> /// <param name="doc">document in which the event is occur.</param> public static void WriteLog(EventArgs args, Document doc) { Trace.WriteLine(""); Trace.WriteLine("[Event] " + GetEventName(args.GetType()) + ": " + TitleNoExt(doc.Title)); }
}// InitializeEngine() // // // **** Process Event **** // public void ProcessEvent(EventArgs e) { // Initialize and validate if (!m_IsGraphsInitialized) { // Graphs not initialized yet. Just store these events. m_InitialEvents.Add(e); return; } else if (m_InitialEvents.Count > 0) { // The graphs have just been initialized, so // lets extract all the previously stored initial events. List <EventArgs> events = new List <EventArgs>(); events.AddRange(m_InitialEvents); // add already acrued events. m_InitialEvents.Clear(); // clearing this signals we are ready for normal operation. events.Add(e); // add the latest event also. foreach (EventArgs anEvent in events) { ProcessEvent(anEvent); } } if (e.GetType() != typeof(EngineEventArgs)) { return; } // // Process Engine Events // EngineEventArgs eArgs = (EngineEventArgs)e; EngineEventArgs.EventType eventType = eArgs.MsgType; EngineEventArgs.EventStatus eventStatus = eArgs.Status; if (eventStatus != EngineEventArgs.EventStatus.Confirm) { return; // we only process confirmations. } if (eArgs.DataObjectList != null) { foreach (object o in eArgs.DataObjectList) { // ***************************************** // **** Curve Definitiion List **** // ***************************************** Type dataType = o.GetType(); //if (dataType == typeof(List<CurveDefinition>)) if (dataType == typeof(CurveDefinitionList)) { // Given a list of curve definitions, update pre-defined curves, // or create new curves. These must be created by the windows thread. // These are usually only received at the start of the run when all parameters are broadcasted. List <CurveDefinition> list = ((CurveDefinitionList)o).CurveDefinitions; Dictionary <int, EngineEventArgs> requestedGraphRequests = new Dictionary <int, EngineEventArgs>(); // place to put CurveDefs for not yet created graphs. foreach (CurveDefinition cDef in list) { ZedGraphControl zg1; lock (GraphListLock) { if (!m_GraphList.TryGetValue(cDef.GraphID, out zg1)) { // Since we can't find this GraphID, request it to be created below. m_ZedGraphIDRequested.Add(cDef.GraphID); zg1 = null; // this signals that graph doesn't exit. } } if (zg1 == null && !requestedGraphRequests.ContainsKey(cDef.GraphID)) { // We couldn't find GraphID, so request it to be created it now! // Also make sure we only request it once thru this loop, just to save time. AddGraph(this, eArgs); // Asynch call will call ProcessEvent() again. EngineEventArgs newEvent = new EngineEventArgs(); // Event we will restack until after graph exists. newEvent.DataObjectList = new List <object>(); newEvent.Status = EngineEventArgs.EventStatus.Confirm; requestedGraphRequests.Add(cDef.GraphID, newEvent);// Mark this ID as having just been requested. } if (requestedGraphRequests.ContainsKey(cDef.GraphID)) { // This is a curve for a graph we just requested... push onto wait list. requestedGraphRequests[cDef.GraphID].DataObjectList.Add(cDef); continue; // skip } UpdateCurveDefinition(zg1, cDef); }//next curveDefn // Push any unfulfilled requests back onto queue. foreach (EngineEventArgs eeArgs in requestedGraphRequests.Values) { m_InitialEvents.Add(eeArgs); } } // ***************************************** // **** ZGraphPoints **** // ***************************************** else if (dataType == typeof(ZGraphPoints)) { // This is a list of ZGraphPoint objects. This message is from the AllParameter broadcast // at the beginning of the run. A new ZGraphControl will request all parameter values // only when first created. Therefore, if we are an old ZGraphControl, it probably is not // for us. if (m_LoadedHistory) { return; } m_LoadedHistory = true; List <ZGraphPoint> pointList = ((ZGraphPoints)o).Points; foreach (ZGraphPoint zpt in pointList) { ZedGraphControl zg1; if (!m_GraphList.TryGetValue(zpt.GraphID, out zg1)) { // No currently existing graph with this id. continue; } CurveItem curve = null; if (zg1.GraphPane != null) { curve = zg1.GraphPane.CurveList[zpt.CurveName]; if (curve == null) { // a new curve showed up - create a new curve, and plot this point anyway. Color newColor = m_DefaultColors[zg1.GraphPane.CurveList.Count % m_DefaultColors.Length]; curve = zg1.GraphPane.AddCurve(zpt.CurveName, new PointPairList(), newColor, SymbolType.None); } } // Add/replace points in the plot. IPointListEdit ip = null; if (curve != null) { ip = curve.Points as IPointListEdit; } if (ip != null) { if (zpt.IsReplaceAtX) { // This is a request to replace point with new one. int foundIndex = -1; for (int i = 0; i < ip.Count; ++i) // search for X-value of point to replace { if (ip[i].X == zpt.X) // very unsafe { foundIndex = i; break; // stop looking } } if (foundIndex > -1) { ip[foundIndex].Y = zpt.Y; } else { ip.Add(zpt.X, zpt.Y); // sort? } } else { ip.Add(zpt.X, zpt.Y); // simple serial addition of new data point. } } }//next zpt } // ***************************************** // **** List<ZGraphPoint> **** // ***************************************** /* * else if (dataType == typeof(List<ZGraphPoint>)) * { // This is a list of ZGraphPoints. This message is from the AllParameter broadcast * // at the beginning of the run. A new ZGraphControl will request all parameter values * // only when first created. Therefore, if we are an old ZGraphControl, it probably is not * // for us. * List<ZGraphPoint> pointList = (List<ZGraphPoint>) o; * foreach (ZGraphPoint zpt in pointList) * { * ZedGraphControl zg1; * if (!m_GraphList.TryGetValue(zpt.GraphID, out zg1)) * { // No currently existing graph with this id. * continue; * } * CurveItem curve = null; * if (zg1.GraphPane != null) * { * curve = zg1.GraphPane.CurveList[zpt.CurveName]; * if (curve == null) * { // a new curve showed up - create a new curve, and plot this point anyway. * Color newColor = m_DefaultColors[zg1.GraphPane.CurveList.Count % m_DefaultColors.Length]; * curve = zg1.GraphPane.AddCurve(zpt.CurveName, new PointPairList(), newColor, SymbolType.None); * } * } * // Add/replace points in the plot. * IPointListEdit ip = null; * if (curve != null) * ip = curve.Points as IPointListEdit; * if (ip != null) * { * if (zpt.IsReplaceAtX) * { // This is a request to replace point with new one. * int foundIndex = -1; * for (int i = 0; i < ip.Count; ++i) // search for X-value of point to replace * if (ip[i].X == zpt.X) // very unsafe * { * foundIndex = i; * break; // stop looking * } * if (foundIndex > -1) * ip[foundIndex].Y = zpt.Y; * else * { * ip.Add(zpt.X, zpt.Y); * // sort? * } * * } * else * ip.Add(zpt.X, zpt.Y); // simple serial addition of new data point. * } * }//next zpt * } */ // ***************************************** // **** Curve Definition **** // ***************************************** else if (dataType == typeof(CurveDefinition)) { CurveDefinition zNewCurve = (CurveDefinition)o; ZedGraphControl zg1; if (!m_GraphList.TryGetValue(zNewCurve.GraphID, out zg1)) { // New graph ID! continue; // TODO: Create new graph on the fly. } UpdateCurveDefinition(zg1, zNewCurve); } // ***************************************** // **** ZGraphPoint **** // ***************************************** else if (dataType == typeof(ZGraphText)) { ZGraphText zpt = (ZGraphText)o; ZedGraphControl zg1; if (!m_GraphList.TryGetValue(zpt.GraphID, out zg1)) { // No currently existing graph with this id. continue; } TextObj text = new TextObj(zpt.Text, zpt.X, zpt.Y); text.FontSpec.Angle = zpt.FontAngle; text.Location.AlignH = zpt.FontAlignH; text.Location.AlignV = zpt.FontAlignV; text.FontSpec.Size = zpt.FontSize; text.FontSpec.Border.IsVisible = zpt.FontBorderIsVisible; text.FontSpec.Fill.IsVisible = zpt.FontFillIsVisible; zg1.GraphPane.GraphObjList.Add(text); } // ***************************************** // **** ZGraphPoint **** // ***************************************** else if (dataType == typeof(ZGraphPoint)) { ZGraphPoint zpt = (ZGraphPoint)o; ZedGraphControl zg1; if (!m_GraphList.TryGetValue(zpt.GraphID, out zg1)) { // No currently existing graph with this id. continue; } CurveItem curve = null; if (zg1.GraphPane != null) { curve = zg1.GraphPane.CurveList[zpt.CurveName]; if (curve == null) { // a new curve showed up - create a new curve, and plot this point anyway. Color newColor = m_DefaultColors[zg1.GraphPane.CurveList.Count % m_DefaultColors.Length]; curve = zg1.GraphPane.AddCurve(zpt.CurveName, new PointPairList(), newColor, SymbolType.None); } } // Add/replace points in the plot. IPointListEdit ip = null; if (curve != null) { ip = curve.Points as IPointListEdit; } if (ip != null) { if (zpt.IsReplaceAtX) { // This is a request to replace point with new one. int foundIndex = -1; for (int i = 0; i < ip.Count; ++i) // search for X-value of point to replace { if (ip[i].X == zpt.X) // very unsafe { foundIndex = i; break; // stop looking } } if (foundIndex > -1) { ip[foundIndex].Y = zpt.Y; } else { ip.Add(zpt.X, zpt.Y); // sort? } } else { ip.Add(zpt.X, zpt.Y); // simple serial addition of new data point. } } }// ZPoint } m_IsUpdateRequired = true; //Regenerate(this, EventArgs.Empty); } //if e.DataObjectList is empty } // ProcessEvent()
/* Events */ protected virtual void TraceEvent(HtmlGenericControl memo, object sender, EventArgs args, string eventName) { string s = ""; PropertyInfo[] properties = args.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo propertyInfo in properties) { s += propertyInfo.Name + " = " + (propertyInfo.PropertyType.IsValueType ? propertyInfo.GetValue(args, null) : "[" + propertyInfo.PropertyType.Name + "]") + "<br />"; } memo.InnerHtml += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr><td valign=\"top\" style=\"width: 100px;\">Sender:</td><td valign=\"top\">" + (sender as Control).ID + "</td></tr><tr><td valign=\"top\">EventType:</td><td valign=\"top\"><b>" + eventName + "</b></td></tr><tr><td valign=\"top\">Arguments:</td><td valign=\"top\">" + s + "</td></tr></table><br />"; }
public void RafNotifyCompleted(object e, EventArgs a) { string r = a.GetType().ToString(); }
public override string ToString() => $"kind:{StartKind} cause:{StartCause} previous:{PreviousExecutionState} type:{EventArgs?.GetType().ToString() ?? "null"}";
private void TimerButton_Click(object sender, EventArgs e) { //Right click delete if (e.GetType().Equals(typeof(MouseEventArgs))) { MouseEventArgs mouse = (MouseEventArgs)e; if (mouse.Button == MouseButtons.Right) { TimerMenuStrip.Show(Cursor.Position); } } //Get selected TimerItem BunifuFlatButton clickedButton = (BunifuFlatButton)sender; BLIO.Log("TimerButton " + clickedButton.Text + " clicked!"); //Remove all the text apart from the id and store it int id = GetTimerButtonId(clickedButton); foreach (TimerItem itm in timers) { if (itm.ID == id) { lblTimerTitle.Text = "Timer: " + itm.TimerText; currentTimerItem = itm; lblTimerTitle.Visible = true; if (currentTimerItem.Running) { tmrCountdown.Start(); } else { tmrCountdown.Stop(); } BLIO.Log("Setting values of (UCTimer) numericupdowns"); TimeSpan time = TimeSpan.FromSeconds((double)currentTimerItem.SecondsRemaining); numSeconds.Value = time.Seconds; numMinutes.Value = time.Minutes; numHours.Value = time.Hours; } } //Show play or pause depending on if the selected timer is running or not if (currentTimerItem.Running) { btnPauseResumeTimer.Iconimage = Properties.Resources.pause_2x1; } else { btnPauseResumeTimer.Iconimage = Properties.Resources.Play; } EnableButton(clickedButton); }
static void Log(string title, object sender, EventArgs e) { Console.WriteLine("Event:{0}\n Sender:{1}\n Arguments:{2}", title, sender, e.GetType()); foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(e)) { string name = prop.DisplayName; object value = prop.GetValue(e); Console.WriteLine("\t{0}={1}", name, value); } }
internal DomEventArgs(EventArgs e) { _eventArgs = e; _eventArgsType = e.GetType(); }
private void button1_Click(object sender, EventArgs e) { CancellationTokenSource source = new CancellationTokenSource(); CancellationToken token = source.Token; Random rnd = new Random(); Object lockObj = new Object(); List <Task <int[]> > tasks = new List <Task <int[]> >(); TaskFactory factory = new TaskFactory(token); for (int taskCtr = 0; taskCtr <= 10; taskCtr++) { int iteration = taskCtr + 1; tasks.Add(factory.StartNew(() => { int value; int[] values = new int[10]; for (int ctr = 1; ctr <= 10; ctr++) { lock (lockObj) { value = rnd.Next(0, 101); } if (value == 0) { source.Cancel(); Console.WriteLine("Cancelling at task {0}", iteration); break; } values[ctr - 1] = value; } return(values); }, token)); } try { Task <double> fTask = factory.ContinueWhenAll(tasks.ToArray(), (results) => { Console.WriteLine("Calculating overall mean..."); long sum = 0; int n = 0; foreach (var t in results) { foreach (var r in t.Result) { sum += r; n++; } } return(sum / (double)n); }, token); Console.WriteLine("The mean is {0}.", fTask.Result); } catch (AggregateException ae) { foreach (Exception ex in ae.InnerExceptions) { if (ex is TaskCanceledException) { Console.WriteLine("Unable to compute mean: {0}", ((TaskCanceledException)ex).Message); } else { Console.WriteLine("Exception: " + e.GetType().Name); } } } finally { source.Dispose(); } }
public static void HandlingEvent(ILogger <Renderer> logger, ulong eventHandlerId, EventArgs eventArgs) { _handlingEvent(logger, eventHandlerId, eventArgs?.GetType().Name ?? "null", null); }
private void panStartedHandler(object sender, EventArgs e) { Debug.Log ("panStartedHandler()"); Debug.Log (e.GetType()); }