Пример #1
0
        public Task <MessageResult> ShowAsync(string message, string caption = "", string helpLink                 = null,
                                              MessageButton button           = MessageButton.OK, MessageImage icon = MessageImage.None)
        {
            var tcs = new TaskCompletionSource <MessageResult>();

#pragma warning disable AvoidAsyncVoid
            _dispatcherService.BeginInvoke(async() =>
#pragma warning restore AvoidAsyncVoid
            {
                var previousCursor   = Mouse.OverrideCursor;
                Mouse.OverrideCursor = null;

                var vm = _viewModelFactory.CreateViewModel <HelpLinkMessageBoxViewModel>(null, null);

                vm.Message  = message;
                vm.Button   = button;
                vm.Icon     = icon;
                vm.HelpLink = helpLink;

                vm.SetTitle(caption);

                await _uiVisualizerService.ShowDialogAsync(vm);

                Mouse.OverrideCursor = previousCursor;

                tcs.TrySetResult(vm.Result);
            });

            return(tcs.Task);
        }
Пример #2
0
        public override Task <MessageResult> ShowAsync(string message, string caption = "", MessageButton button = MessageButton.OK, MessageImage icon = MessageImage.None)
        {
            Argument.IsNotNullOrWhitespace("message", message);

            Log.Info("Showing message to the user:\n\n{0}", this.GetAsText(message, button));

            var tcs = new TaskCompletionSource <MessageResult>();

#pragma warning disable AvoidAsyncVoid
            _dispatcherService.BeginInvoke(async() =>
#pragma warning restore AvoidAsyncVoid
            {
                var previousCursor   = Mouse.OverrideCursor;
                Mouse.OverrideCursor = null;

                var vm = _viewModelFactory.CreateViewModel <MessageBoxViewModel>(null, null);

                vm.Message = message;
                vm.Button  = button;
                vm.Icon    = icon;

                vm.SetTitle(caption);

                await _uiVisualizerService.ShowDialogAsync(vm);

                Mouse.OverrideCursor = previousCursor;

                Log.Info("Result of message: {0}", vm.Result);

                tcs.TrySetResult(vm.Result);
            });

            return(tcs.Task);
        }
        public void ClearEntries()
        {
            _isClearingLog = true;

            // Note: we need to dispatch because the FastObservableCollection automatically dispatches (which is a good thing
            // when coming from a background thread). However... the ReplaceRange will be executed *outside* the lock
            // which is not good. So the lock is inside the dispatcher handler, and we manually dispatcher here.
            _dispatcherService.BeginInvoke(() =>
            {
                lock (_lock)
                {
                    _logEntries.Clear();

                    var typeNames = TypeNames;
                    if (typeNames != null)
                    {
                        _isUpdatingTypes = true;

                        using (typeNames.SuspendChangeNotifications())
                        {
                            typeNames.ReplaceRange(new[] { defaultComboBoxItem });
                        }

                        _isUpdatingTypes = false;
                    }
                }

                ResetEntriesCount();

                _isClearingLog = false;
            });
        }
        public void ShowNotification(INotification notification)
        {
            Argument.IsNotNull(() => notification);

            if (IsSuspended)
            {
                Log.Debug("Notifications are suspended, queueing notification");

                _notificationsQueue.Enqueue(notification);

                return;
            }

            _dispatcherService.BeginInvoke(() =>
            {
                EnsureMainWindow();

                var hasActiveWindows = HasActiveWindows();
                if (!hasActiveWindows && notification.Priority <= NotificationPriority.Normal)
                {
                    Log.Debug($"Not showing notification '{notification}' since priority is '{notification.Priority}' and app has no active windows.");
                    return;
                }

                Log.Debug("Showing notification '{0}'", notification);

                var notificationLocation = _notificationPositionService.GetLeftTopCorner(NotificationSize, CurrentNotifications.Count);

                var popup = new Popup();

                popup.AllowsTransparency            = true;
                popup.Placement                     = PlacementMode.Custom;
                popup.CustomPopupPlacementCallback += (popupSize, targetSize, offset) =>
                {
                    var x = DpiHelper.CalculateSize(DpiHelper.DpiX, notificationLocation.X);
                    var y = DpiHelper.CalculateSize(DpiHelper.DpiY, notificationLocation.Y);

                    var popupPlacement = new CustomPopupPlacement(new Point(x, y), PopupPrimaryAxis.None);

                    var ttplaces = new[] { popupPlacement };
                    return(ttplaces);
                };

                var notificationViewModel          = _viewModelFactory.CreateViewModel <NotificationViewModel>(notification, null);
                notificationViewModel.ClosedAsync += async(sender, e) => popup.IsOpen = false;

                var notificationView         = new NotificationView();
                notificationView.DataContext = notificationViewModel;
                notificationView.Unloaded   += OnNotificationViewUnloaded;

                popup.Child = notificationView;

                popup.IsOpen = true;

                OpenedNotification?.Invoke(this, new NotificationEventArgs(notification));

                CurrentNotifications.Add(notification);
            });
        }
 private void OnRunApplicationExecute()
 {
     _dispatcherService.BeginInvoke(async() =>
     {
         _processService.StartProcess(_entryAssembly.Location);
         await CloseViewModelAsync(null);
     });
 }
