コード例 #1
0
        private void RunGameController(Action <IGameController> runDelegate, bool remoteConnection)
        {
            if (Interlocked.CompareExchange(ref _gameController, null, null) != null)
            {
                return;
            }

            try
            {
                _gameController = ResolveGameController();

                if (remoteConnection)
                {
                    ShowConnectingScreen();
                }
                else
                {
                    ShowLoadingScreen();
                }

                runDelegate.BeginInvoke(
                    _gameController,
                    delegate(IAsyncResult result)
                {
                    try
                    {
                        runDelegate.EndInvoke(result);
                        //GameLog.Print("trying runDelegate.EndInvoke");
                    }
                    catch (SupremacyException e)
                    {
                        GameLog.Client.General.Error("runDelegate.EndInvoke failed", e);
                        Interlocked.Exchange(ref _gameController, null);
                        _dispatcherService.InvokeAsync((Action)ClearStatusWindow);
                        _errorService.HandleError(e);
                        _dispatcherService.InvokeAsync((Action)ActivateMenuScreen);
                    }
                },
                    null);
            }
            catch (SupremacyException e)
            {
                GameLog.Client.General.Error("ResolveGameController failed", e);
                ClearStatusWindow();
                _errorService.HandleError(e);
                Interlocked.Exchange(ref _gameController, null);
                ActivateMenuScreen();
            }
        }
コード例 #2
0
        public Task <bool> ShowNotificationAsync(
            string title,
            string description,
            string accept,
            string cancel)
        {
            var tcs = new TaskCompletionSource <bool>();

            _dispatcher.InvokeAsync(async() =>
            {
                try
                {
                    bool displayAlertResult;
                    if (string.IsNullOrWhiteSpace(cancel))
                    {
                        await Application.Current.MainPage.DisplayAlert(title, description, accept);
                        displayAlertResult = true;
                    }
                    else
                    {
                        displayAlertResult =
                            await Application.Current.MainPage.DisplayAlert(title, description, accept, cancel);
                    }

                    tcs.SetResult(displayAlertResult);
                }
                catch (Exception e)
                {
                    tcs.SetException(e);
                }
            });

            return(tcs.Task);
        }
コード例 #3
0
        public Task PersistGrid(XamDataGrid grid)
        {
            return(dispatcherService.InvokeAsync(() =>
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    grid.SaveCustomizations(memoryStream);

                    byte[] bytes = memoryStream.ToArray();

                    var str = Encoding.UTF8.GetString(bytes);

                    var externalInformations = GetGridExternalInformations(grid);



                    //    using (var ms = new MemoryStream())
                    //    {
                    //        x.Serialize(externalInformations, ms);

                    //        byte[] bytes2 = ms.ToArray();
                    //                var str1 = Encoding.UTF8.GetString(bytes2);

                    //    File.WriteAllText(File, str1);
                    //}

                    //File.WriteAllText(GridLayout, str);
                }
            }));
        }
コード例 #4
0
        private void HandleEffectCompilerRequestedPacket(RemoteEffectCompilerEffectRequested packet, PackageViewModel package)
        {
            // Received a shader requested notification, add it to list of "pending shaders", and update count in UI

            dispatcher.InvokeAsync(() =>
            {
                CheckEffectLogAsset(package);

                // Try to decode request
                try
                {
                    // Deserialize as an object
                    var binaryReader = new BinarySerializationReader(new MemoryStream(packet.Request));
                    EffectCompileRequest effectCompileRequest = null;
                    binaryReader.Context.SerializerSelector   = SerializerSelector.AssetWithReuse;
                    binaryReader.SerializeExtended(ref effectCompileRequest, ArchiveMode.Deserialize, null);

                    // Record in list of pending effects and check if it would result in a new shader
                    // (it is still recorded in list of pending effect, in case EffectLog asset is deleted in the meantime)
                    if (pendingEffects.Add(effectCompileRequest) && !effectLogStore.Contains(effectCompileRequest))
                    {
                        UpdateImportEffectLogPendingCount(session.ImportEffectLogPendingCount + 1);
                    }
                }
                catch
                {
                    // TODO Log error
                    //Log.Warning("Received an effect compilation request which could not be decoded. Make sure Windows project compiled successfully and is up to date.");
                }
            });
        }
