Example #1
0
 private static TResult PushFrame <TResult>([NotNull] IDispatcherService dispatcher, Func <Task <TResult> > task)
 {
     return(dispatcher.Invoke(() =>
     {
         var frame = new DispatcherFrame();
         var frameTask = task().ContinueWith(x => { frame.Continue = false; return x.Result; });
         ComponentDispatcher.PushModal();
         Dispatcher.PushFrame(frame);
         ComponentDispatcher.PopModal();
         return frameTask.Result;
     }));
 }
Example #2
0
        /// <summary>
        /// Writes a line to the output window.
        /// </summary>
        /// <param name="message">Message to write.</param>
        /// <param name="eventType">Type of the event.</param>
        private void WriteLine(string message, TraceEventType eventType)
        {
            _dispatcherService.Invoke(() =>
            {
                var traceEntry = new TraceEntry(TraceHelper.ConvertTraceEventTypeToTraceLevel(eventType), message);
                _traceEntries.Add(traceEntry);

                if (EntryMatchesLevel(traceEntry))
                {
                    TraceEntryCollection.Add(traceEntry);
                }
            });
        }
Example #3
0
        private async Task OnRemoveExecuteAsync()
        {
            var selectedPerson = SelectedPerson;

            if (await _messageService.ShowAsync(string.Format("Are you sure you want to remove person '{0}'?", selectedPerson), "Are you sure?", MessageButton.YesNo, MessageImage.Question) == MessageResult.Yes)
            {
                Log.Info("Removing person '{0}'", selectedPerson);

                _dispatcherService.Invoke(() =>
                {
                    Persons.Remove(selectedPerson);
                    SelectedPerson = Persons.FirstOrDefault();
                }, true);
            }
        }
