Пример #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PackageStore"/> class.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Unable to find a valid Xenko installation path</exception>
        private PackageStore(string defaultPackageName = "Xenko", string defaultPackageVersion = XenkoVersion.NuGetVersion)
        {
            // TODO: these are currently hardcoded to Xenko
            DefaultPackageName      = defaultPackageName;
            DefaultPackageVersion   = new PackageVersion(defaultPackageVersion);
            defaultPackageDirectory = DirectoryHelper.GetPackageDirectory(defaultPackageName);

            // Try to resolve an installation path from the path of this assembly
            // We need to be able to use the package manager from an official Xenko install as well as from a developer folder
            if (globalInstallationPath == null)
            {
                globalInstallationPath = DirectoryHelper.GetInstallationDirectory(DefaultPackageName);
            }

            // If there is no root, this is an error
            if (globalInstallationPath == null)
            {
                throw new InvalidOperationException("Unable to find a valid Xenko installation or dev path");
            }

            // Preload default package
            var logger             = new LoggerResult();
            var defaultPackageFile = DirectoryHelper.GetPackageFile(defaultPackageDirectory, DefaultPackageName);

            defaultPackage = Package.Load(logger, defaultPackageFile, GetDefaultPackageLoadParameters());
            if (defaultPackage == null)
            {
                throw new InvalidOperationException("Error while loading default package from [{0}]: {1}".ToFormat(defaultPackageFile, logger.ToText()));
            }
            defaultPackage.IsSystem = true;

            // Check if we are in a root directory with store/packages facilities
            store = new NugetStore(globalInstallationPath);
        }
Пример #2
0
        /// <summary>
        /// Gets the paradox SDK dir.
        /// </summary>
        /// <returns></returns>
        private static string FindParadoxSdkDir()
        {
            // TODO: Maybe move it in some common class somewhere? (in this case it would be included with "Add as link" in VSPackage)
            var paradoxSdkDir = Environment.GetEnvironmentVariable("SiliconStudioParadoxDir");

            // Check if it is a dev directory
            if (File.Exists(Path.Combine(paradoxSdkDir, "build\\Paradox.sln")))
            {
                return(paradoxSdkDir);
            }

            // Check if we are in a root directory with store/packages facilities
            if (NugetStore.IsStoreDirectory(paradoxSdkDir))
            {
                var store = new NugetStore(paradoxSdkDir)
                {
                    DefaultPackageId = "Paradox"
                };

                var paradoxPackage = store.GetLatestPackageInstalled(store.DefaultPackageId);
                if (paradoxPackage == null)
                {
                    return(null);
                }

                var packageDirectory = store.PathResolver.GetPackageDirectory(paradoxPackage);
                return(Path.Combine(paradoxSdkDir, NugetStore.DefaultGamePackagesDirectory, packageDirectory));
            }

            return(null);
        }
Пример #3
0
        private static void OpenWithGameStudioMenuCommand_Callback(object sender, EventArgs e)
        {
            var dte = (DTE2)ServiceProvider.GetService(typeof(SDTE));

            var solutionFile = dte.Solution?.FileName;

            // Is there any active solution?
            if (solutionFile == null)
            {
                return;
            }

            // Locate GameStudio
            var packageInfo = XenkoCommandsProxy.CurrentPackageInfo;

            if (packageInfo.LoadedVersion == null || packageInfo.SdkPath == null)
            {
                return;
            }

            var store          = new NugetStore(packageInfo.StorePath);
            var mainExecutable = store.LocateMainExecutable(packageInfo.SdkPath);

            if (Process.Start(mainExecutable, $"\"{solutionFile}\"") == null)
            {
                throw new InvalidOperationException("Could not start GameStudio process");
            }
        }
Пример #4
0
        /// <summary>
        /// Setup the Launcher's service interface to handle IPC communications.
        /// </summary>
        private bool Initialize()
        {
            // Setup the Nuget store
            store = Launcher.InitializeNugetStore();

            return(true);
        }
Пример #5
0
        internal static NugetStore InitializeNugetStore()
        {
            var thisExeDirectory = new UFile(Assembly.GetEntryAssembly().Location).GetFullDirectory().ToWindowsPath();
            var store            = new NugetStore(thisExeDirectory);

            return(store);
        }