コード例 #5
0
        public ItemViewModel(IDispatcherService dispatcherService, IDialogService dialogService)
        {
            _dispatcherService = dispatcherService;
            _dialogService     = dialogService;

            ColoredImageDatas = new ObservableCollection <ColoredImageData>();

            Search = new RelayCommand(PrivateSearch);

            currentPropertyObserver = new PropertyObserver <ItemViewModel>(this);
            currentPropertyObserver.RegisterHandler(p => p.SearchText, (vm) => { vm.PrivateSearch(); });

            Task.Run(() =>
            {
                try
                {
                    LoadXml(ColoredImageDatas, XmlPath);
                }
                catch (Exception ex)
                {
                    string title = string.Format("加载 {0} 失败", XmlPath);

                    Log.Error(ex, title);

                    _dispatcherService.InvokeAsync(() =>
                    {
                        _dialogService.ShowInformation(ex.Message, title);
                    });
                }
            });
        }
コード例 #6
0
        private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (stack.RollInProgress)
            {
                return;
            }

            // We create a transaction at the first change, and complete it at the next dispatcher frame with InvokeAsync
            if (currentTransaction == null)
            {
                currentTransaction = stack.CreateTransaction();
                dispatcher.InvokeAsync(CompleteTransaction);
            }

            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                PropertySelectionSuppressed = true;
                try
                {
                    // When we add a new item to selection, we clear the selection in all other collections
                    foreach (var scope in scopes.Where(x => !x.Collections.Contains(sender)))
                    {
                        foreach (var collection in scope.Collections)
                        {
                            var descriptor = TypeDescriptorFactory.Default.Find(collection.GetType()) as CollectionDescriptor;
                            descriptor?.Clear(collection);
                        }
                    }
                }
                finally
                {
                    PropertySelectionSuppressed = false;
                }
            }
        }
コード例 #7
0
ファイル: SoundPreview.cs プロジェクト: Aggror/Stride
        private async void UpdatePlaybackTime()
        {
            try
            {
                while (IsRunning)
                {
                    await Task.Delay(50);

                    if (UpdateViewModelTime != null)
                    {
                        await dispatcher.InvokeAsync(() =>
                        {
                            if (loaded)
                            {
                                IsPlaying    = instance.PlayState == PlayState.Playing;
                                var position = instance.Position;
                                UpdateViewModelTime(true, IsPlaying, position + startTime, sound.TotalLength);
                            }
                            else
                            {
                                UpdateViewModelTime(false, false, TimeSpan.Zero, TimeSpan.Zero);
                            }
                        });
                    }
                }
            }
            catch (TaskCanceledException)
            {
                //Cool!
            }
        }
コード例 #8
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);
            }
        }
コード例 #9
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.YesNoCancel, MessageImage.Question) == MessageResult.Yes)
            {
                Log.Info("Removing person '{0}'", selectedPerson);

                await _dispatcherService.InvokeAsync(() =>
                {
                    Persons.Remove(selectedPerson);
                    SelectedPerson = Persons.FirstOrDefault();
                });
            }
        }
コード例 #10
0
        public async Task <bool> InitializeAsync()
        {
            var taskCompletionSource = new TaskCompletionSource <bool>();

            await _dispatcher.InvokeAsync(() =>
            {
                UNUserNotificationCenter.Current.RequestAuthorization(
                    UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound,
                    (isAllowed, error) =>
                {
                    taskCompletionSource.TrySetResult(isAllowed);
                });
            });

            var result = await taskCompletionSource.Task.ReturnInTimeoutAsync(false, InitializationDelayMilliseconds);

            return(result);
        }