Пример #6
0
 public static DispatcherOperation BeginInvoke(
     this IDispatcherService dispatcher,
     Action action,
     DispatcherPriority priority
     )
 {
     return(dispatcher.BeginInvoke(action, priority));
 }
Пример #7
0
 private void OnShowInstalledDialogExecute()
 {
     _dispatcherService.BeginInvoke(async() =>
     {
         _uiVisualizerService.ShowDialog <AppInstalledViewModel>();
         await CloseViewModelAsync(null);
     });
 }
Пример #8
0
        private async Task CountAndSearchAsync()
        {
            var selectedRepository = Navigator.SelectedRepository;

            if (selectedRepository is null)
            {
                return;
            }

            try
            {
                _dispatcherService.BeginInvoke(() => SearchResult.PackageList.Clear());

                using (ScopeManager <AuthenticationScope> .GetScopeManager(selectedRepository.Source.GetSafeScopeName(), () => new AuthenticationScope()))
                {
                    using (_pleaseWaitService.WaitingScope())
                    {
                        var searchSettings = SearchSettings;

                        SearchResult.TotalPackagesCount = await TaskHelper.Run(() => _packageQueryService.CountPackages(selectedRepository, searchSettings.SearchFilter, IsPrereleaseAllowed ?? true), true);

                        var packageDetails = await TaskHelper.Run(() => _packageQueryService.GetPackages(selectedRepository, IsPrereleaseAllowed ?? true, searchSettings.SearchFilter, searchSettings.PackagesToSkip), true);

                        var packages = packageDetails;

                        _dispatcherService.BeginInvoke(() =>
                        {
                            using (SearchResult.PackageList.SuspendChangeNotifications())
                            {
                                CollectionExtensions.AddRange(((ICollection <IPackageDetails>)SearchResult.PackageList), packages);
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to search packages");
            }
            finally
            {
                // Note: this is hack
                Navigator.SelectedRepository = selectedRepository;
            }
        }
 Task DoTearDown(IDispatcherService service, IUIAwaiter awaiter, IBenchmarkItem target, object uiControl)
 {
     return(Task.Factory.StartNew(() =>
     {
         using (var token = awaiter.BeginAwaiting(() => target.TearDown(uiControl)))
             service.BeginInvoke(() => token.Run());
         running--;
     }, TaskCreationOptions.LongRunning));
 }
        Task <T> UIOperation <T>(IDispatcherService dispatcher, Func <T> uiOperation)
        {
            var completionSource = new TaskCompletionSource <T>();

            completionSource.Task.ConfigureAwait(false);
            dispatcher.BeginInvoke(() =>
                                   completionSource.SetResult(uiOperation()));
            return(completionSource.Task);
        }
Пример #11
0
        protected override async Task InitializeAsync()
        {
            await base.InitializeAsync();

            if (_injectedValidationContext != null)
            {
                _dispatcherService.BeginInvoke(() => ValidationContext = _injectedValidationContext);
            }
        }
Пример #12
0
 private void OnShowInstalledDialogExecute()
 {
     // Dispatch since we close the vm
     _dispatcherService.BeginInvoke(async() =>
     {
         await _uiVisualizerService.ShowDialogAsync <AppInstalledViewModel>();
         await CloseViewModelAsync(null);
     });
 }
Пример #13
0
        public void ShowNotification(INotification notification)
        {
            Argument.IsNotNull(() => notification);

            if (IsSuspended)
            {
                Log.Debug("Notifications are suspended, queueing notification");

                _notificationsQueue.Enqueue(notification);

                return;
            }

            EnsureMainWindow();

            _dispatcherService.BeginInvoke(() =>
            {
                Log.Debug("Showing notification '{0}'", notification);

                var notificationLocation = _notificationPositionService.GetLeftTopCorner(NotificationSize, CurrentNotifications.Count);

                var popup = new Popup();

                popup.AllowsTransparency            = true;
                popup.Placement                     = PlacementMode.Custom;
                popup.CustomPopupPlacementCallback += (popupSize, targetSize, offset) =>
                {
                    var x = DpiHelper.CalculateSize(DpiHelper.DpiX, notificationLocation.X);
                    var y = DpiHelper.CalculateSize(DpiHelper.DpiY, notificationLocation.Y);

                    var popupPlacement = new CustomPopupPlacement(new Point(x, y), PopupPrimaryAxis.None);

                    var ttplaces = new [] { popupPlacement };
                    return(ttplaces);
                };

                //popup.Placement = PlacementMode.AbsolutePoint;
                //popup.PlacementRectangle = new Rect(notificationLocation.X, notificationLocation.Y, NotificationSize.Width, NotificationSize.Height);

                var notificationViewModel          = _viewModelFactory.CreateViewModel <NotificationViewModel>(notification);
                notificationViewModel.ClosedAsync += async(sender, e) => popup.IsOpen = false;

                // TODO: consider factory
                var notificationView         = new NotificationView();
                notificationView.DataContext = notificationViewModel;
                notificationView.Unloaded   += OnNotificationViewUnloaded;

                popup.Child = notificationView;

                popup.IsOpen = true;

                OpenedNotification.SafeInvoke(this, new NotificationEventArgs(notification));

                CurrentNotifications.Add(notification);
            });
        }
        protected override void Execute(object parameter)
        {
            var pluginsToScan =
                (from plugin in _globalFrontendService.SelectedPlugins where plugin.IsEnabled select plugin).ToList();
            int  addedPresets = 0;
            int  totalPresets = 0;
            bool listExceeded = false;

            _dispatcherService.BeginInvoke(() =>
            {
                foreach (var plugin in pluginsToScan)
                {
                    var hs = new HashSet <Preset>();

                    if (_licenseService.GetPresetExportLimit() > 0)
                    {
                        hs.AddRange(plugin.Presets.Take(_licenseService.GetPresetExportLimit()));

                        if (plugin.Presets.Count > _licenseService.GetPresetExportLimit())
                        {
                            listExceeded = true;
                        }
                    }
                    else
                    {
                        hs.AddRange(plugin.Presets);
                    }

                    hs.ExceptWith(_globalFrontendService.PresetExportList);
                    hs.RemoveWhere(p => !p.IsMetadataModified);

                    _globalFrontendService.PresetExportList.AddItems(hs.ToList());


                    addedPresets += hs.Count;
                    totalPresets += plugin.Presets.Count;
                }
            });

            if (listExceeded)
            {
                MessageBox.Show(
                    $"The trial version is limited to {_licenseService.GetPresetExportLimit()} presets per plugin.");
            }

            var    skippedPresets = totalPresets - addedPresets;
            string report         = $"Added {addedPresets} presets from {pluginsToScan.Count} plugins.";

            if (skippedPresets > 0)
            {
                report += $" Skipped {skippedPresets} presets already on export list or already exported.";
            }

            _applicationService.ReportStatus(report);
            base.Execute(parameter);
        }
Пример #15
0
        /// <summary>
        /// Called when the ribbon is loaded.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        /// <remarks>
        /// This is a workaround. If this code is not used, you will get issues with showing the second contextual tab group.
        /// </remarks>
        private void OnRibbonLoaded(object sender, RoutedEventArgs e)
        {
            _ribbon.Loaded -= OnRibbonLoaded;

            foreach (var group in _ribbon.ContextualGroups)
            {
                group.Visibility = Visibility.Visible;
            }

            _dispatcherService.BeginInvoke(() =>
            {
                foreach (var group in _ribbon.ContextualGroups)
                {
                    group.Visibility = Visibility.Hidden;
                }

                ActivateTabForCurrentlySelectedDocumentView();
            });
        }
 Task <long> DoBehcmark(IDispatcherService service, IUIAwaiter awaiter, IBenchmarkItem target)
 {
     return(Task.Factory.StartNew <long>(() =>
     {
         using (var token = awaiter.BeginAwaiting(() => target.Benchmark())) {
             service.BeginInvoke(() => token.Run());
             return token.ElapsedMilliseconds;
         }
     }, TaskCreationOptions.LongRunning));
 }
Пример #17
0
        private void OnLogMessage(object sender, LogMessageEventArgs e)
        {
            var logEntry = new LogEntry(e);

            if (!logEntry.Data.ContainsKey("ThreadId"))
            {
                logEntry.Data["ThreadId"] = ThreadHelper.GetCurrentThreadId();
            }

            _dispatcherService.BeginInvoke(() => AddLogEntries(new[] { logEntry }), true);
        }
Пример #18
0
        private void OnRunApplicationExecute()
        {
            _dispatcherService.BeginInvoke(() =>
            {
                _processService.StartProcess(_entryAssembly.Location);

#pragma warning disable 4014
                CloseViewModelAsync(null);
#pragma warning restore 4014
            });
        }
Пример #19
0
        private void OnFolderContentChanged(object sender, FolderNodeEventArgs e)
        {
            switch (e.ChangeType)
            {
            case WatcherChangeTypes.Changed:
                _dispatcherService.BeginInvoke(() => OnChanged(e.NewPath));
                break;

            case WatcherChangeTypes.Created:
                _dispatcherService.BeginInvoke(() => OnCreated(e.NewPath));
                break;

            case WatcherChangeTypes.Deleted:
                _dispatcherService.BeginInvoke(() => OnDeleted(e.OldPath));
                break;

            case WatcherChangeTypes.Renamed:
                _dispatcherService.BeginInvoke(() => OnRenamed(e.NewPath, e.OldPath));
                break;
            }
        }
Пример #20
0
 public void OnLoaded()
 {
     unsubscribe = LoggerService.Subscribe(content => {
         DispatcherService.BeginInvoke(() => {
             EventsLog.Add(content.Replace("\r\n", ""));
             if (EventsLog.Count > 25)
             {
                 EventsLog.RemoveAt(0);
             }
         });
     });
 }
Пример #21
0
 private void OnLogMessage(object sender, LogMessageEventArgs e)
 {
     _dispatcherService.BeginInvoke(() =>
     {
         var traceEntries = TraceEntries;
         if (traceEntries != null)
         {
             var traceEntry = new TraceEntry(new LogEntry(e));
             TraceEntries.Add(traceEntry);
         }
     });
 }
Пример #22
0
        /// <summary>
        /// Called when the current location has changed.
        /// </summary>
        protected void RaiseLocationChanged()
        {
            var locationChanged = LocationChanged;

            if (locationChanged != null)
            {
                var currentLocation = GetCurrentLocation();
                var value           = new LocationChangedEventArgs(currentLocation);

                _dispatcherService.BeginInvoke(() => locationChanged(this, value));
            }
        }
Пример #23
0
        private async Task CountAndSearchAsync()
        {
            var selectedRepository = Navigator.SelectedRepository;

            try
            {
                _dispatcherService.BeginInvoke(() => SearchResult.PackageList.Clear());

                using (_pleaseWaitService.WaitingScope())
                {
                    var searchSettings = SearchSettings;
                    searchSettings.PackagesToSkip = 0;

                    SearchResult.TotalPackagesCount = await TaskHelper.Run(() => _packageQueryService.CountPackages(selectedRepository, searchSettings.SearchFilter, IsPrereleaseAllowed ?? true), true);

                    var packageDetails = await TaskHelper.Run(() => _packageQueryService.GetPackages(selectedRepository, IsPrereleaseAllowed ?? true, searchSettings.SearchFilter, searchSettings.PackagesToSkip), true);

                    var packages = packageDetails;

                    _dispatcherService.BeginInvoke(() =>
                    {
                        using (SearchResult.PackageList.SuspendChangeNotifications())
                        {
                            SearchResult.PackageList.AddRange(packages);
                        }
                    });
                }
            }
            catch (Exception exception)
            {
                Log.Error(exception, "Failed to search packages.");
            }
            finally
            {
                // TODO: this is hack. Need to fix it.
                Navigator.SelectedRepository = selectedRepository;
            }
        }
        private void OnRunApplicationExecute()
        {
            _dispatcherService.BeginInvoke(() =>
            {
                var location = _entryAssembly.Location;

                // Note: in .NET Core, entry assembly can be a .dll, make sure to enforce exe
                location = System.IO.Path.ChangeExtension(location, ".exe");

                _processService.StartProcess(location);

#pragma warning disable 4014
                CloseViewModelAsync(null);
#pragma warning restore 4014
            });
        }
Пример #25
0
        /// <summary>
        /// Reports progress on the UI thread.
        /// </summary>
        /// <param name="action">The action.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="action"/> is <c>null</c></exception>
        public void ReportProgress(Action action)
        {
            Argument.IsNotNull("action", action);

            if (!IsExecuting)
            {
                return;
            }

            _dispatcherService.BeginInvoke(() =>
            {
                action();

                RaiseCanExecuteChanged();
            });
        }
Пример #26
0
        private void OnContactsArrived(IEnumerable <Contact> contacts)
        {
            _contacts = new List <Contact>();
            foreach (var item in contacts)
            {
                _contacts.Add(item);
            }

            //raise the property changed on the UI thread
            _dispatcherService.BeginInvoke((Action) delegate
            {
                //notify ui that the contacts data arrived so binding updates
                OnPropertyChanged(() => Contacts);

                //update state
                _stateManager.GoToState("ContactsLoaded");
            });
        }
Пример #27
0
        protected void RaisePropertyChanged(string name)
        {
            _dispatcherService.BeginInvoke(() =>
            {
                PropertyChanged.Raise(this, name);
#if SILVERLIGHT
                PropertyChanged.Raise(this, "");
#endif

                // unit test friendly - bbulla
                if (_propertyMap != null && _propertyMap.ContainsKey(name))
                {
                    _propertyMap[name].Each(this.RaisePropertyChanged);
                }

                ExecuteDependentMethods(name);
                FireChangesOnDependentCommands(name);
            });
        }
Пример #28
0
        private void SetStatus(string status)
        {
            if (!string.IsNullOrWhiteSpace(status))
            {
                var statusLines = status.Split(new[] { "\n", "\r\n", Environment.NewLine },
                                               StringSplitOptions.RemoveEmptyEntries);
                if (statusLines.Length > 0)
                {
                    status = statusLines[0];
                }
            }

            if (_statusBarItem != null)
            {
                _dispatcherService.BeginInvoke(() =>
                {
                    _statusBarItem.SetCurrentValue(StatusBarItem.ValueProperty, status);
                });
            }
        }
Пример #29
0
        private void UpdateValidationResult(NetworkValidationResult networkValidationResult, bool allowToClose = true)
        {
            Argument.IsNotNull(() => networkValidationResult);

            var computerId = _networkLicenseService.ComputerId;

            MaximumNumberOfConcurrentUsages = networkValidationResult.MaximumConcurrentUsers;
            CurrentUsers = (from user in networkValidationResult.CurrentUsers
                            where !string.Equals(user.ComputerId, computerId)
                            select user).ToList();

            if (allowToClose && networkValidationResult.IsValid)
            {
                Log.Info("No longer exceeding maximum concurrent users, closing network license validation");

#pragma warning disable 4014
                _dispatcherService.BeginInvoke(() => this.SaveAndCloseViewModelAsync());
#pragma warning restore 4014
            }
        }
        public async Task DownloadAndRunAsync()
        {
            if (string.IsNullOrWhiteSpace(SupportUrl))
            {
                throw Log.ErrorAndCreateException <InvalidOperationException>("Please initialize the service by setting the SupportUrl property");
            }

            Log.Info("Downloading support app from '{0}'", SupportUrl);

            var webClient = new WebClient();

            webClient.DownloadProgressChanged += OnWebClientOnDownloadProgressChanged;
            webClient.DownloadDataCompleted   += OnWebClientOnDownloadDataCompleted;

            var data = await webClient.DownloadDataTaskAsync(SupportUrl);

            Log.Info("Support app is downloaded, storing file in temporary folder");

            var tempDirectory = Path.Combine(Path.GetTempPath(), "Orc_AutomaticSupport", DateTime.Now.ToString("yyyyMMddHHmmss"));

            if (!Directory.Exists(tempDirectory))
            {
                Directory.CreateDirectory(tempDirectory);
            }

            var tempFile = Path.Combine(tempDirectory, "SupportApp.exe");

            File.WriteAllBytes(tempFile, data);

            Log.Info("Running support app");

            _processService.StartProcess(tempFile, CommandLineParameters, exitCode =>
            {
                _dispatcherService.BeginInvoke(() => SupportAppClosed.SafeInvoke(this));
            });
        }