Example #1
0
        public void Execute(object parameter)
        {
            // Initialize
            _progressDialogViewModel = new ProgressDialogViewModel();
            // Set the view model's token source
            _progressDialogViewModel.TokenSource = new CancellationTokenSource();

            Thread thread = new Thread(new ThreadStart(RunProcess));

            thread.IsBackground = true; //make them a daemon - prevent thread callback issues
            thread.Name         = "DllThread";
            thread.Start();

            _timer.Start();

            Thread.Sleep(200);

            if (_state != StateEnum.Finish)
            {
                // Announce that work is starting
                //_mainViewModel.RaiseWorkStartedEvent();
                _windowService.OpenProgressWindow(_progressDialogViewModel);
            }
            else
            {
            }
        }
    public async Task ProgressDialogViewModel_Cancel()
    {
        var mock = new Mock <IMainModel>();

        mock.SetupGet(x => x.UIScheduler)
        .Returns(new SynchronizationContextScheduler(SynchronizationContext.Current !));

        var subjectProgress = new Subject <ProgressInfo>();

        mock
        .SetupGet(x => x.CurrentProgressInfo)
        .Returns(subjectProgress.ToReadOnlyReactivePropertySlim());

        var cancelToken = new CancellationTokenSource();

        mock
        .SetupGet(x => x.CancelWork)
        .Returns(cancelToken);

        var vm = new ProgressDialogViewModel(mock.Object);

        cancelToken.IsCancellationRequested
        .Should().BeFalse();

        await vm.CancelCommand.ExecuteAsync();

        cancelToken.IsCancellationRequested
        .Should().BeTrue();

        await vm.CancelCommand.ExecuteAsync();

        cancelToken.IsCancellationRequested
        .Should().BeTrue();
    }
Example #3
0
        void OpenServerLogFile(object o)
        {
            WebClient client = new WebClient {
                Credentials = CurrentEnvironment.Connection.HubConnection.Credentials
            };
            var dialog = new ProgressDialog();

            _progressDialogViewModel = new ProgressDialogViewModel(() => { dialog.Close(); }, delegate
            {
                dialog.Show();
            }, delegate
            {
                dialog.Close();
            });
            _progressDialogViewModel.StatusChanged("Server Log File", 0, 0);
            _progressDialogViewModel.SubLabel = "Preparing to download Warewolf Server log file.";
            dialog.DataContext = _progressDialogViewModel;
            _progressDialogViewModel.Show();
            client.DownloadProgressChanged += DownloadProgressChanged;
            client.DownloadFileCompleted   += DownloadFileCompleted;
            var managementServiceUri = WebServer.GetInternalServiceUri("getlogfile", CurrentEnvironment.Connection);
            var tempPath             = Path.GetTempPath();

            _serverLogFile = Path.Combine(tempPath, CurrentEnvironment.Connection.DisplayName + " Server Log.txt");
            client.DownloadFileAsync(managementServiceUri, _serverLogFile);
        }
Example #4
0
        public override async Task ShowMessage(string message, string title)
        {
            var viewModel = new ProgressDialogViewModel
            {
                Report = this.Report,
                Title  = title
            };

            var view = new ProgressDialog
            {
                DataContext = viewModel
            };



            MessageBoxResult result;

            result = (MessageBoxResult)await DialogHost.Show(view, "RootDialog", new DialogOpenedEventHandler((sender, args) =>
            {
                Task.Factory.StartNew(() =>
                {
                    this.Action();

                    if (this.IsAutoClose)
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            DialogHost.CloseDialogCommand.Execute(MessageBoxResult.OK, view);
                        });
                    }
                });
            }));

            this.Result = result;
        }
Example #5
0
        /* This service is nearly identical to ServiceTwo. The only difference in the
         * two classes is that this class takes three times as long to perform its
         * work as ServiceTwo. */

        /// <summary>
        /// Performs a service provided by this class
        /// </summary>
        /// <param name="workList">A list of work items (typically, file paths) to be processed.</param>
        /// <param name="viewModel">The Progress dialog view model for this application.</param>
        public static void DoWork(int[] workList, ProgressDialogViewModel viewModel)
        {
            /* We get a token source from the CancellationTokenSource and
             * wrap it in a Parallel Options object so we can pass it to the
             * Parallel.ForEach() method that will traverse the file list. */

            // Get a cancellation token
            var loopOptions = new ParallelOptions();

            loopOptions.CancellationToken = viewModel.TokenSource.Token;

            /* If the user cancels this task while in progress, the cancellation token passed
             * in will cause an OperationCanceledException to be thrown. We trap the exception
             * and set the Progress dialog view model to display a cancellation message. */

            // Process work items in parallel
            try
            {
                Parallel.ForEach(workList, loopOptions, t => ProcessWorkItem(viewModel));
            }
            catch (OperationCanceledException)
            {
                var ShowCancellationMessage = new Action(viewModel.ShowCancellationMessage);
                Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, ShowCancellationMessage);
            }
        }
 public static ProgressDialog Open(Progress<ProgressDialogState> reporter, Stopwatch stopwatch = null)
 {
     var box = new ProgressDialog();
     var vm = new ProgressDialogViewModel(box, reporter, stopwatch);
     box.DataContext = vm;
     return box;
 }