コード例 #11
0
        private void LoadXml(ObservableCollection <ColoredImageData> imageDatas, string path)
        {
            string itemIconsDirectory = CommonHelper.GetAppSettings("ItemIconsDirectory").Replace("/", "\\");

            XmlDocument doc = new XmlDocument();

            doc.Load(path);

            XmlNode baseNode = doc.SelectSingleNode(doc.DocumentElement.Name);

            foreach (XmlNode node in baseNode.ChildNodes)
            {
                if (node is XmlElement)
                {
                    string itemName = node.Attributes["name"]?.Value;

                    string customIcon = (node.SelectSingleNode("property[@name='CustomIcon']") as XmlElement)?.GetAttribute("value");

                    string uriStr = itemIconsDirectory + "\\" + (customIcon ?? itemName) + ".png";

                    if (SdtdLocalizationManager.Instance.LocalizationDict.TryGetValue(itemName, out string chinese) &&
                        System.IO.File.Exists(uriStr))
                    {
                        string customIconTint = (node.SelectSingleNode("property[@name='CustomIconTint']") as XmlElement)?.GetAttribute("value");

                        ColoredImageData coloredImageData = new ColoredImageData()
                        {
                            Source   = new Uri(uriStr, UriKind.Relative),
                            HexColor = customIconTint ?? null,
                            ToolTip  = itemName + Environment.NewLine + chinese,
                            English  = itemName,
                            Chinese  = chinese
                        };

                        _dispatcherService.InvokeAsync(() =>
                        {
                            imageDatas.Add(coloredImageData);
                        }, DispatcherPriority.ApplicationIdle);
                    }
                }
            }
        }
コード例 #12
0
ファイル: EventBinder.cs プロジェクト: Tauron1990/Fun
                    public async Task Execute(EventData parameter, bool sync)
                    {
                        var args = _methodType switch
                        {
                            MethodType.Zero => new object[0],
                            MethodType.One => new object[] { parameter },
                            MethodType.Two => new[] { parameter?.Sender, parameter?.EventArgs },
                            MethodType.EventArgs => new[] { parameter?.EventArgs },
                            _ => new object[0]
                        };

                        if (sync)
                        {
                            await DispatcherService.InvokeAsync(() => _method.InvokeFast(Context, args)).ConfigureAwait(false);
                        }
                        else
                        {
                            await(_method.InvokeFast <Task>(Context, args) ?? Task.CompletedTask).ConfigureAwait(false);
                        }
                    }
        protected override async Task ExecuteAsync(object parameter)
        {
            var result = await _messageService.ShowAsync(
                "This action will remove the selected plugin(s) from the database. Note: If the plugins are still in " +
                "the configured VST directories, they will be analyzed again unless you disable them." +
                Environment.NewLine + Environment.NewLine +
                "This will also remove any imported presets for these plugins." +
                Environment.NewLine + Environment.NewLine +
                "Do you wish to continue?",
                "Remove Plugins: Please confirm", MessageButton.YesNo, MessageImage.Question);

            if (result == MessageResult.Yes)
            {
                var pluginsToRemove = _globalFrontendService.SelectedPlugins.ToList();

                ApplicationService.StartApplicationOperation(this, "Removing plugins",
                                                             pluginsToRemove.Count);
                var progress       = ApplicationService.GetApplicationProgress();
                var progressStatus = new CountProgress(pluginsToRemove.Count);


                foreach (var plugin in pluginsToRemove)
                {
                    progressStatus.Current = pluginsToRemove.IndexOf(plugin);
                    progressStatus.Status  = $"Removing {plugin.PluginName} and associated presets. This may take up to several minutes.";
                    progress.Progress.Report(progressStatus);
                    await _dispatcherService.InvokeAsync(async() => { _globalService.Plugins.Remove(plugin); });

                    _dataPersister.DeletePresetsForPlugin(plugin);
                    await _presetDataPersister.DeletePresetDataForPlugin(plugin, true);
                }

                progressStatus.Status = $"Compacting database. This may take up to several minutes.";
                progress.Progress.Report(progressStatus);
                await _presetDataPersister.VacuumDatabase();

                _dataPersister.Save();

                ApplicationService.StopApplicationOperation("Finished removing plugins");
            }
        }