Example #4
0
        internal static async Task DownloadAndInstallNewVersion(IDispatcherService dispatcher, IDialogService dialogService, string strideInstallerUrl)
        {
            try
            {
                // Diplay progress window
                var mainWindow = dispatcher.Invoke(() => Application.Current.MainWindow as LauncherWindow);
                dispatcher.InvokeAsync(() =>
                {
                    selfUpdateWindow = new SelfUpdateWindow {
                        Owner = mainWindow
                    };
                    selfUpdateWindow.LockWindow();
                    selfUpdateWindow.ShowDialog();
                }).Forget();


                var strideInstaller = Path.Combine(Path.GetTempPath(), $"StrideSetup-{Guid.NewGuid()}.exe");
                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadFile(strideInstallerUrl, strideInstaller);
                }

                var startInfo = new ProcessStartInfo(strideInstaller)
                {
                    UseShellExecute = true
                };
                // Release the mutex before starting the new process
                Launcher.Mutex.Dispose();

                Process.Start(startInfo);

                Environment.Exit(0);
            }
            catch (Exception e)
            {
                await dispatcher.InvokeAsync(() =>
                {
                    if (selfUpdateWindow != null)
                    {
                        selfUpdateWindow.ForceClose();
                    }
                });

                await dialogService.MessageBox(string.Format(Strings.NewVersionDownloadError, e.Message), MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #5
0
    /// <summary>
    /// fires the property changed event
    /// </summary>
    /// <param name="value"></param>
    protected void RaisePropertyChanged <T>(Expression <Func <T> > propertyExpression)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;

        if (handler != null)
        {
            MemberExpression memberExpression = propertyExpression.Body as MemberExpression;
            if (memberExpression != null)
            {
                dispatcher.Invoke(() =>
                                  handler(this, new PropertyChangedEventArgs(memberExpression.Member.Name))
                                  );
            }
            else
            {
                throw new ArgumentException("RaisePropertyChanged event was not raised with a property: " + propertyExpression);
            }
        }
    }
Example #6
0
        private void OnRemoveExecute()
        {
            var selectedPerson = SelectedPerson;

            var task = _messageService.Show(string.Format("Are you sure you want to remove person '{0}'?", selectedPerson), "Are you sure?", MessageButton.YesNo, MessageImage.Question);

            task.ContinueWith(result =>
            {
                if (result.Result == MessageResult.Yes)
                {
                    Log.Info("Removing person '{0}'", selectedPerson);

                    _dispatcherService.Invoke(() =>
                    {
                        Persons.Remove(selectedPerson);
                        SelectedPerson = Persons.FirstOrDefault();
                    });
                }
            });
        }
        private void SubscribeLogListener()
        {
            if (!_isViewModelActive)
            {
                return;
            }

            var logListenerType = LogListenerType;

            if (logListenerType is null)
            {
                return;
            }

            if (logListenerType == typeof(LogViewerLogListener))
            {
                var logViewerLogListener = _logViewerLogListener;
                if (logViewerLogListener is not null)
                {
                    _logListener = logViewerLogListener;
                    _dispatcherService.Invoke(() => AddLogEntries(logViewerLogListener.GetLogEntries().ToList(), true));
                }
            }
            else
            {
                var logListener = _typeFactory.CreateInstance(logListenerType) as ILogListener;
                if (logListener is not null)
                {
                    LogManager.AddListener(logListener);
                    _logListener = logListener;
                }
            }

            if (_logListener is null)
            {
                return;
            }

            _logListener.IgnoreCatelLogging = IgnoreCatelLogging;
            _logListener.LogMessage        += OnLogMessage;
        }
Example #8
0
        protected override void OnChecked(RoutedEventArgs e)
        {
            base.OnChecked(e);

            var dropDown = DropDown;

            if (dropDown is null)
            {
                return;
            }

            _dispatcherService.Invoke(() =>
            {
                dropDown.SetCurrentValue(ContextMenu.PlacementTargetProperty, this);
                dropDown.SetCurrentValue(ContextMenu.PlacementProperty, PlacementMode.Custom);
                dropDown.SetCurrentValue(ContextMenu.MinWidthProperty, ActualWidth);
                dropDown.SetCurrentValue(ContextMenu.CustomPopupPlacementCallbackProperty, (CustomPopupPlacementCallback)CustomPopupPlacementCallback);
            });

            dropDown.SetCurrentValue(ContextMenu.IsOpenProperty, true);
        }
Example #9
0
        public void LoadFileNode(FileNode fileNode)
        {
            Log.Debug("Loading file node '{0}'", fileNode);

            try
            {
                _dispatcherService.Invoke(() =>
                {
                    var fileRecords = _logReaderService.LoadRecordsFromFileAsync(fileNode).Result;

                    var logRecords = fileNode.Records;
                    using (logRecords.SuspendChangeNotifications())
                    {
                        ((ICollection <LogRecord>)logRecords).ReplaceRange(fileRecords);
                    }
                }, true);
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to load file node '{0}'", fileNode);
            }
        }
Example #10
0
        public async Task PrepareForPresentation(IDispatcherService dispatcher)
        {
            Task <BitmapImage> task;

            lock (ComputingThumbnails)
            {
                if (!ComputingThumbnails.TryGetValue(thumbnailId, out task))
                {
                    task = Task.Run(() => BuildBitmapImage(thumbnailId, thumbnailStream));
                    ComputingThumbnails.Add(thumbnailId, task);
                }
            }

            var result = await task;

            dispatcher.Invoke(() => Presenter = result);
            thumbnailStream = null;

            lock (ComputingThumbnails)
            {
                ComputingThumbnails.Remove(thumbnailId);
            }
        }
Example #11
0
        public async Task PrepareForPresentation(IDispatcherService dispatcher)
        {
            Task <ImageSource> task;

            lock (ComputingThumbnails)
            {
                if (!ComputingThumbnails.TryGetValue(thumbnailId, out task))
                {
                    task = Task.Run(() => BuildImageSource());
                    ComputingThumbnails.Add(thumbnailId, task);
                }
            }

            var result = await task;

            dispatcher.Invoke(() => Presenter = result);
            FreeBuildingResources();

            lock (ComputingThumbnails)
            {
                ComputingThumbnails.Remove(thumbnailId);
            }
        }
 /// <summary>
 /// Executes the specified action asynchronously with the specified arguments on the thread that the Dispatcher was created on if required.
 /// <para />
 /// To check whether this is necessary, it will check whether the current thread has access to the dispatcher.
 /// </summary>
 /// <param name="dispatcherService">The dispatcher service.</param>
 /// <param name="action">The action.</param>
 /// <exception cref="ArgumentNullException">The <paramref name="action" /> is <c>null</c>.</exception>
 public static void InvokeIfRequired(this IDispatcherService dispatcherService, Action action)
 {
     dispatcherService.Invoke(action, true);
 }
Example #13
0
        /// <summary>
        /// The execute.
        /// </summary>
        private void Execute()
        {
            IsRunning = true;

            lock (_syncObj)
            {
                IsCommitting = false;
            }

            try
            {
                bool aborted        = false;
                int  progress       = 0;
                int  total          = _tasks.Count;
                var  processedTasks = new Stack <ITask>();
                while (!aborted && _tasks.Count > 0)
                {
                    ITask task = _tasks.Peek();
                    try
                    {
                        Log.Debug("Executing task '{0}'. ", task.Name);
                        if (_progressNotifyableViewModel != null)
                        {
                            _progressNotifyableViewModel.UpdateStatus(progress++, total, task);
                        }
                        else
                        {
                            // TODO: Display smooth detailed progress using the PleasWaitService
// ReSharper disable AccessToModifiedClosure
                            _dispatcherService.BeginInvoke(() => _pleaseWaitService.UpdateStatus(progress++, total, task.Name));
// ReSharper restore AccessToModifiedClosure
                        }

                        if (task.AutomaticallyDispatch)
                        {
                            _dispatcherService.Invoke(task.Execute);
                        }
                        else
                        {
                            task.Execute();
                        }

                        processedTasks.Push(_tasks.Dequeue());
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);

                        if (!_exceptionService.HandleException(ex))
                        {
                            processedTasks.Push(_tasks.Dequeue());
                            aborted = true;
                        }
                        else
                        {
                            processedTasks.Push(_tasks.Dequeue());
                        }
                    }
                }

                if (aborted)
                {
                    progress = processedTasks.Count;
                    while (processedTasks.Count > 0)
                    {
                        ITask task = processedTasks.Pop();
                        Log.Debug("Rolling back task '{0}'. ", task.Name);

                        try
                        {
                            task.Rollback();
                        }
                        catch (Exception e)
                        {
                            Log.Warning("Rollback of task '{0}' failed", task.Name);
                            Log.Error(e);
                        }
                        finally
                        {
                            if (_progressNotifyableViewModel != null)
                            {
                                _progressNotifyableViewModel.UpdateStatus(--progress, total, task);
                            }
                            else
                            {
                                _dispatcherService.BeginInvoke(() => _pleaseWaitService.UpdateStatus(--progress, total, string.Format("Rollback '{0}'", task.Name)));
                            }
                        }
                    }
                }
            }
            finally
            {
                if (_pleaseWaitService != null)
                {
                    _dispatcherService.Invoke(() => _pleaseWaitService.Hide());
                }

                IsRunning = false;

                if (_progressNotifyableViewModel != null && CloseViewModelOnTerminated)
                {
                    _dispatcherService.Invoke(() => _progressNotifyableViewModel.CloseViewModel(null));
                }

                if (_completedCallback != null)
                {
                    _dispatcherService.Invoke(() => _completedCallback.Invoke());
                }
            }
        }