Example #7
0
        private void ExecuteInternal(Action <CancellationToken, IProgress <ProgressReport> > action,
                                     ProgressDialogOptions options, bool isCancellable = true)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                CancellationToken cancellationToken = cancellationTokenSource.Token;

                var cancelCommand = isCancellable ? new CancelCommand(cancellationTokenSource) : null;

                var viewModel = new ProgressDialogViewModel(
                    options, cancellationToken, cancelCommand);

                var window = new ProgressDialog
                {
                    DataContext = viewModel,
                };

                var task = _taskFactory
                           .StartNew(() => action(cancellationToken, viewModel.Progress),
                                     cancellationToken);

                task.ContinueWith(_ => viewModel.Close = true);

                window.ShowDialog();
            }
        }
Example #8
0
        private static void ProcessEntityItem(KeyValuePair <int, SheetRow> item1, ProgressDialogViewModel viewModel)
        {
            var entityRepository = RepoBuilder.CreateEntityRepo();

            if (item1.Key > 0)
            {
                entityRepository.Add(new Entity()
                {
                    Id           = entityRepository.GetId(),
                    Name         = GetString(item1, 0),
                    Address      = GetString(item1, 1),
                    Town         = GetString(item1, 2),
                    Coord_x      = GetString(item1, 3),
                    Coord_y      = GetString(item1, 4),
                    Organization = GetString(item1, 5),
                    Phone        = GetString(item1, 6),
                    Email        = GetString(item1, 7),
                    Fax          = GetString(item1, 8)
                });
                entityRepository.SubmitChanges();

                var IncrementProgressCounter = new Action <int>(viewModel.IncrementProgressCounter);
                Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, IncrementProgressCounter, 1);
            }
        }
Example #9
0
        public ProgressDialogViewModel OpenProgressWindow(ProgressDialogViewModel vm)
        {
            //var vm = new ProgressDialogViewModel(mainViewModel);
            //vm.Image = captcha.Image;
            // vm.WindowService = this;

            bool?result = null;

            Window activeWindow = ActiveWindow;

            if (activeWindow == null)
            {
                throw new NullReferenceException("ActiveWindow");
            }

            //Application.Current.Dispatcher.Invoke(() =>
            //{
            //Window activeWindow2 = ActiveWindow;

            _viewOfProgress                       = new ProgressDialog();
            _viewOfProgress.Owner                 = activeWindow;
            _viewOfProgress.DataContext           = vm;
            _viewOfProgress.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            ApplyEffect(_viewOfProgress.Owner);
            result = _viewOfProgress.ShowDialog();
            ClearEffect(_viewOfProgress.Owner);
            //}, DispatcherPriority.Normal);

            //view.Activated += (a, b) => { vm.Load(); };
            //view.Closed += (a, b) => { vm.Dispose(); };

            return(result == true ? vm : null);
        }
        public static ProgressDialog Open(Progress <ProgressDialogState> reporter, Stopwatch stopwatch = null)
        {
            var box = new ProgressDialog();
            var vm  = new ProgressDialogViewModel(box, reporter, stopwatch);

            box.DataContext = vm;
            return(box);
        }
        public ProgressDialog()
        {
            InitializeComponent();

            pdvm = new ProgressDialogViewModel();

            DataContext = pdvm;
        }
Example #12
0
        void ProgressDialog_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ProgressDialogViewModel pdvm = (ProgressDialogViewModel)this.DataContext;

            if (pdvm.IsBusy)
            {
                e.Cancel = true;
            }
        }
Example #13
0
        public async Task ShowProgress(string text, WindowType hostIdentifier = WindowType.Root)
        {
            var viewModel = new ProgressDialogViewModel(text);
            var view      = new ProgressDialog {
                ViewModel = viewModel
            };

            await DialogHost.Show(view, Common.GetEnumDescription(hostIdentifier));
        }