コード例 #14
0
        protected Task InvokeDialog()
        {
            return(dispatcher.InvokeAsync(() =>
            {
                var result = Dialog.ShowDialog();
                switch (result)
                {
                case CommonFileDialogResult.None:
                    Result = DialogResult.None;
                    break;

                case CommonFileDialogResult.Ok:
                    Result = DialogResult.Ok;
                    break;

                case CommonFileDialogResult.Cancel:
                    Result = DialogResult.Cancel;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }));
        }
コード例 #15
0
        protected override async Task ExecuteThreaded(object parameter)
        {
            var pluginsToScan = GetPluginsToScan();


            var pluginsToUpdateMetadata =
                (from p in GlobalService.Plugins
                 where p.RequiresMetadataScan
                 orderby p.PluginName, p.DllFilename
                 select p).ToList();

            _applicationService.StartApplicationOperation(this, "Analyzing VST plugins: Loading missing metadata",
                                                          pluginsToUpdateMetadata.Count);

            var pluginsToRemove = new List <Plugin>();
            var mergedPlugins   = new List <(Plugin oldPlugin, Plugin mergedIntoPlugin)>();
            var progress        = _applicationService.GetApplicationProgress();

            // First pass: Load missing metadata
            try
            {
                var result = await TaskHelper.Run(
                    async() => await _pluginService.UpdateMetadata(pluginsToUpdateMetadata, progress), true,
                    progress.CancellationToken);

                pluginsToRemove = result.removedPlugins;
                mergedPlugins   = result.mergedPlugins;

                await _dispatcherService.InvokeAsync(() =>
                {
                    foreach (var plugin in pluginsToRemove)
                    {
                        GlobalService.Plugins.Remove(plugin);

                        if (pluginsToScan.Contains(plugin))
                        {
                            pluginsToScan.Remove(plugin);
                        }
                    }
                });
            }
            catch (Exception e)
            {
                _applicationService.AddApplicationOperationError(
                    $"Unable to update metadata because of {e.GetType().FullName}: {e.Message}");
                LogTo.Debug(e.StackTrace);
            }

            _applicationService.StopApplicationOperation("Analyzing VST plugins Metadata analysis complete.");

            if (mergedPlugins.Count > 0)
            {
                var sb = new StringBuilder();
                foreach (var merge in (from p in mergedPlugins orderby p.oldPlugin.LastKnownGoodDllPath select p))
                {
                    sb.AppendLine(
                        $"{merge.oldPlugin.LastKnownGoodDllPath} => {merge.mergedIntoPlugin.LastKnownGoodDllPath}");
                }


                var result = await _messageService.ShowAsync(
                    "Automatically merged different plugin DLLs to the same plugin. Affected plugin(s):" +
                    Environment.NewLine + Environment.NewLine +
                    sb + Environment.NewLine + Environment.NewLine +
                    "Would you like to abort the analysis now, so that you can review the settings for each affected plugin? (Highly recommended!)",
                    "Auto-merged Plugins", HelpLinks.SETTINGS_PLUGIN_DLL, MessageButton.YesNo, MessageImage.Question);

                if (result == MessageResult.Yes)
                {
                    // ReSharper disable once MethodSupportsCancellation
                    _dataPersisterService.Save();
                    _commandManager.ExecuteCommand(Commands.Application.CancelOperation);
                }
            }

            if (!progress.CancellationToken.IsCancellationRequested && !SkipPresetLoading)
            {
                _applicationService.StartApplicationOperation(this, "Analyzing VST plugins",
                                                              pluginsToScan.Count);
                progress = _applicationService.GetApplicationProgress();


                await TaskHelper.Run(
                    async() => await AnalyzePlugins(pluginsToScan.OrderBy(p => p.PluginName).ToList(),
                                                    progress.CancellationToken), true,
                    progress.CancellationToken);

                // ReSharper disable once MethodSupportsCancellation
                _dataPersisterService.Save();
            }


            if (progress.CancellationToken.IsCancellationRequested)
            {
                _applicationService.StopApplicationOperation("Plugin analysis cancelled.");
            }
            else
            {
                _applicationService.StopApplicationOperation("Plugin analysis completed.");
            }

            var unreportedPlugins =
                (from plugin in GlobalService.Plugins
                 where !plugin.IsReported && !plugin.DontReport && !plugin.IsSupported && plugin.HasMetadata &&
                 plugin.IsEnabled
                 select plugin).ToList();

            if (unreportedPlugins.Any())
            {
                var result = await _messageService.ShowCustomRememberMyChoiceDialogAsync(
                    "There are unsupported plugins which are not reported." +
                    Environment.NewLine +
                    "Would you like to report them, so we can implement support for them?",
                    "Report Unsupported Plugins", null, MessageButton.YesNo, MessageImage.Question,
                    "Don't ask again for the currently unreported plugins");


                if (result.result == MessageResult.Yes)
                {
                    _commandManager.ExecuteCommand(Commands.Plugin.ReportUnsupportedPlugins);
                }

                if (result.dontChecked)
                {
                    foreach (var plugin in unreportedPlugins)
                    {
                        plugin.DontReport = true;
                    }

                    _dataPersisterService.Save();
                }
            }
        }
コード例 #16
0
 private Task OnProjectActivationAsync(object sender, ProjectUpdatingCancelEventArgs e)
 {
     return(_dispatcherService.InvokeAsync(() => Project = (Project)e.NewProject));
 }
コード例 #17
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);
            }
        }
