コード例 #1
0
 private void RestoreAll(IEnumerable <Project> projects, ConverterUpdateViewModel model)
 {
     foreach (var project in projects)
     {
         _restorer.RestorePackages(project);
     }
 }
コード例 #2
0
        public ConvertProgressViewer(ConverterUpdateViewModel model, Action close)
        {
            _close = close;

            DataContext = model;
            InitializeComponent();
        }
コード例 #3
0
        private void RefreshSolution(Solution sln, IEnumerable <Project> projects, ConverterUpdateViewModel model)
        {
            try
            {
                var projectInfos = projects.Select(p => new ProjectInfo(p.GetFullName(), p.Name)).ToList();
                var slnPath      = sln.FullName;
                _logger.WriteLine("Closing solution");
                sln.Close();
                int counter = 0;
                int total   = projectInfos.Count(p => !string.IsNullOrEmpty(p.FullName));
                foreach (var project in projectInfos.Where(p => !string.IsNullOrEmpty(p.FullName)))
                {
                    counter++;
                    model.Status = $"Fixing restore style in'{project.Name}/{project.FullName}'   ({counter}/{total}";
                    _logger.WriteLine(model.Status);
                    AddRestoreProjectStyle(project.FullName, project, model);
                }

                sln.Open(slnPath);
                _logger.WriteLine("Reopen the solution");
            }
            catch (Exception e)
            {
                model.Log = $"Exception while working with restore style property.  Do this manually.";
                _logger.WriteLine(model.Log);
                _logger.WriteLine(e.ToString());
            }
        }
コード例 #4
0
 private void RemoveDependencyFiles(IEnumerable <Project> projects, ConverterUpdateViewModel model)
 {
     foreach (var project in projects)
     {
         model.Status = $"Removing dependency files for '{project.Name}'";
         _logger.WriteLine(model.Status);
         RemoveDependencyFiles(project);
     }
 }
コード例 #5
0
 private void AddRestoreProjectStyle(string path, ProjectInfo project, ConverterUpdateViewModel model)
 {
     try
     {
         const string NS         = "http://schemas.microsoft.com/developer/msbuild/2003";
         var          doc        = XDocument.Load(path);
         var          properties = doc.Descendants(XName.Get("PropertyGroup", NS)).FirstOrDefault();
         properties?.LastNode.AddAfterSelf(
             new XElement(XName.Get("RestoreProjectStyle", NS), "PackageReference"));
         _logger.WriteLine($"Fixed projectstyle in ");
         doc.Save(path);
     }
     catch (Exception e)
     {
         model.Log = $"Exception: Project {project.Name}/{project.FullName},  Exception: {e.Message},{e}";
         _logger.WriteLine(model.Log);
     }
 }
コード例 #6
0
        private IDictionary <string, IEnumerable <PackageConfigEntry> > RemoveAndCachePackages(
            IEnumerable <Project> projects, ConverterUpdateViewModel model, CancellationToken token)
        {
            var installedPackages =
                new Dictionary <string, IEnumerable <PackageConfigEntry> >(StringComparer.OrdinalIgnoreCase);
            var projectList = projects.ToList();
            int total       = projectList.Count;

            foreach (var project in projectList)
            {
                token.ThrowIfCancellationRequested();

                model.Status =
                    $"{model.Count}/{total}  Retrieving and removing old package format for '{project.Name}'";
                _logger.WriteLine(model.Status);

                var packages = _services.GetInstalledPackages(project)
                               .Select(p => new PackageConfigEntry(p.Id, p.VersionString))
                               .ToArray();
                var fullname = project.GetFullName();
                if (fullname != null)
                {
                    installedPackages.Add(fullname, packages);
                    _logger.WriteLine($"{project.Name} added {packages.Length} packages");
                    RemovePackages(project, packages.Select(p => p.Id), token, model);
                }
                else
                {
                    model.Log = $"{project.Name} not modified, missing fullname";
                    _logger.WriteLine(model.Log);
                }

                model.Count++;
            }

            return(installedPackages);
        }