Example #14
0
        public ProgressDialog()
        {
            InitializeComponent();
            if (pdvm == null)
            {
                pdvm = new ProgressDialogViewModel();
            }

            DataContext = pdvm;
        }
        public void ProgressDialogViewModel_CancelCommand_CancelCommandExecuted_CallsCancelAction()
        {
            //------------Setup for test--------------------------
            bool cancelActionCalled = false;
            var  vm = new ProgressDialogViewModel(() => { cancelActionCalled = true; }, () => { }, () => { });

            //------------Execute Test---------------------------
            vm.CancelCommand.Execute(null);
            //------------Assert Results-------------------------
            Assert.IsTrue(cancelActionCalled);
        }
        public void ProgressDialogViewModel_Show_Executed_CallsCloseAction()
        {
            //------------Setup for test--------------------------
            var showActionCalled = false;
            var vm = new ProgressDialogViewModel(() => { }, () => { showActionCalled = true; }, () => {});

            //------------Execute Test---------------------------
            vm.Show();
            //------------Assert Results-------------------------
            Assert.IsTrue(showActionCalled);
        }
        void RegisterVMPropertyChangedEventHandlers(ProgressDialogViewModel oldVm, ProgressDialogViewModel newVm)
        {
            if (oldVm != null)
            {
                oldVm.PropertyChanged -= VM_PropertyChanged;
            }

            if (newVm != null)
            {
                newVm.PropertyChanged += VM_PropertyChanged;
            }
        }
        private void VM_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            ProgressDialogViewModel vm = this.DataContext as ProgressDialogViewModel;

            if (vm != null && e.PropertyName == nameof(ProgressDialogViewModel.OperationEnded))
            {
                if (vm.OperationEnded)
                {
                    this.Close();
                }
            }
        }
        public void ProgressDialogViewModel_StartCancel_Exected_SetsSubLabelAndCancelButtonEnabled()
        {
            //------------Setup for test--------------------------
            var vm = new ProgressDialogViewModel(() => { }, () => { }, () => { });

            vm.SubLabel = "Downloading ...";
            vm.IsCancelButtonEnabled = true;
            //------------Execute Test---------------------------
            vm.StartCancel();
            //------------Assert Results-------------------------
            Assert.AreEqual("Please wait while the process is being cancelled...", vm.SubLabel);
            Assert.IsFalse(vm.IsCancelButtonEnabled);
        }
Example #20
0
        private bool TryExecuteInternal <T>(
            Func <CancellationToken, IProgress <ProgressReport>, T> action,
            ProgressDialogOptions options, out T result, bool isCancellable = true)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                CancellationToken cancellationToken = cancellationTokenSource.Token;

                var cancelCommand = isCancellable ? new CancelCommand(cancellationTokenSource) : null;

                var viewModel = new ProgressDialogViewModel(
                    options, cancellationToken, cancelCommand);

                var window = new ProgressDialog
                {
                    DataContext = viewModel
                };

                var task = _taskFactory
                           .StartNew(() => action(cancellationToken, viewModel.Progress),
                                     cancellationToken);

                task.ContinueWith(_ => viewModel.Close = true);

                window.ShowDialog();

                if (task.IsCanceled)
                {
                    result = default(T);
                    return(false);
                }

                if (task.IsCompleted)
                {
                    result = task.Result;
                    return(true);
                }

                result = default(T);
                return(false);
            }
        }
Example #21
0
        public void ShowProgressDialog()
        {
            ProgressDialog = new ProgressDialogViewModel(new ProgressDialogView());
            var cancelAsyncPrintCommand = new DelegateCommand(ExecuteCancelAsyncPrint);

            ProgressDialog.CancelCommand        = cancelAsyncPrintCommand;
            ProgressDialog.MaxProgressValue     = ApproaxNumberOfPages;
            ProgressDialog.CurrentProgressValue = 0;
            ProgressDialog.Message             = GetStatusMessage();
            ProgressDialog.DialogTitle         = "Printing...";
            ProgressDialog.CancelButtonCaption = "Cancel";
            SetProgressDialogCancelButtonVisibility();
            ProgressDialog.Show();
        }
Example #22
0
        public async Task Begin(int count, Action <ProgressStatus> task)
        {
            _action    = task;
            _viewModel = new ProgressDialogViewModel
            {
                Count = count, Progress = 0
            };

            ProgressDialog dialog = new ProgressDialog
            {
                DataContext = _viewModel
            };
            await DialogHost.Show(dialog, _identifier, OpenedEventHandler);
        }