コード例 #18
0
        UpdateMetadata(IList <Plugin> pluginsToUpdate,
                       ApplicationProgress applicationProgress)
        {
            var pluginsToRemove = new List <Plugin>();
            var mergedPlugins   = new List <(Plugin oldPlugin, Plugin mergedIntoPlugin)>();
            var progressStatus  = new CountProgress(pluginsToUpdate.Count);

            foreach (var plugin in pluginsToUpdate)
            {
                if (applicationProgress.CancellationToken.IsCancellationRequested)
                {
                    return(pluginsToRemove, mergedPlugins);
                }

                try
                {
                    _globalFrontendService.SelectedPlugin = plugin;
                    progressStatus.Current = pluginsToUpdate.IndexOf(plugin);
                    progressStatus.Status  = $"Loading metadata for {plugin.DllFilename}";
                    applicationProgress.Progress.Report(progressStatus);

                    var originalPluginLocation = plugin.PluginLocation;
                    foreach (var pluginLocation in plugin.PluginLocations)
                    {
                        if (pluginLocation.IsPresent &&
                            plugin.RequiresMetadataScan

                            /*pluginLocation.LastMetadataAnalysisVersion != _globalService.PresetMagicianVersion &&
                             * (!pluginLocation.HasMetadata || plugin.RequiresMetadataScan || pluginLocation.PresetParser == null || (pluginLocation.PresetParser != null &&
                             *                               pluginLocation.PresetParser.RequiresRescan()))*/)
                        {
                            plugin.PluginLocation = pluginLocation;
                            pluginLocation.LastMetadataAnalysisVersion = _globalService.PresetMagicianVersion;

                            using (var remotePluginInstance =
                                       _remoteVstService.GetRemotePluginInstance(plugin, false))
                            {
                                try
                                {
                                    await remotePluginInstance.LoadPlugin();

                                    plugin.Logger.Debug($"Attempting to find presetParser for {plugin.PluginName}");
                                    pluginLocation.PresetParser = null;
                                    _vendorPresetParserService.DeterminatePresetParser(remotePluginInstance);
                                    remotePluginInstance.UnloadPlugin();
                                }
                                catch (Exception e)
                                {
                                    applicationProgress.LogReporter.Report(new LogEntry(LogLevel.Error,
                                                                                        $"Error while loading metadata for {plugin.DllPath}: {e.GetType().FullName} {e.Message}"));
                                    LogTo.Debug(e.StackTrace);
                                }
                            }
                        }
                    }

                    plugin.PluginLocation = originalPluginLocation;
                    plugin.EnsurePluginLocationIsPresent();
                    plugin.UpdateRequiresMetadataScanFlag(_globalService.PresetMagicianVersion);

                    if (!plugin.HasMetadata && plugin.PluginLocation == null && plugin.Presets.Count == 0)
                    {
                        // No metadata and still no plugin location dll => remove it

                        applicationProgress.LogReporter.Report(new LogEntry(LogLevel.Info,
                                                                            "Removing unknown plugin entry without metadata, without presets and without plugin dll"));
                        pluginsToRemove.Add(plugin);

                        continue;
                    }

                    if (!plugin.HasMetadata)
                    {
                        // Still no metadata, probably plugin loading failure. Try again in the next version.
                        continue;
                    }

                    if (_globalService.RuntimeConfiguration.StripBridgedPluginPrefix &&
                        plugin.PluginName.StartsWith("[jBridge]"))
                    {
                        plugin.OverridePluginName   = true;
                        plugin.OverriddenPluginName = plugin.PluginName.Replace("[jBridge]", "");
                    }


                    // We now got metadata - check if there's an existing plugin with the same plugin ID. If so,
                    // merge this plugin with the existing one if it has no presets.
                    var existingPlugin =
                        (from p in _globalService.Plugins
                         where p.VstPluginId == plugin.VstPluginId && p.PluginId != plugin.PluginId &&
                         plugin.IsPresent &&
                         !pluginsToRemove.Contains(p)
                         select p)
                        .FirstOrDefault();

                    if (existingPlugin == null)
                    {
                        continue;
                    }

                    if (plugin.Presets.Count == 0)
                    {
                        // There's an existing plugin which this plugin can be merged into. Schedule it for removal
                        pluginsToRemove.Add(plugin);
                        mergedPlugins.Add((oldPlugin: plugin, mergedIntoPlugin: existingPlugin));

                        if (existingPlugin.PluginLocation == null)
                        {
                            if (Core.UseDispatcher)
                            {
                                await _dispatcherService.InvokeAsync(() =>
                                {
                                    existingPlugin.PluginLocation = plugin.PluginLocation;
                                });
                            }
                            else
                            {
                                existingPlugin.PluginLocation = plugin.PluginLocation;
                            }
                        }
                        else
                        {
                            existingPlugin.PluginLocations.Add(plugin.PluginLocation);
                            existingPlugin.EnsurePluginLocationIsPresent();
                        }
                    }
                    else if (existingPlugin.Presets.Count == 0)
                    {
                        // The existing plugin has no presets - remove it!
                        pluginsToRemove.Add(existingPlugin);
                        mergedPlugins.Add((oldPlugin: existingPlugin, mergedIntoPlugin: plugin));
                        if (plugin.PluginLocation == null)
                        {
                            if (Core.UseDispatcher)
                            {
                                await _dispatcherService.InvokeAsync(() =>
                                {
                                    plugin.PluginLocation = existingPlugin.PluginLocation;
                                });
                            }
                            else
                            {
                                plugin.PluginLocation = existingPlugin.PluginLocation;
                            }
                        }
                        else
                        {
                            plugin.PluginLocations.Add(existingPlugin.PluginLocation);
                            existingPlugin.EnsurePluginLocationIsPresent();
                        }
                    }
                }
                catch (Exception e)
                {
                    applicationProgress.LogReporter.Report(new LogEntry(LogLevel.Error,
                                                                        $"Unable to load  metadata for {plugin.DllFilename} because of {e.GetType().FullName} {e.Message}"));
                }


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

            return(pluginsToRemove, mergedPlugins);
        }