private void NeuronService_ConnectionStateChanged(object sender, ConnectionStateChangedEventArgs e) { UiDispatcher.BeginInvokeOnMainThread(() => { AssignProperties(e.State); }); }
private void SetStatusLabelCaption(string caption, int?errorCount = null) { var reparseCommandButton = FindChildByTag(typeof(ReparseCommandMenuItem).FullName) as ReparseCommandMenuItem; if (reparseCommandButton == null) { return; } var showErrorsCommandButton = FindChildByTag(typeof(ShowParserErrorsCommandMenuItem).FullName) as ShowParserErrorsCommandMenuItem; if (showErrorsCommandButton == null) { return; } UiDispatcher.Invoke(() => { reparseCommandButton.SetCaption(caption); reparseCommandButton.SetToolTip(string.Format(RubberduckUI.ReparseToolTipText, caption)); if (errorCount.HasValue && errorCount.Value > 0) { showErrorsCommandButton.SetToolTip(string.Format(RubberduckUI.ParserErrorToolTipText, errorCount.Value)); } }); Localize(); }
private async Task LoadJSonFile(string file) { try { UiDispatcher.RunOnUIThread(() => { SystemConsole.Show(); }); AppendMessage("Loading " + file); ShowStatus("Loading " + file); JSonDataLog data = new JSonDataLog(); await data.Load(file, progress); //logs.Add(data); ShowSchema(); LoadFlights(data); } catch (Exception ex) { AppendMessage("### Error loading json file: " + ex.Message); } ShowStatus("Done Loading " + file); UpdateButtons(); }
private void NewRate(LatestPriceResultMessage result) { UiDispatcher.Invoke(() => { var e = ExchangeRates.FirstOrDefault(x => x.IsSimilarRequest(result)); if (e != null) { ExchangeRates.Remove(e); } ExchangeRates.Add(result); var exrs = ExchangeRates.OrderBy(x => x.Pair.ToString()).ToList(); ExchangeRates.Clear(); foreach (var er in exrs) { ExchangeRates.Add(er); } if (AssetLeft.IsNone() || AssetRight.IsNone() || ConvertLeft == 0) { return; } var ap = new AssetPair(AssetLeft, AssetRight); if (!result.Pair.Equals(ap)) { return; } _isConverted = result.IsConverted; ResultViewModel = new ExchangeRateResultViewModel(this, result); LoadingInfo = ""; }); }
private async Task DoInstallAndRaiseAsync() { string password = null; if (HasPassword && !string.IsNullOrEmpty(Password) && !string.IsNullOrWhiteSpace(Password)) { password = Password; } try { bool isInstalled = await Database.DatabaseProvider.InstallAsync(password); if (isInstalled) { await UiDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(RaisePropertyChangedToViewModel)); } } catch (Exception exception) { MessageBoxHelper.ShowMessage(exception.Message, "Failed to install Database", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Invokes the specified method on the feature object in Mowbly javascript layer, with the result as argument. /// </summary> /// <param name="obj">The object to invoke the method on in Mowbly javascript layer</param> /// <param name="method">The method to call in Mowbly javascript layer</param> /// <param name="r">The /// <see cref="CloudPact.MowblyFramework.Core.Features.MethodResult">MethodResult</see> /// object to send to Mowbly javascript layer.</param> internal void InvokeJavascript(string obj, string method, MethodResult r) { UiDispatcher.BeginInvoke(() => { Page.InvokeJavascript(obj, method, new Object[] { r }); }); }
private void LoadFlights(IDataLog data) { UiDispatcher.RunOnUIThread(() => { // add flights Flight entireLog = new Flight() { Name = "Log " + logs.Count, StartTime = data.StartTime, Duration = data.Duration }; allFlights.Add(entireLog); foreach (var flight in data.GetFlights()) { flight.Name = "Flight " + allFlights.Count; allFlights.Add(flight); AppendMessage("Motor started at {0} and ran for {1} ", flight.StartTime, flight.Duration); } if (myMap.Visibility == Visibility.Visible) { ShowMap(); } }); }
private void TagProfile_Changed(object sender, PropertyChangedEventArgs e) { UiDispatcher.BeginInvokeOnMainThread(() => { IntroText = string.Format(AppResources.ToConnectToDomainYouNeedAnAccount, this.TagProfile.Domain); }); }
private void ShowSchema() { UiDispatcher.RunOnUIThread(() => { LogItemSchema schema = null; // todo: compute combined schema for selected logs, but for now just show the first one. if (this.currentFlightLog != null) { schema = currentFlightLog.Schema; } else if (this.logs.Count > 0) { schema = this.logs[0].Schema; } if (schema == null || schema.ChildItems == null || schema.ChildItems.Count == 0) { CategoryList.ItemsSource = null; } else { // todo: compute combined schema for selected logs, but for now just show the first one. List <LogItemSchema> list = new List <Model.LogItemSchema>(schema.ChildItems); list.Sort((a, b) => { return(string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); }); CategoryList.ItemsSource = list; } }); }
private async Task LoadMavlinkFile(string file) { try { UiDispatcher.RunOnUIThread(() => { SystemConsole.Show(); }); AppendMessage("Loading " + file); ShowStatus("Loading " + file); MavlinkLog data = new MavlinkLog(); await data.Load(file, progress); logs.Add(data); ShowSchema(); Debug.WriteLine(data.StartTime.ToString()); LoadFlights(data); // remember successfully loaded log file. Settings settings = await((App)App.Current).LoadSettings(); settings.LastLogFile = file; await settings.SaveAsync(); } catch (Exception ex) { AppendMessage("### Error loading log: " + ex.Message); } ShowStatus("Done Loading " + file); UpdateButtons(); }
private void ShowStatus(string message) { UiDispatcher.RunOnUIThread(() => { StatusText.Text = message; }); }
private void UpdateButtons() { UiDispatcher.RunOnUIThread(() => { ShowMapButton.Visibility = Visibility.Visible; }); }
// background thread private void ChangePassword(object state) { OfxRequest req = new OfxRequest(this.account, this.money, null); try { req.ChangePassword(this.account, newPassword, out logFile); } catch (Exception e) { Error = e; } if (cancelled) { return; } UiDispatcher.BeginInvoke(new Action(() => { if (this.Error != null) { // The error might be about the new password being invalid for some reason, so show // the message and let user try again. ShowError(this.Error.Message); EnableButtons(); } else { this.DialogResult = true; this.account.Password = this.GetUserDefinedField("NewPassword"); this.Close(); } })); }
public override async void CanExecuteCommand(params IJavascriptObject[] e) { var parameter = _JavascriptToCSharpConverter.GetFirstArgumentOrNull(e); await UiDispatcher.RunAsync(() => _CanExecute = _Command.CanExecute(parameter)); UpdateCanExecuteValue(); }
/// <summary> /// Invoke the method specified by the /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object /// </summary> /// <param name="message"> /// <see cref="CloudPact.MowblyFramework.Core.Features.JSMessage">JSMessage</see> object /// </param> internal async override void InvokeAsync(JSMessage message) { try { switch (message.Method) { case "sendMail": List <string> toList = ((JToken)message.Args[0]).ToObject <List <string> >(); string subject = message.Args[1] as string; string body = message.Args[2] as string; List <string> ccList = ((JToken)message.Args[3]).ToObject <List <string> >(); List <string> bccList = ((JToken)message.Args[4]).ToObject <List <string> >(); // Create email compose task and display EmailComposeTask emailComposeTask = new EmailComposeTask(); emailComposeTask.To = String.Join("; ", toList); emailComposeTask.Subject = subject; emailComposeTask.Body = body; emailComposeTask.Cc = String.Join("; ", ccList); emailComposeTask.Bcc = String.Join("; ", bccList); UiDispatcher.BeginInvoke(() => { emailComposeTask.Show(); }); // Set app navigated to external page Mowbly.AppNavigatedToExternalPage = true; break; case "sendText": case "sendData": // Create sms compose task and show List <string> phoneNumbers = ((JToken)message.Args[0]).ToObject <List <string> >(); string text = message.Args[1] as string; SmsComposeTask smsComposeTask = new SmsComposeTask(); smsComposeTask.To = String.Join(";", phoneNumbers); smsComposeTask.Body = text; UiDispatcher.BeginInvoke(() => { smsComposeTask.Show(); }); // Set app navigated to external page Mowbly.AppNavigatedToExternalPage = true; break; default: Logger.Error("Feature " + Name + " does not support method " + message.Method); break; } } catch (Exception ce) { Logger.Error("Exception occured. Reason - " + ce.Message); } await Task.FromResult(0); }
public App(VBE vbe, IMessageBox messageBox, UI.Settings.Settings settings, IRubberduckParser parser, IGeneralConfigService configService, IAppMenu appMenus, RubberduckCommandBar stateBar, IRubberduckHooks hooks) { _vbe = vbe; _messageBox = messageBox; _settings = settings; _parser = parser; _configService = configService; _autoSave = new AutoSave.AutoSave(_vbe, _configService); _appMenus = appMenus; _stateBar = stateBar; _hooks = hooks; _hooks.MessageReceived += _hooks_MessageReceived; _configService.SettingsChanged += _configService_SettingsChanged; _parser.State.StateChanged += Parser_StateChanged; _parser.State.StatusMessageUpdate += State_StatusMessageUpdate; _stateBar.Refresh += _stateBar_Refresh; UiDispatcher.Initialize(); }
private void _state_StateChanged(object sender, System.EventArgs e) { _allDeclarations = _state.AllDeclarations .Select(item => new Declaration(item)) .ToArray(); _userDeclarations = _state.AllUserDeclarations .Select(item => new Declaration(item)) .ToArray(); var errorHandler = OnError; if (_state.Status == Parsing.VBA.ParserState.Error && errorHandler != null) { UiDispatcher.Invoke(errorHandler.Invoke); } var parsedHandler = OnParsed; if (_state.Status == Parsing.VBA.ParserState.Parsed && parsedHandler != null) { UiDispatcher.Invoke(parsedHandler.Invoke); } var readyHandler = OnReady; if (_state.Status == Parsing.VBA.ParserState.Ready && readyHandler != null) { UiDispatcher.Invoke(readyHandler.Invoke); } }
private void _state_StateChanged(object sender, ParserStateEventArgs e) { if (e.State == ParserState.Pending) { UiDispatcher.InvokeAsync(Refresh); } }
void Backup(bool shutdown) { ConsoleTextBox.Document.Blocks.Clear(); this._errors = new ErrorLog(); this.cancel = new CancellationTokenSource(); Task.Run(() => { try { backup.Run(this._log, this._errors, cancel); } catch (Exception ex) { backup.Error = ex.Message; backup.Running = false; backup.Complete = true; this._log.WriteLine(ex.Message); } if (shutdown) { backup.Shutdown(); UiDispatcher.RunOnUIThread(ShowCancelShutdown); } UiDispatcher.RunOnUIThread(OnBackupComplete); }); }
public ParserState() { UiDispatcher.Initialize(); _state = new RubberduckParserState(); _state.StateChanged += _state_StateChanged; }
public MainWindow() { UiDispatcher.Initialize(); InitializeComponent(); RestorePosition(); this.Loaded += OnMainWindowLoaded; }
bool HandleUnhandledException(object exceptionObject) { Exception ex = exceptionObject as Exception; string message = null; string details = null; if (ex == null && exceptionObject != null) { message = exceptionObject.GetType().FullName; details = exceptionObject.ToString(); } else { message = ex.Message; details = ex.ToString(); } try { UiDispatcher.RunOnUIThread(() => { MessageBoxEx.Show(message, "Unhandled Exception", details, MessageBoxButton.OK, MessageBoxImage.Error); }); return(true); } catch (Exception) { // hmmm, if we can't show the dialog then perhaps this is some sort of stack overflow. // save the details to a file, terminate the process and } return(false); }
private void DiffBaseline(TestModel model) { string path = model.Path; model.Baseline = FindBaseline(path); string newBaseLine = System.IO.Path.Combine(model.Path, settings.ErrorLogName); string oldBaseLine = System.IO.Path.Combine(model.Baseline, settings.BaselineName); if (File.Exists(newBaseLine) && !File.Exists(oldBaseLine)) { MessageBox.Show(this, model.Path + "\n\nThis test baseline cannot be fixed because it was not supposed to pass.", "Unexpected Baseline", MessageBoxButton.OK, MessageBoxImage.Error); FailedTestList.SelectedIndex++; return; } else if (!File.Exists(newBaseLine) && File.Exists(oldBaseLine)) { MessageBox.Show(this, model.Path + "\n\nThis test baseline cannot be fixed because the test couldn't run.", "Missing Baseline", MessageBoxButton.OK, MessageBoxImage.Error); FailedTestList.SelectedIndex++; return; } Task.Run(() => { string args = string.Format("\"{0}\" \"{1}\"", newBaseLine, oldBaseLine); Process windiff = Process.Start(new ProcessStartInfo(settings.WindiffPath, args)); windiff.WaitForExit(); UiDispatcher.RunOnUIThread(() => { PromptUser(model); }); }); }
private void FiterEventTextChanged(string filter) { if (FilterValueChanged != null) { UiDispatcher.BeginInvoke(FilterValueChanged, this, filter); } }
private void NeuronService_ConnectionStateChanged(object sender, ConnectionStateChangedEventArgs e) { UiDispatcher.BeginInvokeOnMainThread(() => { SetConnectionStateAndText(e.State); RegisterCommand.ChangeCanExecute(); }); }
public static int Run(Arguments args) { var app = new InstallApplication(); var dispatcher = new UiDispatcher(System.Windows.Threading.Dispatcher.CurrentDispatcher); var window = new MainWindow(new MainWindowViewModel(dispatcher)); window.Show(); return app.Run(); }
private MasterDataSource() { var networkConfiguration = new NetworkWrapper(); var uiDispatcher = new UiDispatcher(); var peopleNetworkMessenger = new PeopleNetworkMessenger(networkConfiguration, uiDispatcher); PeopleDataSource = new PeopleDataSource(peopleNetworkMessenger); }
/// <summary> /// Notifies the user interface registered controls based on the current state and the new position of the cursor position. /// </summary> /// <param name="normalizedX">New X position of the kinect cursor</param> /// <param name="normalizedY">New Y position of the kinect cursor</param> /// <param name="hasCursorPositionChanged">Boolean that indicates whether the normalizedX and normalizedY values are identical to the previous values</param> protected void UpdateControls(double normalizedX, double normalizedY, bool hasCursorPositionChanged) { UiDispatcher.BeginInvoke(new Action(() => { var newActiveControl = GetActiveControl(normalizedX, normalizedY); if (newActiveControl == currentActiveControl) { if (newActiveControl != null && hasCursorPositionChanged) { newActiveControl.TriggerCursorMove(new KinectUiEventArgs() { NormalizedX = normalizedX, NormalizedY = normalizedY }); } if (newActiveControl != null && newActiveControl.IsActivationEnabled) { var elapsed = DateTime.Now - this.ActiveControlEnterTime; var normalizedTime = Math.Min(1.0, elapsed.TotalMilliseconds / newActiveControl.ActivationTime.Value); if (!IsControlActivated) { this.UpdateCursorsActivationProgress(normalizedTime); } if (normalizedTime == 1.0 && !IsControlActivated) { newActiveControl.TriggerActivation(new KinectUiEventArgs() { NormalizedX = normalizedX, NormalizedY = normalizedY }); IsControlActivated = true; } } } else { if (newActiveControl != null) { newActiveControl.TriggerCursorEnter(new KinectUiEventArgs() { NormalizedX = normalizedX, NormalizedY = normalizedY }); this.ActiveControlEnterTime = DateTime.Now; } if (currentActiveControl != null) { currentActiveControl.TriggerCursorLeave(new KinectUiEventArgs() { NormalizedX = normalizedX, NormalizedY = normalizedY }); this.StopCursorsActivationCountdown(); } IsControlActivated = false; this.UpdateCursorsActivationProgress(0.0); } currentActiveControl = newActiveControl; })); }
void BeginGetQuotes(HashSet <Security> toFetch) { if (_services.Count == 0 || toFetch.Count == 0) { return; } UiDispatcher.BeginInvoke(new Action(() => { OutputPane output = (OutputPane)provider.GetService(typeof(OutputPane)); output.Clear(); output.AppendHeading(Walkabout.Properties.Resources.StockQuoteCaption); })); List <string> batch = new List <string>(); foreach (Security s in toFetch) { if (string.IsNullOrEmpty(s.Symbol)) { continue; // skip it. } batch.Add(s.Symbol); } bool foundService = false; IStockQuoteService service = GetHistoryService(); HistoryDownloader downloader = GetDownloader(service); if (service != null) { downloader.BeginFetchHistory(batch); foundService = true; } service = GetQuoteService(); if (service != null) { foundService = true; if (service.SupportsBatchQuotes) { service.BeginFetchQuotes(batch); } else { foreach (var item in batch) { service.BeginFetchQuote(item); } } } if (!foundService) { AddError(Walkabout.Properties.Resources.ConfigureStockQuoteService); UiDispatcher.BeginInvoke(new Action(UpdateUI)); } }
public static int Run(Arguments args) { var app = new InstallApplication(); var dispatcher = new UiDispatcher(System.Windows.Threading.Dispatcher.CurrentDispatcher); var window = new MainWindow(new MainWindowViewModel(dispatcher)); window.Show(); return(app.Run()); }
public void Startup() { CleanReloadConfig(); _appMenus.Initialize(); _hooks.HookHotkeys(); // need to hook hotkeys before we localize menus, to correctly display ShortcutTexts _appMenus.Localize(); Task.Delay(1000).ContinueWith(t => UiDispatcher.Invoke(() => _parser.State.OnParseRequested(this))); UpdateLoggingLevel(); }
public static int Run(Arguments args) { Log.InfoFormat("Starting update of v{0} to {1}", Constants.ApplicationVersion, args.InstallationPath); var app = new UpdateApplication(); var dispatcher = new UiDispatcher(System.Windows.Threading.Dispatcher.CurrentDispatcher); var window = new UpdaterWindow(new UpdateWindowViewModel(dispatcher, args.InstallationPath)); window.Show(); return app.Run(); }
public UpdateWindowViewModel(UiDispatcher dispatcher, string installationPath) { if (dispatcher == null) throw new ArgumentNullException("dispatcher"); if (installationPath == null) throw new ArgumentNullException("installationPath"); _dispatcher = dispatcher; _installationPath = installationPath; _installer = new Installer(); _installationTask = Task.Factory.StartNew(Installation, TaskCreationOptions.LongRunning); _installationTask.ContinueWith(OnInstallationFinished); }
public static int Start(string[] args) { InstallExceptionHandlers(); Log.InfoFormat("Starting tailviewer..."); Log.InfoFormat("Commandline arguments: {0}", string.Join(" ", args)); LogEnvironment(); ApplicationSettings settings = ApplicationSettings.Create(); bool neededPatching; settings.Restore(out neededPatching); if (neededPatching) { // TODO: Save settings right again to complete the upgrade // (maybe we should preserve an old version) } var actionCenter = new ActionCenter(); using (var taskScheduler = new DefaultTaskScheduler()) using (var dataSources = new DataSources(taskScheduler, settings.DataSources)) using (var updater = new AutoUpdater(actionCenter, settings.AutoUpdate)) { if (args.Length > 0) { var filePath = args[0]; if (File.Exists(filePath)) { // Not only do we want to add this file to the list of data sources, // but we also want to select it so the user can view it immediately, regardless // of what was selected previously. var dataSource = dataSources.AddDataSource(filePath); settings.DataSources.SelectedItem = dataSource.Id; } else { Log.ErrorFormat("File '{0}' does not exist, won't open it!", filePath); } } if (settings.AutoUpdate.CheckForUpdates) { // Our initial check for updates is not due to a user action // and therefore we don't need to show a notification when the // application is up-to-date. updater.CheckForUpdates(addNotificationWhenUpToDate: false); } var quickFilters = new QuickFilters(settings.QuickFilters); actionCenter.Add(Changelog.MostRecent); var application = new App(); Dispatcher dispatcher = Dispatcher.CurrentDispatcher; var uiDispatcher = new UiDispatcher(dispatcher); dispatcher.UnhandledException += actionCenter.ReportUnhandledException; TaskScheduler.UnobservedTaskException += actionCenter.ReportUnhandledException; var window = new MainWindow(settings) { DataContext = new MainWindowViewModel(settings, dataSources, quickFilters, actionCenter, updater, uiDispatcher) }; settings.MainWindow.RestoreTo(window); window.Show(); return application.Run(); } }
private async void OnAlertUpdate(string channel, string data) { UiDispatcher disp = new UiDispatcher(this); disp.Alert = data; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(disp.OnAddAlert)); }
private async void ShowProgress(bool show) { UiDispatcher disp = new UiDispatcher(this); disp.Show = show; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(disp.OnShowDispatched)); }
private async void OnReset() { UiDispatcher disp = new UiDispatcher(this); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(disp.ClearList)); GetKpiList("Sales"); GetKpiList("CashFlow"); GetKpiList("Expense"); }
private async void OnUpdateKPI(ErpKpi kpi) { UiDispatcher disp = new UiDispatcher(this); disp.Item = kpi; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(disp.OnUpdateItem)); }
private void GetKpiList(string channel) { if (_Connected) { ShowProgress(true); Task <IEnumerable<ErpKpi>> task = _Hub.Invoke<IEnumerable<ErpKpi>>("GetAllKPIs", new object[] { channel }); task.Wait(); UiDispatcher disp = new UiDispatcher(this); disp.List = task.Result; Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(disp.OnLoadList)).AsTask().Wait(); ShowProgress(false); } }
private async void ReportChange(StateChange change) { UiDispatcher disp = new UiDispatcher(this, false, "How can I assist you?"); // Set connected state _Connected = (change.NewState == ConnectionState.Connected); // If connected and not welcomed yet if (_Connected && !_Welcome) { // Set state _Welcome = true; // Add text await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(disp.AddConversationText)); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(disp.UpdateState)); }
/* Handle response text from system */ private async void OnResponse(string data) { UiDispatcher state = new UiDispatcher(this); // Check data if (data != null) { UiDispatcher disp = new UiDispatcher(this, false, data); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(disp.AddConversationText)); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(state.UpdateState)); }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { UiDispatcher state = new UiDispatcher(this); // Update the UI state state.UpdateState(); // Create connection _Connection = new HubConnection("http://swmsignalrsite.azurewebsites.net/"); _Connection.StateChanged += change => ReportChange(change); _Connection.Closed += () => ReportClosed(); // Create hub proxy _Hub = _Connection.CreateHubProxy("erpTicker"); _Hub.On<string>("addResponse", data => OnResponse(data)); // Start the connection _Connection.Start(); }
private void ask_Click(object sender, RoutedEventArgs e) { UiDispatcher disp = new UiDispatcher(this, true, request.Text); // Check state with SignalR hub if (_Connected && !_Waiting) { // If text if (!string.IsNullOrEmpty(request.Text)) { // Add the text disp.AddConversationText(); // Invoke the request _Hub.Invoke("sendRequest", new object[] { _Connection.ConnectionId, request.Text }); // Clear the text request.Text = string.Empty; } } }