Example #14
0
        private async Task AnalyzePlugins(IList <Plugin> pluginsToScan, CancellationToken cancellationToken)
        {
            foreach (var plugin in pluginsToScan)
            {
                if (!plugin.IsPresent)
                {
                    continue;
                }

                if (!plugin.HasMetadata)
                {
                    continue;
                }

                LogTo.Debug($"Begin analysis of {plugin.DllFilename}");
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                _globalFrontendService.SelectedPlugin = plugin;

                try
                {
                    using (var remotePluginInstance = _remoteVstService.GetRemotePluginInstance(plugin))
                    {
                        _applicationService.UpdateApplicationOperationStatus(
                            pluginsToScan.IndexOf(plugin), $"Scanning {plugin.DllFilename}");


                        if (!plugin.HasMetadata)
                        {
                            if (plugin.LoadError)
                            {
                                LogTo.Debug($"Skipping {plugin.DllPath} because a load error occured");
                            }
                            else
                            {
                                throw new Exception(
                                          $"Plugin {plugin.DllPath} has no metadata and was loaded correctly.");
                            }
                        }

                        if (plugin.PresetParser == null)
                        {
                            throw new Exception(
                                      $"Plugin {plugin.DllPath} has no preset parser. Please report this as a bug.");
                        }


                        var wasLoaded = remotePluginInstance.IsLoaded;
                        plugin.PresetParser.PluginInstance  = remotePluginInstance;
                        plugin.PresetParser.DataPersistence = _presetDataPersisterService;
                        await _presetDataPersisterService.OpenDatabase();

                        _presetDataPersisterService.PresetUpdated += ContextOnPresetUpdated;
                        _currentPluginIndex = pluginsToScan.IndexOf(plugin);
                        _currentPlugin      = plugin;

                        plugin.PresetParser.RootBank = plugin.RootBank.First();

                        plugin.PresetParser.Logger.MirrorTo(plugin.Logger);
                        _totalPresets       = plugin.PresetParser.GetNumPresets();
                        _currentPresetIndex = 0;

                        await plugin.PresetParser.DoScan();

                        await _presetDataPersisterService.CloseDatabase();

                        _dataPersisterService.SavePresetsForPlugin(plugin);

                        await _dispatcherService.InvokeAsync(() => { plugin.NativeInstrumentsResource.Load(plugin); });

                        if (GlobalService.RuntimeConfiguration.AutoCreateResources &&
                            _resourceGeneratorService.ShouldCreateScreenshot(remotePluginInstance))
                        {
                            plugin.Logger.Debug(
                                $"Auto-generating resources for {plugin.DllFilename} - Opening Editor");
                            _applicationService.UpdateApplicationOperationStatus(
                                pluginsToScan.IndexOf(plugin),
                                $"Auto-generating resources for {plugin.DllFilename} - Opening Editor");
                            if (!remotePluginInstance.IsLoaded)
                            {
                                await remotePluginInstance.LoadPlugin();
                            }

                            remotePluginInstance.OpenEditorHidden();
                            _dispatcherService.Invoke(() => Application.Current.MainWindow.BringWindowToTop());
                            await Task.Delay(1000);
                        }

                        await _dispatcherService.InvokeAsync(() =>
                        {
                            if (GlobalService.RuntimeConfiguration.AutoCreateResources &&
                                _resourceGeneratorService.NeedToGenerateResources(remotePluginInstance))
                            {
                                plugin.Logger.Debug(
                                    $"Auto-generating resources for {plugin.DllFilename} - Creating screenshot and applying magic");
                                _applicationService.UpdateApplicationOperationStatus(
                                    pluginsToScan.IndexOf(plugin),
                                    $"Auto-generating resources for {plugin.DllFilename} - Creating screenshot and applying magic");

                                _resourceGeneratorService.AutoGenerateResources(remotePluginInstance);
                            }
                        });

                        wasLoaded = remotePluginInstance.IsLoaded;


                        _applicationService.UpdateApplicationOperationStatus(
                            pluginsToScan.IndexOf(plugin),
                            $"{plugin.DllFilename} - Updating Database");
                        _dataPersisterService.SavePlugin(plugin);


                        if (wasLoaded)
                        {
                            plugin.Logger.Debug($"Unloading {plugin.DllFilename}");
                            remotePluginInstance.UnloadPlugin();
                        }
                    }
                }
                catch (Exception e)
                {
                    plugin.LogPluginError("loading presets", e);

                    var errorMessage =
                        $"Unable to analyze {plugin.DllFilename} because of {e.GetType().FullName}: {e.Message}";
                    _applicationService.AddApplicationOperationError(errorMessage + " - see plugin log for details");
                }

                if (plugin.PresetParser != null && plugin.PresetParser.Logger.HasLoggedEntries(LogLevel.Error))
                {
                    var errors = plugin.PresetParser.Logger.GetFilteredLogEntries(new List <LogLevel> {
                        LogLevel.Error
                    });

                    foreach (var error in errors)
                    {
                        _applicationService.AddApplicationOperationError(error.Message);
                    }
                }

                // Remove the event handler here, so we can be absolutely sure we removed this.
                _presetDataPersisterService.PresetUpdated -= ContextOnPresetUpdated;

                LogTo.Debug($"End analysis of {plugin.DllFilename}");
            }
        }