Example #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DialogViewModel"/> class.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="mediaItemMapper">The media item mapper.</param>
        public DialogViewModel(ILocalizationService translator, IYoutubeUrlParseService service, IMediaItemMapper mediaItemMapper, FileSystemViewModel fileSystemViewModel)
        {
            _translator          = translator ?? throw new ArgumentNullException(nameof(translator));
            _service             = service ?? throw new ArgumentNullException(nameof(service));
            _mediaItemMapper     = mediaItemMapper ?? throw new ArgumentNullException(nameof(mediaItemMapper));
            _fileSystemViewModel = fileSystemViewModel ?? throw new ArgumentNullException(nameof(fileSystemViewModel));

            CloseDialogCommand  = new RelayCommand(Close, () => CanClose());
            CancelDialogCommand = new RelayCommand(Cancel, () => CanCancel());
            AcceptDialogCommand = new RelayCommand(Accept, () => CanAccept());

            ExceptionDialogViewModel = new ExceptionDialogViewModel();
            MessageDialogViewModel   = new MessageDialogViewModel();
            ProgressDialogViewModel  = new ProgressDialogViewModel();
        }
        public void ProgressDialogViewModel_StatusChanged_Exected_SetsLabelAndProgressValue()
        {
            //------------Setup for test--------------------------
            var vm = new ProgressDialogViewModel(() => { }, () => { }, () => { });
            //------------Execute Test---------------------------
            const long totalBytes      = 25895554;
            const int  progressPercent = 85;

            vm.Label         = "Warewolf.msi downloaded 60% of 25288 KB";
            vm.ProgressValue = 60;
            vm.StatusChanged("Warewolf.msi", progressPercent, totalBytes);
            //------------Assert Results-------------------------
            Assert.AreEqual("Warewolf.msi downloaded 85% of 25288 KB", vm.Label);
            Assert.AreEqual(progressPercent, vm.ProgressValue);
        }