コード例 #7
0
        private void InstallPackages(IEnumerable <Project> projects,
                                     IDictionary <string, IEnumerable <PackageConfigEntry> > installedPackages, ConverterUpdateViewModel model,
                                     CancellationToken token)
        {
            var actualProjects = projects.Where(p => p.GetFullName() != null).ToList();

            _logger.WriteLine($"Projects: {actualProjects.Count}    Retrived packages: {installedPackages.Count}");
            int countProjects = 0;

            foreach (var project in actualProjects)
            {
                countProjects++;
                token.ThrowIfCancellationRequested();
                var exist        = installedPackages.TryGetValue(project.GetFullName(), out var packages);
                var packagecount = exist ? packages.Count() : 0;

                _logger.WriteLine($"({countProjects}/{actualProjects.Count})  Project {project.Name}/{project.GetFullName()}, packages to install: {packagecount} ");

                if (packagecount == 0)
                {
                    continue;
                }

                try
                {
                    model.Status =
                        $"({countProjects}/{actualProjects.Count})  Adding PackageReferences: {project.Name}";
                    int counter       = 0;
                    int countPackages = packages.Count();
                    foreach (var package in packages)
                    {
                        try
                        {
                            _installer.InstallPackage(null, project, package.Id, package.Version, false);
                            counter++;
                            model.Log = $"({counter}/{countPackages}) Added package {package.Id}";
                            _logger.WriteLine(model.Log);
                        }
                        catch (Exception e)
                        {
                            model.Log = $"Exception installing {package.Id} ({e})";
                            _logger.WriteLine(model.Log);
                        }
                    }

                    model.Status =
                        $"Added PackageReferences to {project.Name}/{project.FullName},  {counter} out of {packages.Count()} included";
                    _logger.WriteLine(model.Status);
                    model.Count++;

                    System.Threading.Thread.Sleep(1000);
                }
                catch (NotImplementedException e)
                {
                    Trace.WriteLine(e);
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Removes packages. Will do a couple of passes in case packages rely on each other
        /// </summary>
        /// <param name="project"></param>
        /// <param name="ids"></param>
        /// <param name="token"></param>
        /// <param name="model"></param>
        private bool RemovePackages(Project project, IEnumerable <string> ids, CancellationToken token,
                                    ConverterUpdateViewModel model)
        {
            var retryCount  = new ConcurrentDictionary <string, int>(StringComparer.OrdinalIgnoreCase);
            var packages    = new Queue <string>(ids);
            var maxRetry    = packages.Count + 1;
            int maxAttempts = maxRetry * packages.Count;
            int counter     = 0;

            _logger.WriteLine($"{project.Name}: Packages: {packages.Count}, maxattempts: {maxAttempts}");
            while (packages.Count > 0 && counter < maxAttempts)
            {
                counter++;
                token.ThrowIfCancellationRequested();

                var package = packages.Dequeue();

                try
                {
                    model.Log = $"Uninstalling {package}";
                    _logger.WriteLine(model.Log + $" (counter = {counter})");

                    _uninstaller.UninstallPackage(project, package, false);
                    model.Log = $"Uninstalled {package}";
                    _logger.WriteLine(model.Log);
                    counter = 0;
                }
                catch (Exception e)
                {
                    if (e is InvalidOperationException)
                    {
                        model.Log = $"Invalid operation exception when uninstalling {package} ";
                        _logger.WriteLine(model.Log);
                        Debug.WriteLine(e.Message);
                    }
                    else
                    {
                        model.Log = $"Exception uninstalling {package} ";
                        _logger.WriteLine(model.Log);
                        Debug.WriteLine(e);
                    }

                    retryCount.AddOrUpdate(package, 1, (_, count) => count + 1);

                    if (retryCount[package] < maxRetry)
                    {
                        model.Log = $"{package} added back to queue";
                        _logger.WriteLine(model.Log);
                        packages.Enqueue(package);
                    }
                }
            }

            if (counter == maxAttempts)
            {
                model.Log = $"Could not uninstall all packages in {project.Name}";
                _logger.WriteLine(model.Log);
                System.Threading.Thread.Sleep(2000);
            }

            return(!retryCount.Values.Any(v => v >= maxRetry));
        }
コード例 #9
0
        public async Task ShowAsync(Solution sln, Action <ConverterUpdateViewModel, CancellationToken> action)
        {
            if (IsUnsaved(sln))
            {
                MessageDialog.Show("Save before conversion.", "Solution and projects needs to be saved before converting to project.json", MessageDialogCommandSet.Ok);
                return;
            }

            var model = new ConverterUpdateViewModel();

            using (var cts = new CancellationTokenSource())
            {
                // This is run on the UI thread, so we capture this before we do anything else
                var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

                var viewer = new ConvertProgressViewer(model, cts.Cancel);
                var tcs    = new TaskCompletionSource <bool>();

                var task = Task.Run(() =>
                {
                    try
                    {
                        action(model, cts.Token);
                        tcs.SetResult(true);
                    }
                    catch (OperationCanceledException)
                    {
                        tcs.SetCanceled();
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                    finally
                    {
                        cts.Cancel();
                    }
                });

                var result = viewer.ShowModal(cts.Token);

                await tcs.Task.ContinueWith(r =>
                {
                    if (r.IsCanceled)
                    {
                        MessageDialog.Show("Conversion incomplete", "Conversion to project.json dependency was canceled. Please revert any changes and try again.", MessageDialogCommandSet.Ok);
                    }
                    else if (r.IsFaulted)
                    {
                        const string url = "https://github.com/twsouthwick/NuGetPackageConfigConverter/";

                        if (MessageDialog.Show("Conversion failed", $"An unexpected error occured. Please open an issue at {url} with the contents on the clipboard. Press OK to be taken to the issue tracker.", MessageDialogCommandSet.OkCancel) == MessageDialogCommand.Ok)
                        {
                            var error = r.Exception?.ToString();

                            if (!string.IsNullOrEmpty(error))
                            {
                                System.Windows.Clipboard.SetText(error);
#if !DEBUG
                                System.Diagnostics.Process.Start($"{url}issues/new");
#endif
                            }
                        }
                    }
                    else
                    {
                        MessageDialog.Show("Conversion complete", "Conversion to project.json dependency is complete. Some files may have been removed by uninstalling the packages and not added back. Please ensure project builds and runs before committing any changes.", MessageDialogCommandSet.Ok);
                    }
                }, taskScheduler);
            }
        }
コード例 #10
0
        private IDictionary <string, IEnumerable <PackageConfigEntry> > RemoveAndCachePackages(IEnumerable <KeyValuePair <Project, ProjectItem> > items, ConverterUpdateViewModel model, CancellationToken token)
        {
            var installedPackages = new Dictionary <string, IEnumerable <PackageConfigEntry> >(StringComparer.OrdinalIgnoreCase);

            foreach (var item in items)
            {
                token.ThrowIfCancellationRequested();

                var project = item.Key;
                var config  = item.Value;

                model.Status = $"Removing package.config: {project.Name}";

                var packages = PackageConfigEntry.ParseFile(config.FileNames[0]);

                if (packages.Any())
                {
                    installedPackages.Add(project.FullName, packages);
                    _restorer.RestorePackages(project);

                    if (!RemovePackages(project, packages.Select(p => p.Id), token))
                    {
                        // Add warning that forcing deletion of package.config
                        config.Delete();
                    }
                }
                else
                {
                    config.Delete();
                }

                project.Save();

                model.Count++;
            }

            return(installedPackages);
        }
コード例 #11
0
        private void InstallPackages(Solution sln, IDictionary <string, IEnumerable <PackageConfigEntry> > installedPackages, ConverterUpdateViewModel model, CancellationToken token)
        {
            foreach (var project in sln.GetProjects())
            {
                token.ThrowIfCancellationRequested();

                try
                {
                    IEnumerable <PackageConfigEntry> packages;
                    if (installedPackages.TryGetValue(project.FullName, out packages))
                    {
                        model.Status = $"Adding packages back via project.json: {project.Name}";

                        foreach (var package in packages)
                        {
                            try
                            {
                                _installer.InstallPackage(null, project, package.Id, package.Version, false);
                            }
                            catch (Exception e)
                            {
                                Trace.WriteLine(e);
                            }
                        }

                        model.Count++;
                    }
                }
                catch (NotImplementedException e)
                {
                    Trace.WriteLine(e);
                }
            }
        }