Example #15
0
 private void RequestShowMainWindow()
 {
     dispatcher.EnsureAccess(false);
     dispatcher.Invoke(ShowMainWindow);
 }
Example #16
0
        /// <summary>
        /// The execute.
        /// </summary>
        private void Execute()
        {
            IsRunning = true;

            lock (_syncObj)
            {
                IsCommitting = false;
            }

            try
            {
                bool aborted        = false;
                int  progress       = 0;
                int  total          = _tasks.Count;
                var  processedTasks = new Stack <ITask>();
                while (!aborted && _tasks.Count > 0)
                {
                    ITask task = _tasks.Peek();
                    try
                    {
                        Log.Debug("Executing task '{0}'. ", task.Name);
                        if (_progressNotifyableViewModel != null)
                        {
                            _progressNotifyableViewModel.UpdateStatus(progress++, total, task);
                        }
                        else
                        {
                            // TODO: Display smooth detailed progress using the PleasWaitService
// ReSharper disable AccessToModifiedClosure
                            _dispatcherService.Invoke(() => _pleaseWaitService.UpdateStatus(progress++, total, task.Name));
// ReSharper restore AccessToModifiedClosure
                        }

                        if (task.AutomaticallyDispatch)
                        {
                            _dispatcherService.Invoke(task.Execute);
                        }
                        else
                        {
                            task.Execute();
                        }

                        processedTasks.Push(_tasks.Dequeue());
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);

                        var messageResult = MessageResult.None;
                        _dispatcherService.Invoke(() =>
                        {
                            messageResult = _messageService.Show(string.Format(TaskExecutionErrorMessagePattern, task.Name), "Error", MessageButton.YesNoCancel, MessageImage.Error);
                        });

                        switch (messageResult)
                        {
                        case MessageResult.Yes:
                            progress--;
                            break;

                        case MessageResult.No:
                            processedTasks.Push(_tasks.Dequeue());
                            break;

                        case MessageResult.Cancel:
                            processedTasks.Push(_tasks.Dequeue());
                            aborted = true;
                            break;
                        }
                    }
                }

                if (aborted)
                {
                    progress = processedTasks.Count;
                    while (processedTasks.Count > 0)
                    {
                        ITask task = processedTasks.Pop();
                        Log.Debug("Rolling back task '{0}'. ", task.Name);

                        try
                        {
                            task.Rollback();
                        }
                        catch (Exception e)
                        {
                            Log.Warning("Rollback of task '{0}' failed", task.Name);
                            Log.Error(e);
                        }
                        finally
                        {
                            if (_progressNotifyableViewModel != null)
                            {
                                _progressNotifyableViewModel.UpdateStatus(--progress, total, task);
                            }
                            else
                            {
                                _dispatcherService.Invoke(() => _pleaseWaitService.UpdateStatus(--progress, total, string.Format("Rollback '{0}'", task.Name)));
                            }
                        }
                    }
                }
            }
            finally
            {
                if (_pleaseWaitService != null)
                {
                    _dispatcherService.Invoke(() => _pleaseWaitService.Hide());
                }

                IsRunning = false;

                if (_progressNotifyableViewModel != null && CloseViewModelOnTerminated)
                {
                    _dispatcherService.Invoke(() => _progressNotifyableViewModel.CloseViewModel(null));
                }

                if (_completedCallback != null)
                {
                    _dispatcherService.Invoke(() => _completedCallback.Invoke());
                }
            }
        }