Example #25
0
        /// <summary>
        /// Call this method from UI thread. It has code at the beginning which needs to run
        /// in UI thread and then awaits the async operation.
        /// </summary>
        /// <param name="asyncAction"></param>
        /// <returns></returns>
        public static async Task <bool> StartActionWithProgress(Func <CancellationToken, Task> asyncAction, bool sendNotificationOnError = true)
        {
            bool error = false;

            var dialogServiceVm = DependencyContainer.Get <DialogServiceViewModel>();
            NotificationService notificationService = null;

            if (sendNotificationOnError)
            {
                notificationService = DependencyContainer.Get <NotificationService>();
            }

            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken       ct  = cts.Token;

            ProgressDialogViewModel progressVm = new ProgressDialogViewModel(cts);

            dialogServiceVm.ShowProgressDialog(progressVm);

            try
            {
                await asyncAction(ct);
            }
            catch (Exception ex)
            {
                error = true;

                if (sendNotificationOnError)
                {
                    Notification notification = new Notification(NotificationTypeEnum.Error, "Operation failed.", ex);
                    notificationService.AddNotification(notification);
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                progressVm.OperationEnded = true;
            }

            if (error)
            {
                return(false);
            }
            return(true);
        }
Example #26
0
        /// <summary>
        /// Open progress window.
        /// </summary>
        /// <param name="viewModel"></param>
        public void OpenProgressWindow(ProgressDialogViewModel viewModel = null)
        {
            if (ProgressWindow.Window != null)
            {
                return;
            }

            ProgressWindow.Window = new ProgressWindow();

            if (viewModel != null)
            {
                ((ProgressWindowViewModel)ProgressWindow.Window.DataContext).VM = viewModel;
            }

            ProgressWindow.Window.Show();
        }
      public void DoDragDrop(List <IEntry> entries)
      {
          VirtualFileDataObject virtualFileDataObject = new VirtualFileDataObject(StartDragDrop, EndDragDrop);
          var files = new List <VirtualFileDataObject.FileDescriptor>();

          string currentDir = Utils.CurrentWindow.CurrentDir;

          foreach (var entry in entries)
          {
              if (entry is FileEntry file)
              {
                  PopulateFile(files, file, currentDir);
              }
              else if (entry is FolderEntry folder)
              {
                  PopulateFiles(files, folder, currentDir);
              }
          }

          //Show dialog only when there are more than 5 items moved.
          Console.WriteLine("Beginning with {0} files", files.Count);
          virtualFileDataObject.SetData(files);

          if (files.Count > 10)
          {
              Aggregator = new EventAggregator();
              Aggregator.GetEvent <StartProgress>().Subscribe(() =>
                {
                    var pms = new DialogParameters();
                    pms.Add("ProgressAction", new Action <ProgressDialogViewModel>(dialog => {
                        Progress = dialog;
                    }));

                    Utils.ShowDialog("ProgressDialog", pms);
                }, ThreadOption.UIThread);
          }

          try
          {
              VirtualFileDataObject.DoDragDrop(Control, virtualFileDataObject, DragDropEffects.Copy);
          }
          catch (COMException)
          {
              Console.WriteLine("Failed Drag-Drop.");
          }
          Console.WriteLine("Finished Drag-Drop operation setup");
      }
Example #28
0
        public void ShowProgressAndContinue(string text, WindowType hostIdentifier = WindowType.Root)
        {
            var viewModel = new ProgressDialogViewModel(text);
            var view      = new ProgressDialog {
                ViewModel = viewModel
            };

            DialogHost.Show(view, Common.GetEnumDescription(hostIdentifier));

            //var cts = new CancellationTokenSource();

            //await Task.Factory.StartNew(async () =>
            //{
            //    await DialogHost.Show(view, Common.GetEnumDescription(hostIdentifier));
            //}, cts.Token);

            //cts.CancelAfter(50000);
        }
Example #29
0
        public DialogViewModel(ILocalizationService translator, IYoutubeUrlParser service, IMediaItemMapper mediaItemMapper, IMessenger messenger, FileSystemViewModel fileSystemViewModel, Func <CreateMediaItem> createMediaItemFactory)
        {
            _translator             = translator ?? throw new ArgumentNullException(nameof(translator), $"{nameof(translator)} {Resources.IsRequired}");
            _service                = service ?? throw new ArgumentNullException(nameof(service), $"{nameof(service)} {Resources.IsRequired}");
            _mediaItemMapper        = mediaItemMapper ?? throw new ArgumentNullException(nameof(mediaItemMapper), $"{nameof(mediaItemMapper)} {Resources.IsRequired}");
            _fileSystemViewModel    = fileSystemViewModel ?? throw new ArgumentNullException(nameof(fileSystemViewModel), $"{nameof(fileSystemViewModel)} {Resources.IsRequired}");
            _messenger              = messenger ?? throw new ArgumentNullException(nameof(messenger), $"{nameof(messenger)} {Resources.IsRequired}");
            _createMediaItemFactory = createMediaItemFactory ?? throw new ArgumentNullException(nameof(createMediaItemFactory), $"{nameof(createMediaItemFactory)} {Resources.IsRequired}");


            CloseDialogCommand  = new RelayCommand(Close, () => CanClose());
            CancelDialogCommand = new RelayCommand(Cancel, () => CanCancel());
            AcceptDialogCommand = new RelayCommand(Accept, () => CanAccept());

            ExceptionDialogViewModel = new ExceptionDialogViewModel();
            MessageDialogViewModel   = new MessageDialogViewModel();
            ProgressDialogViewModel  = new ProgressDialogViewModel();
        }
Example #30
0
        /// <summary>
        /// Processes an item in the work list passed into this service.
        /// </summary>
        private static void ProcessWorkItem(ProgressDialogViewModel viewModel)
        {
            /* We don't perform any real work here. Instead, we simply kill time for
             * 300 milliseconds. */

            // Simulate a time-consuming task
            //Thread.Sleep(300);

            /* Since this code is being executed on a backgound thread, we use the
             * application Dispatcher to call a view model method on the main (UI)
             * thread. Note that we increment the progress counter by three clicks,
             * since each work item takes three times as long to process as each
             * ServiceTwo work item. */

            // Increment progress counter
            var IncrementProgressCounter = new Action <int>(viewModel.IncrementProgressCounter);

            Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, IncrementProgressCounter, 3);
        }
Example #31
0
        async private Task ExecuteAsyncInternal(
            Func <CancellationToken, IProgress <ProgressReport>, Task> action,
            ProgressDialogOptions options, bool isCancellable = true)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                CancellationToken cancellationToken = cancellationTokenSource.Token;

                var cancelCommand = isCancellable ? new CancelCommand(cancellationTokenSource) : null;

                var viewModel = new ProgressDialogViewModel(
                    options, cancellationToken, cancelCommand);

                var window = new ProgressDialog
                {
                    DataContext = viewModel
                };

                Task task = action(cancellationToken, viewModel.Progress);

#pragma warning disable 4014
                task.ContinueWith(_ => viewModel.Close = true);
#pragma warning restore 4014

                window.ShowDialog();

                await task;
            }
        }