Пример #6
0
 internal VsixVersionViewModel(LauncherViewModel launcher, NugetStore store)
     : base(launcher, store, null)
 {
     ExecuteActionCommand = new AnonymousCommand(ServiceProvider, ExecuteAction)
     {
         IsEnabled = false
     };
 }
        internal void Initialize(NugetStore store, string defaultLogText = null)
        {
            var dispatcherService = new DispatcherService(Dispatcher);
            var dialogService     = new DialogService(dispatcherService, Launcher.ApplicationName);
            var serviceProvider   = new ViewModelServiceProvider(new object[] { dispatcherService, dialogService });

            DataContext = new LauncherViewModel(serviceProvider, store);
        }
Пример #8
0
        /// <summary>
        /// Gets the xenko SDK dir.
        /// </summary>
        /// <returns></returns>
        internal static async Task <PackageInfo> FindXenkoSdkDir(string solution, string packageName = "Xenko.VisualStudio.Commands")
        {
            // Resolve the sdk version to load from the solution's package
            var packageInfo = new PackageInfo {
                ExpectedVersion = await PackageSessionHelper.GetPackageVersion(solution), SdkPaths = new List <string>()
            };

            // Check if we are in a root directory with store/packages facilities
            var store = new NugetStore(null);
            NugetLocalPackage xenkoPackage = null;

            // Try to find the package with the expected version
            if (packageInfo.ExpectedVersion != null && packageInfo.ExpectedVersion >= MinimumVersion)
            {
                // Xenko up to 3.0
                if (packageInfo.ExpectedVersion < new PackageVersion(3, 1, 0, 0))
                {
                    xenkoPackage = store.GetPackagesInstalled(new[] { "Xenko" }).FirstOrDefault(package => package.Version == packageInfo.ExpectedVersion);
                    if (xenkoPackage != null)
                    {
                        var xenkoSdkDir = store.GetRealPath(xenkoPackage);

                        packageInfo.LoadedVersion = xenkoPackage.Version;

                        foreach (var path in new[]
                        {
                            // Xenko 2.x and 3.0
                            @"Bin\Windows\Direct3D11",
                            @"Bin\Windows",
                            // Xenko 1.x
                            @"Bin\Windows-Direct3D11"
                        })
                        {
                            var fullPath = Path.Combine(xenkoSdkDir, path);
                            if (Directory.Exists(fullPath))
                            {
                                packageInfo.SdkPaths.AddRange(Directory.EnumerateFiles(fullPath, "*.dll", SearchOption.TopDirectoryOnly));
                                packageInfo.SdkPaths.AddRange(Directory.EnumerateFiles(fullPath, "*.exe", SearchOption.TopDirectoryOnly));
                            }
                        }
                    }
                }
                // Xenko 3.1+
                else
                {
                    var logger = new Logger();
                    var(request, result) = await RestoreHelper.Restore(logger, packageName, new VersionRange(packageInfo.ExpectedVersion.ToNuGetVersion()));

                    if (result.Success)
                    {
                        packageInfo.SdkPaths.AddRange(RestoreHelper.ListAssemblies(request, result));
                        packageInfo.LoadedVersion = packageInfo.ExpectedVersion;
                    }
                }
            }

            return(packageInfo);
        }
Пример #9
0
        /// <summary>
        /// Gets the xenko SDK dir.
        /// </summary>
        /// <returns></returns>
        private static PackageInfo FindXenkoSdkDir()
        {
            // Resolve the sdk version to load from the solution's package
            var packageInfo = new PackageInfo {
                ExpectedVersion = PackageSessionHelper.GetPackageVersion(solution)
            };

            // TODO: Maybe move it in some common class somewhere? (in this case it would be included with "Add as link" in VSPackage)
            var xenkoSdkDir = Environment.GetEnvironmentVariable("SiliconStudioXenkoDir");

            // Failed to locate xenko
            if (xenkoSdkDir == null)
            {
                return(packageInfo);
            }

            // If we are in a dev directory, assume we have the right version
            if (File.Exists(Path.Combine(xenkoSdkDir, "build\\Xenko.sln")))
            {
                packageInfo.SdkPath       = xenkoSdkDir;
                packageInfo.LoadedVersion = packageInfo.ExpectedVersion;
                return(packageInfo);
            }

            // Check if we are in a root directory with store/packages facilities
            if (NugetStore.IsStoreDirectory(xenkoSdkDir))
            {
                var      store        = new NugetStore(xenkoSdkDir);
                IPackage xenkoPackage = null;

                // Try to find the package with the expected version
                if (packageInfo.ExpectedVersion != null && packageInfo.ExpectedVersion >= MinimumVersion)
                {
                    xenkoPackage = store.GetPackagesInstalled(store.MainPackageIds).FirstOrDefault(package => GetVersion(package) == packageInfo.ExpectedVersion);
                }

                // If the expected version is not found, get the latest package
                if (xenkoPackage == null)
                {
                    xenkoPackage = store.GetLatestPackageInstalled(store.MainPackageIds);
                }

                // If no package was found, return no sdk path
                if (xenkoPackage == null)
                {
                    return(packageInfo);
                }

                // Return the loaded version and the sdk path
                var packageDirectory = store.PathResolver.GetPackageDirectory(xenkoPackage);
                packageInfo.LoadedVersion = GetVersion(xenkoPackage);
                packageInfo.SdkPath       = Path.Combine(xenkoSdkDir, store.RepositoryPath, packageDirectory);
            }

            return(packageInfo);
        }