Example #17
0
 private void AddValue(Key key, NotificationWithLastTime item)
 {
     _notificationDic.Add(key, item);
     _dispatcherService.Invoke(() => _notificationList.Add(item.Notification));
 }
Example #18
0
        private void OnSearchTimerElapsed(object sender, EventArgs e)
        {
            _textSelectTimer.Stop();

            _dispatcherService.Invoke(() => AssociatedObject?.SelectAll());
        }
Example #19
0
 /// <inheritdoc/>
 protected override void UndoAction()
 {
     dispatcher.Invoke(() => innerActionItem.Undo());
 }
Example #20
0
 static void ShutdownDispatcher(IDispatcherService dispatcher)
 {
     dispatcher.Invoke(() => Dispatcher.CurrentDispatcher.InvokeShutdown());
 }
Example #21
0
        private static async Task UpdateLauncherFiles(IDispatcherService dispatcher, IDialogService dialogService, NugetStore store, CancellationToken cancellationToken)
        {
            var version          = new PackageVersion(Version);
            var productAttribute = (typeof(SelfUpdater).Assembly).GetCustomAttribute <AssemblyProductAttribute>();
            var packageId        = productAttribute.Product;
            var packages         = (await store.GetUpdates(new PackageName(packageId, version), true, true, cancellationToken)).OrderBy(x => x.Version);

            try
            {
                // First, check if there is a package forcing us to download new installer
                const string ReinstallUrlPattern = @"force-reinstall:\s*(\S+)\s*(\S+)";
                var          reinstallPackage    = packages.LastOrDefault(x => x.Version > version && Regex.IsMatch(x.Description, ReinstallUrlPattern));
                if (reinstallPackage != null)
                {
                    var regexMatch     = Regex.Match(reinstallPackage.Description, ReinstallUrlPattern);
                    var minimumVersion = PackageVersion.Parse(regexMatch.Groups[1].Value);
                    if (version < minimumVersion)
                    {
                        var installerDownloadUrl = regexMatch.Groups[2].Value;
                        await DownloadAndInstallNewVersion(dispatcher, dialogService, installerDownloadUrl);

                        return;
                    }
                }
            }
            catch (Exception e)
            {
                await dialogService.MessageBox(string.Format(Strings.NewVersionDownloadError, e.Message), MessageBoxButton.OK, MessageBoxImage.Error);
            }

            // If there is a mandatory intermediate upgrade, take it, otherwise update straight to latest version
            var package = (packages.FirstOrDefault(x => x.Version > version && x.Version.SpecialVersion == "req") ?? packages.LastOrDefault());

            // Check to see if an update is needed
            if (package != null && version < new PackageVersion(package.Version.Version, package.Version.SpecialVersion))
            {
                var windowCreated = new TaskCompletionSource <SelfUpdateWindow>();
                var mainWindow    = dispatcher.Invoke(() => Application.Current.MainWindow as LauncherWindow);
                if (mainWindow == null)
                {
                    throw new ApplicationException("Update requested without a Launcher Window. Cannot continue!");
                }

                dispatcher.InvokeAsync(() =>
                {
                    selfUpdateWindow = new SelfUpdateWindow {
                        Owner = mainWindow
                    };
                    windowCreated.SetResult(selfUpdateWindow);
                    selfUpdateWindow.ShowDialog();
                }).Forget();

                var movedFiles = new List <string>();

                // Download package
                var installedPackage = await store.InstallPackage(package.Id, package.Version, null);

                // Copy files from tools\ to the current directory
                var inputFiles = installedPackage.GetFiles();

                var window = windowCreated.Task.Result;
                dispatcher.Invoke(window.LockWindow);

                // TODO: We should get list of previous files from nuspec (store it as a resource and open it with NuGet API maybe?)
                // TODO: For now, we deal only with the App.config file since we won't be able to fix it afterward.
                var          exeLocation   = Launcher.GetExecutablePath();
                var          exeDirectory  = Path.GetDirectoryName(exeLocation);
                const string directoryRoot = "tools/"; // Important!: this is matching where files are store in the nuspec
                try
                {
                    if (File.Exists(exeLocation))
                    {
                        Move(exeLocation, exeLocation + ".old");
                        movedFiles.Add(exeLocation);
                    }
                    var configLocation = exeLocation + ".config";
                    if (File.Exists(configLocation))
                    {
                        Move(configLocation, configLocation + ".old");
                        movedFiles.Add(configLocation);
                    }
                    foreach (var file in inputFiles.Where(file => file.Path.StartsWith(directoryRoot) && !file.Path.EndsWith("/")))
                    {
                        var fileName = Path.Combine(exeDirectory, file.Path.Substring(directoryRoot.Length));

                        // Move previous files to .old
                        if (File.Exists(fileName))
                        {
                            Move(fileName, fileName + ".old");
                            movedFiles.Add(fileName);
                        }

                        // Update the file
                        UpdateFile(fileName, file);
                    }
                }
                catch (Exception)
                {
                    // Revert all olds files if a file didn't work well
                    foreach (var oldFile in movedFiles)
                    {
                        Move(oldFile + ".old", oldFile);
                    }
                    throw;
                }


                // Remove .old files
                foreach (var oldFile in movedFiles)
                {
                    try
                    {
                        var renamedPath = oldFile + ".old";

                        if (File.Exists(renamedPath))
                        {
                            File.Delete(renamedPath);
                        }
                    }
                    catch (Exception)
                    {
                        // All the files have been replaced, we let it go even if we cannot remove all the old files.
                    }
                }

                // Clean cache from files obtain via package.GetFiles above.
                store.PurgeCache();

                dispatcher.Invoke(RestartApplication);
            }
        }
        /// <summary>
        /// Executes the specified delegate asynchronously with the specified arguments on the thread that the Dispatcher was created on if required.
        /// <para />
        /// To check whether this is necessary, it will check whether the current thread has access to the dispatcher.
        /// </summary>
        /// <param name="dispatcherService">The dispatcher service.</param>
        /// <param name="method">A delegate to a method that takes parameters specified in args, which is pushed onto the Dispatcher event queue.</param>
        /// <param name="args">An array of objects to pass as arguments to the given method. Can be <c>null</c>.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="method" /> is <c>null</c>.</exception>
        public static void InvokeIfRequired(this IDispatcherService dispatcherService, Delegate method, params object[] args)
        {
            Argument.IsNotNull("method", method);

            dispatcherService.Invoke(() => method.DynamicInvoke(args), true);
        }
