private void Loaded() { if (AccountStorage.Accounts.Count() == 0) { this.InputBlockViewModel.ShowConfig(); } var n = NotifyStorage.NotifyManually("タブとカラムを読み込んでいます。しばらくお待ちください..."); DispatcherHelper.BeginInvoke(() => { try { if (Setting.Instance.StateProperty.TabInformations != null) { Setting.Instance.StateProperty.TabInformations.ForEach(c => { var column = this.ColumnOwnerViewModel.CreateColumn(); c.ForEach(p => column.AddTab(p)); }); this.ColumnOwnerViewModel.GCColumn(); } } finally { n.Dispose(); Initializer.StandbyApp(); } }); }
private void BeginAuthorize() { this.IsStandby = false; Task.Factory.StartNew(() => { try { string token = null; var uri = ApiHelper.ExecApi(() => this._credentialCore.GetProviderAuthUrl(out token)); if (uri == null || String.IsNullOrEmpty(token)) { throw new Exception("リターン情報が空です。(uri:" + (uri == null ? "NULL" : uri.OriginalString) + " / token: " + token); } this.requestToken = token; Browser.Start(uri.OriginalString); } catch (Exception e) { DispatcherHelper.BeginInvoke(() => this.Messenger.Raise(new InformationMessage( "認証を開始できませんでした。" + Environment.NewLine + "もう一度試してください。" + Environment.NewLine + "エラー: " + e.Message, "認証開始エラー", System.Windows.MessageBoxImage.Error, "Inform"))); } finally { this.IsStandby = true; } }); }
/// <summary> /// 通知を発行する /// </summary> private static void IssueNotification(UserViewModel source, UserViewModel target, string text, EventKind eventKind, string soundPath = null) { if (Setting.Instance.StateProperty.IsInSilentMode) { return; } if (Setting.Instance.NotificationProperty.WindowNotificationStrategy != Configuration.Settings.NotificationStrategy.Disabled) { DispatcherHelper.BeginInvoke(() => { try { if (Setting.Instance.NotificationProperty.WindowNotificationStrategy == Configuration.Settings.NotificationStrategy.OnlyInactive && Application.Current.MainWindow.IsActive) { return; } } catch (NullReferenceException nrex) { throw new NullReferenceException("Rewrap(BEFORE-1)", nrex); } try { var nvm = new NotificationViewModel( Core.KernelService.MainWindowViewModel, source, target, text, eventKind); Core.KernelService.MainWindowViewModel.Messenger.Raise( new TransitionMessage(nvm, TransitionMode.Normal, "Notification")); } catch (NullReferenceException nrex) { throw new NullReferenceException("Rewrap(BEFORE-2)", nrex); } }); } if (Setting.Instance.NotificationProperty.SoundNotificationStrategy != Configuration.Settings.NotificationStrategy.Disabled) { DispatcherHelper.BeginInvoke(() => { try { if (Setting.Instance.NotificationProperty.SoundNotificationStrategy == Configuration.Settings.NotificationStrategy.OnlyInactive && Application.Current.MainWindow.IsActive) { return; } PlaySound(eventKind, soundPath); } catch (NullReferenceException nrex) { throw new NullReferenceException("Rewrap (AFTER)", nrex); } }, System.Windows.Threading.DispatcherPriority.Background); } }
private void ValidatePin() { this.IsStandby = false; Task.Factory.StartNew(() => { try { long userId; string userScreenName; if (this._credentialCore.GetAccessToken( this.requestToken, this.PinString, out userId, out userScreenName) && userId != 0) { this._credentialCore.NumericId = userId; this._credentialCore.ScreenName = userScreenName; this.Success = true; DispatcherHelper.BeginInvoke(() => Messenger.Raise(new WindowActionMessage("Close", WindowAction.Close))); } else { requestToken = String.Empty; PinString = String.Empty; throw new Exception("認証に失敗しました。PINの入力ミスの可能性があります。"); } } catch (WebException wex) { string errormsg = string.Empty; if (wex.Response != null) { using (var sr = new StreamReader(wex.Response.GetResponseStream())) { errormsg = sr.ReadToEnd(); } } else { errormsg = "データはありません。"; } DispatcherHelper.BeginInvoke(() => Messenger.Raise(new InformationMessage( "認証に失敗しました。もう一度やり直してください。" + Environment.NewLine + "エラーデータ:" + errormsg + Environment.NewLine + wex.Message, "認証エラー", System.Windows.MessageBoxImage.Error, "Inform"))); } catch (Exception ex) { DispatcherHelper.BeginInvoke(() => Messenger.Raise(new InformationMessage( "認証に失敗しました。もう一度やり直してください。" + Environment.NewLine + ex.Message, "認証エラー", System.Windows.MessageBoxImage.Error, "Inform"))); } finally { this.IsStandby = true; } }); }
protected void RaiseCollectionChanged(NotifyCollectionChangedEventArgs args) { var handler = CollectionChanged; if (handler != null) { DispatcherHelper.BeginInvoke(() => handler(this, args)); } }
private void BaseEditOnGotFocus(object sender, RoutedEventArgs routedEventArgs) { var baseEdit = sender as BaseEdit; if (baseEdit == null) { return; } DispatcherHelper.BeginInvoke((Action)(baseEdit.SelectAll)); }
public void ShowR4SCandidateDialog(UserViewModel userViewModel, string receiver, string description) { DispatcherHelper.BeginInvoke(() => { var r4svm = new R4SDialogViewModel(userViewModel, receiver, description); var r4s = new R4SDialog(); r4s.DataContext = r4svm; r4s.Owner = Application.Current.MainWindow; r4s.ShowDialog(); }); }
/// <summary> /// Notifies the Messenger that the lists of recipients should be scanned and cleaned up. /// </summary> /// <remarks> /// Since recipients are stored as <see cref="WeakReference" />, recipients can be garbage collected even though the /// Messenger keeps /// them in a list. During the cleanup operation, all "dead" recipients are removed from the lists. Since this operation /// can take a moment, it is only executed when the application is idle. For this reason, a user of the Messenger class /// should use /// <see cref="RequestCleanup" /> instead of forcing one with the <see cref="Cleanup" /> method. /// </remarks> public void RequestCleanup() { if (_isCleanupRegistered) { return; } Action cleanupAction = Cleanup; DispatcherHelper.BeginInvoke(cleanupAction, DispatcherPriority.ApplicationIdle); _isCleanupRegistered = true; }
public void Retry() { this.DoWork().ContinueWith(t => { if (t.Result) { Thread.Sleep(Setting.Instance.ExperienceProperty.PostFinishShowLength); DispatcherHelper.BeginInvoke(() => parent.UpdateWorkers.Remove(this)); } }); }
private void UpdateSysEnvironmentInfo(DbSysInfo sysdbinfo) { if (sysdbinfo == null) { SysEnvironmentInfo = SysDbInfoNone; } else { var version = string.IsNullOrEmpty(sysdbinfo.Version) ? SysDbInfoNone : sysdbinfo.Version; SysEnvironmentInfo = string.Format("{0}", version); } DispatcherHelper.BeginInvoke(new Action(ValidateWorker)); }
private void RefreshInfo() { IsStandby = false; Task.Factory.StartNew(() => { UserInformationManager.ReceiveInidividualInfo(Info); DispatcherHelper.BeginInvoke(() => { IsStandby = true; RefreshUserData(); }); }, TaskCreationOptions.LongRunning); }
/// <summary> /// Sets the <see cref="ItemsView" /> and hooks all needed logic in. /// </summary> /// <param name="view">The view to apply.</param> private void SetItemsView(ListCollectionView view) { DispatcherHelper.BeginInvoke(() => ItemsView = view); // inform about the change ItemsViewChanged?.Invoke(this, EventArgs.Empty); if (ItemsView == null) { // very strange because it indicates that GetDefaultView could not be casted to ListCollectionView return; } // ensure that the CurrentItem property will notify about the fact that the view changed it's current item ItemsView.CurrentChanged += (s, e) => { OnPropertyChanged(nameof(CurrentItem)); }; }
protected void RaiseCollectionChanged(NotifyCollectionChangedEventArgs e) { var handler = this.CollectionChanged; if (handler != null) { DispatcherHelper.BeginInvoke(() => { try { handler(this, e); } catch { } }); } }
private void UpdateCurrentToken() { if (this.inputTextBox.CaretIndex < this.tokenStartPoint) { IsOpening = false; } else { var text = this.inputTextBox.Text; var ctoken = this.GetToken(text, this.inputTextBox.CaretIndex); var otoken = this.GetToken(text, this.tokenStartPoint); if (ctoken != otoken) { // 有効範囲が変わりました IsOpening = false; } else { ViewModel.CurrentToken = ctoken; // 現在のトークン更新で表示要素が無くなったら閉じる // or トークン長がIntelliSenseサジェストアイテムの最大長を上回ったら閉じる if (ViewModel.FilteredItems == null || ViewModel.FilteredItems.Count() == 0 || ctoken.Length > ViewModel.FilteredItems.Select(t => t.ItemText.Length).Max()) { IsOpening = false; } else { // 最も近いものを選択する string cstr; var nearidx = GetNearestIndex(ctoken, out cstr); if (nearidx == -1) { this.intelliSenseList.SelectedIndex = 0; DispatcherHelper.BeginInvoke(() => this.intelliSenseList.SelectedIndex = -1); } else { this.intelliSenseList.SelectedIndex = nearidx; } } } } }
private ConversationViewModel GetConversationModel(string userName, IChatRoom room = null, bool roomMode = true) { var cm = ConversationItems.FirstOrDefault(i => i.GetUniqueName().EqIgnoreCase(userName)); if (cm != null) { return(cm); } var r = room ?? _jabber.GetRoom(userName); if (r == null) { return(null); } var conversation = new ConversationViewModel(userName, room, roomMode); DispatcherHelper.BeginInvoke(new Action(() => ConversationItems.Add(conversation))); return(conversation); }
public void ApplyFollowing(Action callback) { IsCommunicating = true; Task.Factory.StartNew(() => { try { Parallel.ForEach(Relations, r => r.CommitRelation()); } finally { DispatcherHelper.BeginInvoke(() => { IsCommunicating = false; callback(); }); } }); }
/// <summary> /// コマンドが実行可能かどうかが変化した時に呼び出されます。 /// </summary> protected void OnCanExecuteChanged() { foreach (var handlerWeakReference in _canExecuteChangedHandlers.ToList()) { EventHandler result; if (handlerWeakReference.TryGetTarget(out result)) { #if NET4 DispatcherHelper.BeginInvoke(() => result(this, EventArgs.Empty)); #elif NET45 DispatcherHelper.UIDispatcher.InvokeAsync(() => result(this, EventArgs.Empty)); #endif } else { _canExecuteChangedHandlers.Remove(handlerWeakReference); } } }
private void _room_Presence(string from, string status) { if (!RoomMode && from != _uniqueName) { return; } switch (status) { case "offline": var user = ConversationItems.FirstOrDefault(i => i.UserName.EqIgnoreCase(from)); if (user != null) { DispatcherHelper.BeginInvoke(new Action(() => ConversationItems.Remove(user))); //INFO: если были не просмотренные сообщения, то покажем их var receivedMess = _room.GetMessages(user.UserName); if (receivedMess.Any(i => i.State == MsgState.Received)) { OnPrivateChatWindowInternal(user.UserName); } } break; case "online": DispatcherHelper.BeginInvoke( new Action( () => ConversationItems.Add(new JidItem() { UserName = from, GroupName = _uniqueName, Status = status }))); break; default: break; } RefreshContent(); }
private static void FilterControlPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { if (e.NewValue == null) { return; } var filterControl = (FilterControl)e.NewValue; //INFO: вызывается 100500 раз на каждый чих //filterControl.LayoutUpdated += (s, a) => CheckFilterCriteria(filterControl); filterControl.DataContextChanged += (s, a) => { var obj = a.NewValue as INotifyPropertyChanged; if (obj != null) { obj.PropertyChanged += (o, n) => { DispatcherHelper.BeginInvoke(() => { CheckFilterCriteria(filterControl); }, DispatcherPriority.ApplicationIdle); } } ; }; }
private void UpdateAccountImages() { IEnumerable <AccountInfo> currentTarget = null; if (this.overrideTargets != null) { currentTarget = this.overrideTargets; } else { currentTarget = this.UserSelectorViewModel.LinkElements; } if (currentTarget != null) { currentTarget = AccountStorage.Accounts.Where(i => currentTarget.Contains(i)).ToArray(); } Task.Factory.StartNew(() => { var profimgs = currentTarget.Select(ai => ai.ProfileImage).ToArray(); DispatcherHelper.BeginInvoke(() => ImageStackingViewViewModel.ImageUrls = profimgs); }); RaisePropertyChanged(() => IsSelectedAccountEmpty); }
private static void ShowEntityCardGeneric <T>(BusinessEntityDescriptor entityDescriptor) { var viewService = IoC.Instance.Resolve <IViewService>(); var viewModel = IoC.Instance.Resolve <IObjectViewModel <T> >(); var mgr = IoC.Instance.Resolve <IBaseManager <T> >(); object id; var pkType = entityDescriptor.PrimaryKeyDatatype.ToLower().Replace("system.", ""); switch (pkType) { case "decimal": id = Convert.ToDecimal(entityDescriptor.PrimaryKeyValue); break; case "string": id = entityDescriptor.PrimaryKeyValue; break; default: throw new SystemException("This pkType is not supported yet: " + entityDescriptor.PrimaryKeyDatatype); } var source = mgr.Get(id, GetModeEnum.Partial); if (source == null) { throw new SystemException("source entity instance cannot be found. entityType: " + entityDescriptor.EntityType + ", pkValue: " + entityDescriptor.PrimaryKeyValue); } viewModel.SetSource(source); viewService.Show(viewModel, new ShowContext { DockingType = DockType.Document, ShowInNewWindow = false }); DispatcherHelper.BeginInvoke(new Action(() => Application.Current.MainWindow.Activate())); }
private void AddUpdateWorker(TweetWorker w, AccountInfo fallbackOriginal) { if (fallbackOriginal == null) { fallbackOriginal = w.AccountInfo; } else if (fallbackOriginal == w.AccountInfo) { ExceptionStorage.Register(new InvalidOperationException("フォールバックがループしています。"), ExceptionCategory.ConfigurationError); return; } DispatcherHelper.BeginInvoke(() => this._updateWorkers.Add(w)); w.fallbackOriginalAccount = fallbackOriginal; w.RemoveRequired += () => DispatcherHelper.BeginInvoke(() => this._updateWorkers.Remove(w)); w.FallbackRequired += new Action <TweetWorker>(fw => AddUpdateWorker(fw, fallbackOriginal)); w.DoWork().ContinueWith(t => { if (t.Result) { Thread.Sleep(Setting.Instance.ExperienceProperty.PostFinishShowLength); DispatcherHelper.BeginInvoke(() => this._updateWorkers.Remove(w)); } }); }
private void Monitor_OnUpdateLog(object sender, UpdateLogEventArgs e) { var isScrolledToEnd = _mainWindowVm.IsScrolledToEnd; DispatcherHelper.BeginInvoke(() => ScrollToEnd(isScrolledToEnd)); }
private void OnSourceUpdateCompleted(object sender, EventArgs eventArgs) { // т.к. мы не знаем откуда пришло событие - на всякий случай делаем безопасный вызов DispatcherHelper.BeginInvoke(new Action(() => objectListGridControl.EndDataUpdate())); //DispatcherHelper.BeginInvoke(new Action(() => objectListGridControl.SelectedItems.Clear())); }
private void Cancel() { DispatcherHelper.BeginInvoke(() => Messenger.Raise(new WindowActionMessage("Close", WindowAction.Close))); }
protected override void Execute(NativeActivityContext context) { if (!IsEnabled.Get(context)) { return; } var datacontext = context.DataContext; var properties = datacontext.GetProperties(); Action <IBaseManager, NotifyCollectionChangedAction, IList> ivokeHandler = (mngInstance, chngAction, data) => { DispatcherHelper.BeginInvoke(new Action(() => { mngInstance.RiseManagerChanged(chngAction, data); })); }; var mto = IoC.Instance.Resolve <IManagerForObject>(); foreach (var entity in EntityTypes) { if (string.IsNullOrEmpty(entity.Name)) { continue; } var type = mto.GetTypeByName(entity.Name); if (type == null) { throw new DeveloperException("Unknown source type '{0}'.", entity.Name); } var mgrType = mto.GetManagerByTypeName(type.Name); if (mgrType == null) { throw new DeveloperException(string.Format("Unknown source type '{0}'.", type.Name)); } using (var managerInstance = IoC.Instance.Resolve(mgrType, null) as IBaseManager) { if (managerInstance == null) { throw new DeveloperException(string.Format("Can't resolve IBaseManager by '{0}'.", mgrType.Name)); } if (!string.IsNullOrEmpty(entity.Caption) && entity.Value != null) { var action = (RefreshAction)Enum.Parse(typeof(RefreshAction), entity.Value.ToString()); if (action != RefreshAction.Changed) { var prop = properties.Find(entity.Caption, true); if (prop != null) { var ld = prop.GetValue(datacontext); if (ld != null) { var listData = ld as IList; switch (action) { case RefreshAction.InsertOrUpdate: //managerInstance.RiseManagerChanged(NotifyCollectionChangedAction.Add, listData); ivokeHandler(managerInstance, NotifyCollectionChangedAction.Add, listData); break; case RefreshAction.Remove: //managerInstance.RiseManagerChanged(NotifyCollectionChangedAction.Remove, listData); ivokeHandler(managerInstance, NotifyCollectionChangedAction.Remove, listData); break; } continue; } } } } managerInstance.RiseManagerChanged(); } } }
/// <summary> /// Internal representation of the job logic. /// </summary> private async Task Run() { var runs = 0; var shouldRun = true; var overallWatch = new Stopwatch(); var portWatch = new Stopwatch(); overallWatch.Start(); while (!_tokenSource.IsCancellationRequested && shouldRun) { runs++; State = JobStateEnum.Running; JobDefinition.TargetPorts.ToList().ForEach( port => { try { var runResult = new JobSingleRunModel { Tcp = JobDefinition.Tcp, Udp = JobDefinition.Udp, Port = port }; portWatch.Restart(); runResult.PortReached = NetworkUtil.IsPortOpened(JobDefinition.TargetAddess, port, (int)JobDefinition.Timeout.TotalSeconds, JobDefinition.Udp); portWatch.Stop(); runResult.Duration = portWatch.Elapsed; if (JobDefinition.ResolveAddress) { // job should try to resolve ip address Dns.BeginGetHostEntry( JobDefinition.TargetAddess, ar => { IPHostEntry firstNetworkAddress = null; try { firstNetworkAddress = Dns.EndGetHostEntry(ar); } catch { // empty catch } if (firstNetworkAddress == null || !firstNetworkAddress.AddressList.Any()) { return; } runResult.ResolvedAddress = firstNetworkAddress.AddressList[0].ToString(); }, null); } DispatcherHelper.BeginInvoke(() => Result.Runs.Add(runResult)); ResultReceived?.Invoke(this, new JobResultEventArgs(runResult)); if (runResult.PortReached && JobDefinition.AutoStop) { // the port is reached and autostop is on shouldRun = false; return; } if (JobDefinition.MaxTries.HasValue && JobDefinition.MaxTries.Value <= runs) { // the maximum amount of tries is reached shouldRun = false; return; } if (JobDefinition.MaxRuntime.HasValue && JobDefinition.MaxRuntime.Value <= overallWatch.Elapsed) { // maximum runtime is reached shouldRun = false; return; } // inform callers that there is a new result // ReSharper disable once ExplicitCallerInfoArgument OnPropertyChanged(nameof(Result)); } catch (Exception ex) { // TODO } }); State = JobStateEnum.Waiting; await Task.Delay(JobDefinition.WaitTime, CancellationToken.None); } overallWatch.Stop(); }
private void ValueChangedRowCount(object sender, EditValueChangedEventArgs e) { DispatcherHelper.BeginInvoke((ThreadStart)(() => TextRowCount.Focus())); }
/// <summary> /// ユーザーを設定します。<para /> /// NullかString.Emptyが指定されると、ユーザー編集モードに入ります。 /// </summary> internal void SetUser(string screenName) { if (String.IsNullOrEmpty(screenName)) { User = null; InputMode = true; this.Messenger.Raise(new Livet.Messaging.InteractionMessage("FocusToInput")); } else { InputMode = false; screenName = screenName.TrimStart('@', ' ', '\t'); this.IsStandby = false; Task.Factory.StartNew(() => { try { var user = UserStorage.Lookup(screenName); if (user == null) { var cred = AccountStorage.GetRandom(); if (cred != null) { var ud = ApiHelper.ExecApi(() => cred.GetUserByScreenName(screenName)); if (ud == null) { DispatcherHelper.BeginInvoke(() => this.Messenger.Raise(new Livet.Messaging.InformationMessage( "ユーザー @" + screenName + " の情報を取得できません。" + Environment.NewLine + "ユーザーが存在しない可能性があります。", "ユーザー情報取得エラー", System.Windows.MessageBoxImage.Warning, "InformationMessage"))); this.User = null; return; } else { user = UserStorage.Get(ud); } } } if (user == null) { throw new Exception("ユーザー情報がありません。"); } User = user; } catch (Exception e) { ExceptionStorage.Register(e, ExceptionCategory.TwitterError, "ユーザー @" + screenName + " の情報を取得できませんでした。"); DispatcherHelper.BeginInvoke(() => this.Messenger.Raise(new Livet.Messaging.InformationMessage( "ユーザー @" + screenName + "の情報を取得できません。", "ユーザー情報取得エラー", System.Windows.MessageBoxImage.Warning, "InformationMessage"))); this.User = null; } finally { IsStandby = true; } }); } }