Пример #10
0
 internal VsixVersionViewModel(LauncherViewModel launcher, NugetStore store, string packageId)
     : base(launcher, store, null)
 {
     this.packageId       = packageId;
     status               = FormatStatus(Strings.ReportChecking);
     ExecuteActionCommand = new AnonymousTaskCommand(ServiceProvider, ExecuteAction)
     {
         IsEnabled = false
     };
 }
Пример #11
0
        private static async Task UninstallPackage(NugetStore store, NugetPackage package, ProgressReport progressReport)
        {
            await store.UninstallPackage(package, progressReport);

            // If package is GameStudio, then recursively delete its Stride/Xenko dependencies to save more disk space
            if (store.MainPackageIds.Contains(package.Id))
            {
                await UninstallDependencies(store, package);
            }
        }
Пример #12
0
 internal XenkoDevVersionViewModel(LauncherViewModel launcher, NugetStore store, [CanBeNull] NugetLocalPackage localPackage, UDirectory path, bool isDevRedirect)
     : base(launcher, store, localPackage, int.MaxValue, devMinorCounter--)
 {
     this.path                 = path;
     this.localPackage         = localPackage;
     this.isDevRedirect        = isDevRedirect;
     DownloadCommand.IsEnabled = false;
     // Update initial status (IsVisible will be set to true)
     UpdateStatus();
 }