Example #23
0
 public void Run(IService service)
 {
     _dispatcherService.Invoke(Raise);
 }
Example #24
0
        /// <summary>
        /// The execute.
        /// </summary>
        private void Execute()
        {
            IsRunning = true;

            lock (_syncObj)
            {
                IsCommitting = false;
            }

            IPleaseWaitService pleaseWaitService = null;

            if (_viewModelType == null)
            {
                pleaseWaitService = GetService <IPleaseWaitService>();
            }

            try
            {
                bool aborted = false, retry = false;
                int  progress       = 0;
                int  total          = _tasks.Count;
                var  processedTasks = new Stack <ITask>();
                while (!aborted && _tasks.Count > 0)
                {
                    if (!retry)
                    {
                        processedTasks.Push(_tasks.Dequeue());
                    }

                    retry = false;
                    ITask task = processedTasks.Peek();
                    try
                    {
                        Log.Debug("Executing task '{0}'. ", task.Name);
                        if (pleaseWaitService != null)
                        {
                            pleaseWaitService.UpdateStatus(++progress, total, task.Name);
                        }
                        else if (_progressNotifyableViewModel != null)
                        {
                            _progressNotifyableViewModel.UpdateStatus(progress++, total, task);
                        }

                        _dispatcherService.Invoke(task.Execute);
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);

                        var messageResult = _messageService.Show(string.Format(TaskExecutionErrorMessagePattern, task.Name), "Error", MessageButton.YesNoCancel, MessageImage.Error);
                        switch (messageResult)
                        {
                        case MessageResult.Yes:
                            retry = true;
                            break;

                        case MessageResult.Cancel:
                            aborted = true;
                            break;
                        }
                    }
                }

                if (aborted)
                {
                    while (processedTasks.Count > 0)
                    {
                        ITask task = processedTasks.Pop();
                        Log.Debug("Rolling back task '{0}'. ", task.Name);

                        try
                        {
                            if (pleaseWaitService != null)
                            {
                                pleaseWaitService.UpdateStatus(progress--, total, string.Format("Rollback '{0}'", task.Name));
                            }
                            else if (_progressNotifyableViewModel != null)
                            {
                                _progressNotifyableViewModel.UpdateStatus(progress--, total, task);
                            }

                            task.Rollback();
                        }
                        catch (Exception e)
                        {
                            Log.Warning("Rollback of task '{0}' failed", task.Name);
                            Log.Error(e);
                        }
                    }
                }
            }
            finally
            {
                if (pleaseWaitService != null)
                {
                    pleaseWaitService.Hide();
                }

                IsRunning = false;

                _dispatcherService.Invoke(() =>
                {
                    if (_progressNotifyableViewModel != null)
                    {
                        _progressNotifyableViewModel.CloseViewModel(null);
                    }
                });

                if (_completedCallback != null)
                {
                    _dispatcherService.Invoke(() => _completedCallback.Invoke());
                }
            }
        }
        private async Task <string> OnCommandReceivedAsync(RemoteParameter parameter)
        {
            switch (parameter.Command)
            {
            case RemoteCommands.MiriotConfiguring:
                _dispatcherService.Invoke(() =>
                {
                    _vm.HasNoConfiguration = false;
                    _vm.IsConfiguring      = true;
                });
                return(string.Empty);

            case RemoteCommands.LoadUser:
                _dispatcherService.Invoke(async() =>
                {
                    await _vm.LoadUser(_vm.User);
                });
                return(string.Empty);

            case RemoteCommands.GetUser:
                _dispatcherService.Invoke(() =>
                {
                    _vm.HasNoConfiguration = false;
                    _vm.IsConfiguring      = true;
                });
                return(_vm.User.Id.ToString());

            case RemoteCommands.GraphService_Initialize:
                Messenger.Default.Send(new GraphServiceMessage(false));
                return(null);

            case RemoteCommands.GraphService_GetUser:
                Messenger.Default.Send(new GraphServiceMessage(true));

                var _graphService = SimpleIoc.Default.GetInstance <IGraphService>();

                await _graphService.LoginAsync();

                var graphUser = await _graphService.GetUserAsync();

                return(JsonConvert.SerializeObject(graphUser));

            case RemoteCommands.GoToCameraPage:
                SimpleIoc.Default.GetInstance <INavigationService>().NavigateTo(PageKeys.CameraSettings);
                return(null);

            case RemoteCommands.MiriotConnect:
                //_socketService.ListenTcp();
                return(null);

            case RemoteCommands.MiriotDiscovery:
            default:
                // Reply back
                var id  = _platformService.GetSystemIdentifier();
                var sys = new RomeRemoteSystem(null)
                {
                    Id          = id,
                    DisplayName = Environment.MachineName
                };
                return(JsonConvert.SerializeObject(sys));
            }
        }
Example #26
0
 protected override void OnInfo(object sender, NuGetLogRecordEventArgs e)
 {
     _dispatcherService.Invoke(() => _echo.Lines.Add(string.Format("Info: {0}", e.Message)), true);
 }
Example #27
0
        public FolderNode LoadFileSystemContent(string path, bool isNavigationRoot = false)
        {
            Argument.IsNotNullOrEmpty(() => path);

            Log.Debug("Loading file system content '{0}'", path);

            var directoryInfo = new DirectoryInfo(path);

            FolderNode folder = null;

            _dispatcherService.Invoke(() => { folder = new FolderNode(directoryInfo); }, true);

            var logFiles = Directory.GetFiles(path, _wildcardsFilter, SearchOption.TopDirectoryOnly).Where(x => x.IsSupportedFile(_regexFilter)).OrderBy(x => new FileInfo(x).Name).ToList();

            var fileNodes = new List <FileNode>();

#if LOADFILES_PARALLEL
            var fileTasks = new List <Action>();

            foreach (var logFile in logFiles)
            {
                var file = logFile;

                fileTasks.Add(() =>
                {
                    var fileNode = LoadFileFromFileSystem(Path.Combine(path, file));

                    lock (fileTasks)
                    {
                        fileNodes.AddDescendingly(fileNode, CompareFileNodes);
                    }
                });
            }

            // Parse all files parallel
            TaskHelper.RunAndWait(fileTasks.ToArray());
#else
            foreach (var logFile in logFiles)
            {
                var fileNode = LoadFileFromFileSystem(Path.Combine(path, logFile));
                fileNodes.Add(fileNode);
            }
#endif

            _dispatcherService.Invoke(() => folder.Files = new ObservableCollection <FileNode>(fileNodes.OrderByDescending(x => x.FileInfo.CreationTime)), true);

            var logDirectories = Directory.GetDirectories(path).Select(x => Path.Combine(path, x));

#if LOADDIRECTORIES_PARALLEL
            var directoryTasks = new List <Action>();

            foreach (var directory in logDirectories)
            {
                var dir = directory;

                directoryTasks.Add(() =>
                {
                    var folderNode = LoadFileSystemContent(Path.Combine(path, dir));
                    _dispatcherService.Invoke(() => folder.Directories.Add(folderNode));
                });
            }

            // Parse all directories parallel
            TaskHelper.RunAndWait(directoryTasks.ToArray());
#else
            foreach (var directory in logDirectories)
            {
                var fileSystemContent = LoadFileSystemContent(directory);
                _dispatcherService.Invoke(() => folder.Directories.Add(fileSystemContent), true);
            }
#endif

            if (isNavigationRoot)
            {
                _fileSystemWatchingService.BeginDirectoryWatching(folder.FullName, _wildcardsFilter);
            }
            else
            {
                folder.UpdateVisibility();
            }

            _navigationNodeCacheService.AddToCache(folder);

            return(folder);
        }