Пример #13
0
        internal StrideVersionViewModel(LauncherViewModel launcher, NugetStore store, NugetLocalPackage localPackage, string packageId, int major, int minor)
            : base(launcher, store, localPackage)
        {
            PackageSimpleName  = packageId.Replace(".GameStudio", string.Empty);
            Major              = major;
            Minor              = minor;
            SetAsActiveCommand = new AnonymousCommand(ServiceProvider, () => launcher.ActiveVersion = this);
            // Update status if the user changes whether to display beta versions.
            launcher.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(LauncherViewModel.ShowBetaVersions))
                                                    {
                                                        UpdateStatus();
                                                    }
            };

            if (LocalPackage != null && InstallPath != null)
            {
                var libDirectory = Path.Combine(InstallPath, "lib");
                var frameworks   = Directory.EnumerateDirectories(libDirectory);
                foreach (var frameworkPath in frameworks)
                {
                    var frameworkFolder = new DirectoryInfo(frameworkPath).Name;
                    if (File.Exists(Path.Combine(frameworkPath, "Stride.GameStudio.exe")) ||
                        File.Exists(Path.Combine(frameworkPath, "Xenko.GameStudio.exe")))
                    {
                        Frameworks.Add(frameworkFolder);
                    }
                }

                if (Frameworks.Count > 0)
                {
                    try
                    {
                        // If preferred framework exists in our list, select it
                        var preferredFramework = LauncherSettings.PreferredFramework;
                        if (Frameworks.Contains(preferredFramework))
                        {
                            SelectedFramework = preferredFramework;
                        }
                        else
                        {
                            // Otherwise, try to find a framework of the same kind (.NET Core or .NET Framework)
                            var nugetFramework = NuGetFramework.ParseFolder(preferredFramework);
                            SelectedFramework =
                                Frameworks.FirstOrDefault(x => NuGetFramework.ParseFolder(preferredFramework).Framework == nugetFramework.Framework)
                                ?? Frameworks.First(); // otherwise fallback to first choice
                        }
                    }
                    catch
                    {
                        SelectedFramework = Frameworks.First();
                    }
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Setup the Launcher's service interface to handle IPC communications.
        /// </summary>
        private bool Initialize()
        {
            // Setup the Nuget store
            store = Launcher.InitializeNugetStore();

            if (!CreateTargetFilesIfMissing(store))
            {
                return(false);
            }

            return(true);
        }
Пример #15
0
 internal XenkoVersionViewModel(LauncherViewModel launcher, NugetStore store, NugetLocalPackage localPackage, int major, int minor)
     : base(launcher, store, localPackage)
 {
     Major = major;
     Minor = minor;
     SetAsActiveCommand = new AnonymousCommand(ServiceProvider, () => launcher.ActiveVersion = this);
     // Update status if the user changes whether to display beta versions.
     launcher.PropertyChanged += (s, e) => { if (e.PropertyName == nameof(LauncherViewModel.ShowBetaVersions))
                                             {
                                                 UpdateStatus();
                                             }
     };
 }
Пример #16
0
 internal static Task SelfUpdate(IViewModelServiceProvider services, NugetStore store)
 {
     return(Task.Run(async() =>
     {
         var dispatcher = services.Get <IDispatcherService>();
         try
         {
             await UpdateLauncherFiles(dispatcher, services.Get <IDialogService>(), store, CancellationToken.None);
         }
         catch (Exception e)
         {
             dispatcher.Invoke(() => selfUpdateWindow?.ForceClose());
             throw;
         }
     }));
 }
Пример #17
0
        /// <summary>
        /// Gets the xenko SDK dir.
        /// </summary>
        /// <param name="xenkoVersion">The xenko version. If null, it will get latest version.</param>
        /// <returns></returns>
        public static string FindXenkoSdkDir(string xenkoVersion = null)
        {
            // TODO: Almost duplicate of XenkoCommandsProxy.FindXenkoSdkDir!!
            // TODO: Maybe move it in some common class somewhere? (in this case it would be included with "Add as link" in VSPackage)
            var xenkoSdkDir = DirectoryHelper.GetInstallationDirectory("Xenko");

            if (xenkoSdkDir == null)
            {
                xenkoSdkDir = Environment.GetEnvironmentVariable("SiliconStudioXenkoDir");
            }

            if (xenkoSdkDir == null)
            {
                return(null);
            }

            // Check if it is a dev directory
            if (File.Exists(Path.Combine(xenkoSdkDir, "build\\Xenko.sln")))
            {
                return(xenkoSdkDir);
            }

            // Check if we are in a root directory with store/packages facilities
            if (NugetStore.IsStoreDirectory(xenkoSdkDir))
            {
                var store = new NugetStore(xenkoSdkDir);

                var xenkoPackages = store.GetPackagesInstalled(store.MainPackageIds);
                // Convert the provided xenko version into a valid package version
                PackageVersion packageVersion;
                PackageVersion.TryParse(xenkoVersion, out packageVersion);
                // Retrieve the corresponding package, if it exists
                var xenkoPackage = packageVersion != null
                    ? (xenkoPackages.FirstOrDefault(p => p.Version == packageVersion)
                       ?? xenkoPackages.FirstOrDefault(p => p.Version.Version == packageVersion.Version)) // If no exact match, try a second time without the special version tag (beta, alpha, etc...)
                    : xenkoPackages.FirstOrDefault();
                if (xenkoPackage == null)
                {
                    return(null);
                }

                var packageDirectory = store.GetPackageDirectory(xenkoPackage);
                return(Path.Combine(xenkoSdkDir, store.RepositoryPath, packageDirectory));
            }

            return(null);
        }
Пример #18
0
        public LauncherApp()
        {
            clock = Stopwatch.StartNew();

            // TODO: Add a way to clear the cache more othen than the default nuget (>= 200 files)

            // Check config file
            DebugStep("Load store");

            // Get the package name and executable to launch/update
            var thisExeDirectory = Path.GetDirectoryName(typeof(LauncherApp).Assembly.Location);

            store = new NugetStore(thisExeDirectory);
            store.Manager.Logger          = this;
            store.SourceRepository.Logger = this;

            mainPackage = store.Settings.GetConfigValue(MainPackageKey);
            if (string.IsNullOrWhiteSpace(mainPackage))
            {
                throw new LauncherAppException("Invalid configuration. Expecting [{0}] in config", MainPackageKey);
            }
            store.DefaultPackageId = mainPackage;

            mainExecutable = store.Settings.GetConfigValue(MainExecutableKey);
            if (string.IsNullOrWhiteSpace(mainExecutable))
            {
                throw new LauncherAppException("Invalid configuration. Expecting [{0}] in config", MainExecutableKey);
            }

            var aggregateRepo = (AggregateRepository)store.Manager.SourceRepository;

            foreach (var repo in aggregateRepo.Repositories)
            {
                var progressProvider = repo as IProgressProvider;
                if (progressProvider != null)
                {
                    progressProvider.ProgressAvailable += OnProgressAvailable;
                }
            }

            downloadThreads = new List <Thread>();

            // Update the targets everytime the launcher is used in order to make sure targets are up-to-date
            // with packages installed (rewrite for example after a self-update)
            store.UpdateTargets();
        }
Пример #19
0
 private static bool CreateTargetFilesIfMissing(NugetStore store)
 {
     // If target files doesn't exist, create it
     if (!File.Exists(store.TargetFile) || !File.Exists(store.TargetFileOld))
     {
         try
         {
             store.UpdateTargets();
         }
         catch
         {
             // TODO: localize
             Launcher.DisplayError("Target file was missing and couldn't be updated. Please re-install Xenko");
             return(false);
         }
     }
     return(true);
 }
Пример #20
0
 internal static Task SelfUpdate(IViewModelServiceProvider services, NugetStore store)
 {
     return(Task.Run(async() =>
     {
         var dispatcher = services.Get <IDispatcherService>();
         try
         {
             await UpdateLauncherFiles(dispatcher, store, CancellationToken.None);
         }
         catch (Exception e)
         {
             dispatcher.Invoke(() => selfUpdateWindow?.ForceClose());
             string message = $"An error occurred while updating the launcher. If the problem persists, please reinstall this application.{Environment.NewLine}{Environment.NewLine}Details:{Environment.NewLine}{e}";
             await services.Get <IDialogService>().MessageBox(message, MessageBoxButton.OK, MessageBoxImage.Error);
             // We do not want our users to use the old launcher when a new one is available.
             Environment.Exit(1);
         }
     }));
 }
Пример #21
0
        /// <summary>
        /// Gets the paradox SDK dir.
        /// </summary>
        /// <param name="paradoxVersion">The paradox version. If null, it will get latest version.</param>
        /// <returns></returns>
        public static string FindParadoxSdkDir(string paradoxVersion = null)
        {
            // TODO: Almost duplicate of ParadoxCommandsProxy.FindParadoxSdkDir!!
            // TODO: Maybe move it in some common class somewhere? (in this case it would be included with "Add as link" in VSPackage)
            var paradoxSdkDir = DirectoryHelper.GetInstallationDirectory("Paradox");

            if (paradoxSdkDir == null)
            {
                paradoxSdkDir = Environment.GetEnvironmentVariable("SiliconStudioParadoxDir");
            }

            if (paradoxSdkDir == null)
            {
                return(null);
            }

            // Check if it is a dev directory
            if (File.Exists(Path.Combine(paradoxSdkDir, "build\\Paradox.sln")))
            {
                return(paradoxSdkDir);
            }

            // Check if we are in a root directory with store/packages facilities
            if (NugetStore.IsStoreDirectory(paradoxSdkDir))
            {
                var store = new NugetStore(paradoxSdkDir);

                var paradoxPackages = store.GetPackagesInstalled(store.MainPackageId);
                var paradoxPackage  = paradoxVersion != null
                    ? (paradoxPackages.FirstOrDefault(p => p.Version.ToString() == paradoxVersion)
                       ?? paradoxPackages.FirstOrDefault(p => VersionWithoutSpecialPart(p.Version.ToString()) == VersionWithoutSpecialPart(paradoxVersion)))  // If no exact match, try a second time without the special version tag (beta, alpha, etc...)
                    : paradoxPackages.FirstOrDefault();
                if (paradoxPackage == null)
                {
                    return(null);
                }

                var packageDirectory = store.PathResolver.GetPackageDirectory(paradoxPackage);
                return(Path.Combine(paradoxSdkDir, store.RepositoryPath, packageDirectory));
            }

            return(null);
        }
Пример #22
0
        private static async Task UninstallDependencies(NugetStore store, NugetPackage package)
        {
            foreach (var dependency in package.Dependencies)
            {
                string dependencyId       = dependency.Item1;
                string dependencyIdPrefix = dependencyId.Split('.').First();
                PackageVersionRange dependencyVersionRange = dependency.Item2;

                // Dependency must be from Stride/Xenko and package version must match exactly
                if (((dependencyIdPrefix == "Stride") || (dependencyIdPrefix == "Xenko")) && (dependencyVersionRange.Contains(package.Version)))
                {
                    NugetPackage dependencyPackage = store.FindLocalPackage(dependencyId, package.Version);
                    if (dependencyPackage != null)
                    {
                        await store.UninstallPackage(dependencyPackage, null);
                        await UninstallDependencies(store, dependencyPackage);
                    }
                }
            }
        }
Пример #23
0
        internal LauncherViewModel(IViewModelServiceProvider serviceProvider, NugetStore store)
            : base(serviceProvider)
        {
            if (store == null)
            {
                throw new ArgumentNullException(nameof(store));
            }
            DependentProperties.Add("ActiveVersion", new[] { "ActiveDocumentationPages" });
            this.store   = store;
            store.Logger = this;

            DisplayReleaseAnnouncement();

            VsixPackage = new VsixVersionViewModel(this, store);
            // Commands
            InstallLatestVersionCommand = new AnonymousTaskCommand(ServiceProvider, InstallLatestVersion)
            {
                IsEnabled = false
            };
            OpenUrlCommand   = new AnonymousTaskCommand <string>(ServiceProvider, OpenUrl);
            ReconnectCommand = new AnonymousTaskCommand(ServiceProvider, async() =>
            {
                // We are back online (or so we think)
                IsOffline = false;
                await FetchOnlineData();
            });
            StartStudioCommand = new AnonymousTaskCommand(ServiceProvider, StartStudio)
            {
                IsEnabled = false
            };

            foreach (var devVersion in LauncherSettings.DeveloperVersions)
            {
                var version = new XenkoDevVersionViewModel(this, store, null, devVersion, false);
                xenkoVersions.Add(version);
            }
            FetchOnlineData().Forget();
            LoadRecentProjects();
            uninstallHelper = new UninstallHelper(serviceProvider, store);
            GameStudioSettings.RecentProjectsUpdated += (sender, e) => Dispatcher.InvokeAsync(LoadRecentProjects).Forget();
        }
Пример #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageVersionViewModel"/> class.
 /// </summary>
 /// <param name="launcher">The parent <see cref="LauncherViewModel"/> instance.</param>
 /// <param name="store">The related <see cref="NugetStore"/> instance.</param>
 /// <param name="localPackage">The local package of this version, if a local package exists.</param>
 internal PackageVersionViewModel(LauncherViewModel launcher, NugetStore store, NugetLocalPackage localPackage)
     : base(launcher.SafeArgument("launcher").ServiceProvider)
 {
     if (launcher == null)
     {
         throw new ArgumentNullException(nameof(launcher));
     }
     if (store == null)
     {
         throw new ArgumentNullException(nameof(store));
     }
     Launcher        = launcher;
     Store           = store;
     LocalPackage    = localPackage;
     DownloadCommand = new AnonymousCommand(ServiceProvider, () => Download(true));
     DeleteCommand   = new AnonymousTaskCommand(ServiceProvider, () => Delete(true, true))
     {
         IsEnabled = CanDelete
     };
     UpdateStatusInternal();
 }
Пример #25
0
        private static LauncherErrorCode Uninstall()
        {
            try
            {
                // Kill all running processes
                var path = new UFile(Assembly.GetEntryAssembly().Location).GetFullDirectory().ToWindowsPath();
                if (!UninstallHelper.CloseProcessesInPath(DisplayMessage, "Stride", path))
                {
                    return(LauncherErrorCode.UninstallCancelled); // User cancelled
                }
                // Uninstall packages (they might have uninstall actions)
                var store = new NugetStore(path);
                foreach (var package in store.MainPackageIds.SelectMany(store.GetLocalPackages).FilterStrideMainPackages().ToList())
                {
                    store.UninstallPackage(package, null).Wait();
                }

                foreach (var remainingFiles in Directory.GetFiles(path, "*.lock").Concat(Directory.GetFiles(path, "*.old")))
                {
                    try
                    {
                        File.Delete(remainingFiles);
                    }
                    catch (Exception e)
                    {
                        e.Ignore();
                    }
                }

                PrivacyPolicyHelper.RevokeAllPrivacyPolicy();

                return(LauncherErrorCode.Success);
            }
            catch (Exception)
            {
                return(LauncherErrorCode.ErrorWhileUninstalling);
            }
        }
Пример #26
0
        /// <summary>
        /// Gets the stride SDK dir.
        /// </summary>
        /// <returns></returns>
        internal static async Task <PackageInfo> FindStrideSdkDir(string solution, string packageName = "Stride.VisualStudio.Commands")
        {
            // Resolve the sdk version to load from the solution's package
            var packageInfo = new PackageInfo {
                ExpectedVersion = await PackageSessionHelper.GetPackageVersion(solution), SdkPaths = new List <string>()
            };

            // Check if we are in a root directory with store/packages facilities
            var store = new NugetStore(null);
            NugetLocalPackage stridePackage = null;

            // Try to find the package with the expected version
            if (packageInfo.ExpectedVersion != null && packageInfo.ExpectedVersion >= MinimumVersion)
            {
                // Stride up to 3.0
                if (packageInfo.ExpectedVersion < new PackageVersion(3, 1, 0, 0))
                {
                    stridePackage = store.GetPackagesInstalled(new[] { "Stride" }).FirstOrDefault(package => package.Version == packageInfo.ExpectedVersion);
                    if (stridePackage != null)
                    {
                        var strideSdkDir = store.GetRealPath(stridePackage);

                        packageInfo.LoadedVersion = stridePackage.Version;

                        foreach (var path in new[]
                        {
                            // Stride 2.x and 3.0
                            @"Bin\Windows\Direct3D11",
                            @"Bin\Windows",
                            // Stride 1.x
                            @"Bin\Windows-Direct3D11"
                        })
                        {
                            var fullPath = Path.Combine(strideSdkDir, path);
                            if (Directory.Exists(fullPath))
                            {
                                packageInfo.SdkPaths.AddRange(Directory.EnumerateFiles(fullPath, "*.dll", SearchOption.TopDirectoryOnly));
                                packageInfo.SdkPaths.AddRange(Directory.EnumerateFiles(fullPath, "*.exe", SearchOption.TopDirectoryOnly));
                            }
                        }
                    }
                }
                // Stride 3.1+
                else
                {
                    var logger = new Logger();
                    var(request, result) = await RestoreHelper.Restore(logger, NuGetFramework.ParseFrameworkName(".NETFramework,Version=v4.7.2", DefaultFrameworkNameProvider.Instance), "win", packageName, new VersionRange(packageInfo.ExpectedVersion.ToNuGetVersion()));

                    if (result.Success)
                    {
                        packageInfo.SdkPaths.AddRange(RestoreHelper.ListAssemblies(request, result));
                        packageInfo.LoadedVersion = packageInfo.ExpectedVersion;
                    }
                    else
                    {
                        MessageBox.Show($"Could not restore {packageName} {packageInfo.ExpectedVersion}, this visual studio extension may fail to work properly without it."
                                        + $"To fix this you can either build {packageName} or pull the right version from nugget manually");
                        throw new InvalidOperationException($"Could not restore {packageName} {packageInfo.ExpectedVersion}.");
                    }
                }
            }

            return(packageInfo);
        }
Пример #27
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);
            }
        }
Пример #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PackageStore"/> class.
 /// </summary>
 /// <exception cref="System.InvalidOperationException">Unable to find a valid Xenko installation path</exception>
 private PackageStore()
 {
     // Check if we are in a root directory with store/packages facilities
     store = new NugetStore(null);
 }
Пример #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StrideStoreVersionViewModel"/>
 /// </summary>
 /// <param name="launcher"></param>
 /// <param name="store"></param>
 /// <param name="localPackage"></param>
 /// <param name="major"></param>
 /// <param name="minor"></param>
 internal StrideStoreVersionViewModel(LauncherViewModel launcher, NugetStore store, NugetLocalPackage localPackage, string packageId, int major, int minor)
     : base(launcher, store, localPackage, packageId, major, minor)
 {
     FetchReleaseNotes();
     FetchDocumentation();
 }
Пример #30
0
 internal UninstallHelper(IViewModelServiceProvider serviceProvider, NugetStore store)
 {
     this.serviceProvider            = serviceProvider;
     this.store                      = store;
     store.NugetPackageUninstalling += PackageUninstalling;
 }