Example #28
0
 static void ShutdownDispatcher(IDispatcherService dispatcher)
 {
     dispatcher.Invoke(() => Dispatcher.CurrentDispatcher.InvokeShutdown());
 }
Example #29
0
        public void HandleError([NotNull] Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException("exception");
            }

            GameLog.Server.General.Error(BuildErrorMessage(exception));

            string header;
            string message;

            var gameDataException = exception as GameDataException;

            if (gameDataException != null)
            {
                header  = _resourceManager.GetString("GAME_DATA_ERROR_HEADER");
                message = _resourceManager.GetStringFormat(
                    "GAME_DATA_ERROR_MESSAGE_FORMAT",
                    gameDataException.Message,
                    gameDataException.FileName);
            }
            else
            {
                header  = _resourceManager.GetString("GENERIC_ERROR_HEADER");
                message = _resourceManager.GetStringFormat(
                    "GENERIC_ERROR_MESSAGE_FORMAT",
                    exception.Message);
            }

            _dispatcherService.Invoke(
                (Action)
                (() =>
            {
                var formattedTextConverter = new FormattedTextConverter();
                var messageText = new TextBlock {
                    TextWrapping = TextWrapping.Wrap
                };

                BindingHelpers.SetInlines(
                    messageText,
                    (Inline[])formattedTextConverter.Convert(message));

                MessageDialog.Show(
                    header,
                    messageText,
                    MessageDialogButtons.Ok);

                var supremacyException = exception as SupremacyException;
                if (supremacyException == null)
                {
                    ClientCommands.Exit.Execute(false);
                    return;
                }
                switch (supremacyException.Action)
                {
                case SupremacyExceptionAction.Continue:
                    break;

                case SupremacyExceptionAction.Exit:
                    ClientCommands.Exit.Execute(false);
                    break;

                default:
                case SupremacyExceptionAction.Undefined:
                case SupremacyExceptionAction.Disconnect:
                    ClientCommands.EndGame.Execute(false);
                    break;
                }
            }));
        }