Example #1
0
        private static void SwitchToNuGetMode(OperationContext context)
        {
            if (String.IsNullOrEmpty(context.TfsServerUri))
            {
                GeneralUtils.ShowMessage("TFS server uri is missing in Tools->Options->Nuget Tool page", OLEMSGICON.OLEMSGICON_WARNING);
            }

            using (GeneralUtils.StartAnimation())
                using (var progress = GeneralUtils.StartProgressProgress("Back to NuGet",
                                                                         context.Projects.LoadedProjects.Length + 1))
                {
                    foreach (ProjectInfo project in context.Projects.LoadedProjects)
                    {
                        try
                        {
                            progress.Increment();
                            GeneralUtils.ReportStatus($"Switching [{project.Name}]");
                            SwitchProjectToNuGet(project, context);
                        }
                        catch (Exception ex)
                        {
                            GeneralUtils.ShowMessage("Failed to convert project: " + project.Name + ", Error message: " + ex.Message, OLEMSGICON.OLEMSGICON_CRITICAL);
                        }
                    }

                    progress.Increment();
                    context.Projects.ReOpenSolution();
                    GeneralUtils.ShowMessage("Conversion to NuGet mode finished successfully.");
                }
        }
        private static async TPL.Task <IDisposable> UpdateNuGetDependencies(
            ProjectInfo project,
            OperationContext context,
            List <NuGetPackageInfo> dependencies)
        {
            if (dependencies.Count != 0)
            {
                foreach (var package in dependencies)
                {
                    if (project.NuGetPackageReferences.Contains(package.Id))
                    {
                        GeneralUtils.ReportStatus($"Update dependencies of {project.Name}");

                        #region External Proc

                        using (var prc = new System.Diagnostics.Process())
                        {
                            prc.StartInfo.FileName = $@"{_utilitiesPath}\NuGet.exe";
                            // https://msdn.microsoft.com/en-us/library/ms164311.aspx
                            prc.StartInfo.Arguments = $@"update ""{project.PackageConfigFile}"" -repositoryPath {package.RepositoryPath} -source ""{string.Join(";", context.PackagesSources)};https://api.nuget.org/v3/index.json"" -id {package.Id} -noninteractive";
                            if (context.PreRelease)
                            {
                                prc.StartInfo.Arguments += " -prerelease";
                            }
                            prc.StartInfo.UseShellExecute = false;
                            prc.StartInfo.CreateNoWindow  = true;
                            prc.StartInfo.ErrorDialog     = false;

                            await TPL.Task.Factory.StartNew(() =>
                            {
                                prc.Start();
                                if (!prc.WaitForExit(30 * 1000))
                                {
                                    Trace.WriteLine($@"""{prc.StartInfo.FileName}"" {prc.StartInfo.Arguments}");
                                    MessageBox.Show($"Fail to update dependencies (timeout)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }, TPL.TaskCreationOptions.LongRunning);

                            if (prc.ExitCode != 0)
                            {
                                MessageBox.Show($"Fail to update dependencies", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }

                        #endregion // External Proc
                    }
                }
            }

            var result = Disposable.Empty;
            return(result);
        }
        /// <summary>
        /// Builds (projects) the and update (NuGets).
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="packagesToBuild">The packages to build.</param>
        /// <param name="currentProgress">The current progress.</param>
        private static async TPL.Task <DialogResult> BuildAndUpdate(OperationContext context, List <NuGetPackageInfo> packagesToBuild, GeneralUtils.StatusReporter currentProgress)
        {
            for (int i = 0; i < packagesToBuild.Count; i++)
            {
                currentProgress.Report(i);
                NuGetPackageInfo p = packagesToBuild[i];
                GeneralUtils.ReportStatus($"CurrentPackage = {p.Name}");

                string errorMsg = await UpdateSinglePackage(p, context);

                #region Exception Handling (Abort, Retry, Ignore)

                if (errorMsg != null)
                {
                    string       msg    = $@"Failed to update package {p.Id}. 
Error: {errorMsg}.

{context.RecoveredPackages.Count} NuGet packages have been recovered so far.
{context.PackagesUpdatedSoFar.Count} NuGet packages have been updated so far.

Do you want to rollback the state?
OK:     will try to reset the state to the previous state.
Cancel: will stop the processing and let you fix the problem manually.
        you can retry to update after fixing the problem.";
                    DialogResult option = MessageBox.Show(msg, "Execution Problem", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                    switch (option)
                    {
                    case DialogResult.OK:
                        Rollback(context);
                        return(DialogResult.Abort);

                    //return;
                    //case 4: // Retry
                    //    i--;
                    //    continue;
                    case DialogResult.Cancel:
                        return(DialogResult.Cancel);
                    }
                }

                #endregion // Exception Handling (Abort, Retry, Ignore)
            }

            return(DialogResult.OK);
        }
        private static async void Rollback(
            OperationContext context)
        {
            // Recover the old packages
            for (int i = 0; i < context.PackagesUpdatedSoFar.Count; i++)
            {
                NuGetPackageInfo p = context.PackagesUpdatedSoFar[i];
                GeneralUtils.ReportStatus($"Rollback: {p.Name}");

                string errorMsg = await RollbackPackage(p, context);

                if (errorMsg != null)
                {
                    string       msg    = $@"Failed to recover package {p.Id}. Error: {errorMsg}.
{context.RecoveredPackages.Count} NuGet packages have been recovered so far.
Choose one of the following actions: 
    Abort:  to stop the process
            (you can repeat the process after fixing the problem).
    Ignore: to continue recovering the other packages
    Retry:  to try again (from current stage).";
                    DialogResult option = MessageBox.Show(msg, "Rollback",
                                                          MessageBoxButtons.AbortRetryIgnore,
                                                          MessageBoxIcon.Question,
                                                          MessageBoxDefaultButton.Button1);
                    switch (option)
                    {
                    case DialogResult.Abort:
                        return;

                    case DialogResult.Retry:
                        i--;
                        continue;

                    case DialogResult.Ignore:
                        continue;
                    }
                }
            }
            Directory.Delete(context.ArchiveSession);
            GeneralUtils.ShowMessage($"{context.RecoveredPackages.Count} NuGet packages have been restored");
        }
Example #5
0
 private static void SwitchToDebugMode(OperationContext context)
 {
     using (GeneralUtils.StartAnimation())
         using (var progress = GeneralUtils.StartProgressProgress("To Project Reference",
                                                                  context.Projects.LoadedProjects.Length))
         {
             foreach (ProjectInfo project in context.Projects.LoadedProjects)
             {
                 try
                 {
                     progress.Increment();
                     GeneralUtils.ReportStatus($"Switching [{project.Name}]");
                     SwitchProjectToDebug(project, context);
                 }
                 catch (Exception ex)
                 {
                     GeneralUtils.ShowMessage("Failed to convert project: " + project.Name + ", Error message: " + ex.Message, OLEMSGICON.OLEMSGICON_CRITICAL);
                 }
             }
         }
     context.Projects.ReOpenSolution();
     GeneralUtils.ShowMessage("Conversion to debug mode finished successfully.");
 }
Example #6
0
        public /*async*/ Task <bool> BuildProject(ProjectInfo project)
        {
            DTE           dte           = (DTE)_serviceProvider.GetService(typeof(DTE));
            SolutionBuild solutionBuild = dte.Solution.SolutionBuild;

            string solutionConfiguration = solutionBuild.ActiveConfiguration.Name;

            GeneralUtils.ReportStatus($"Build: {project.Name}");

            // TODO: 2017-01 Bnaya, Use the async version
            solutionBuild.BuildProject(solutionConfiguration, project.FullName, true);
            //await TRD.Tasks.Task.Factory.StartNew(() =>
            //            solutionBuild.BuildProject(solutionConfiguration, project.FullName, true),
            //            TaskCreationOptions.LongRunning);

            bool compiledOK = (solutionBuild.LastBuildInfo == 0);

            if (!compiledOK && System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }
            return(TRD.Tasks.Task.FromResult(compiledOK));
        }
        private static TPL.Task RecoverOldVersionFromArchive(
            NuGetPackageInfo packageInfo,
            OperationContext context)
        {
            GeneralUtils.ReportStatus($"Recover old version from archive");

            return(TPL.Task.Factory.StartNew(() =>
            {
                string sourcePackagePath = Path.Combine(context.ArchiveSession, packageInfo.PackageFileName);
                string targetPackagePath = Path.Combine(packageInfo.RepositoryPath, packageInfo.PackageFileName);

                if (File.Exists(sourcePackagePath))
                {
                    File.Move(sourcePackagePath, targetPackagePath);
                }

                // Delete the new version from the repository
                string newPackagePath = Path.Combine(packageInfo.RepositoryPath, packageInfo.NewPackageName);
                if (File.Exists(newPackagePath))
                {
                    File.Delete(newPackagePath);
                }
            }, TPL.TaskCreationOptions.LongRunning));
        }
        /// <summary>
        /// Handle the process of Updating the NuGet packages.
        /// </summary>
        /// <param name="preRelease">if set to <c>true</c> [pre release].</param>
        public static async void UpdateNuGetPackages(bool preRelease)
        {
            using (GeneralUtils.StartAnimation())
                using (var progress = GeneralUtils.StartProgressProgress("NuGet Upgrade", UPDATE_NUGET_COUNT))
                {
                    try
                    {
                        GeneralUtils.ReportStatus($"Start NuGet Upgrade: pre-release = {preRelease}");
                        OperationContext context = LoadNuGetPackages(preRelease);

                        #region Validation

                        if (context == null)
                        {
                            return;
                        }

                        if (context.Projects.LoadedProjects.Length == 0)
                        {
                            return;
                        }

                        if (context.Projects.IsSolutionInDebugMode())
                        {
                            GeneralUtils.ShowMessage("Solution is in debug mode. Switch back to NuGet mode before updating the packages.", OLEMSGICON.OLEMSGICON_WARNING);
                            return;
                        }

                        if (!await context.Projects.BuildSolution())
                        {
                            if (MessageBox.Show(@"Make sure that the solution is build 
with no errors, before NuGet upgrade!
Do you want to continue", "Pre build solution",
                                                MessageBoxButtons.YesNo,
                                                MessageBoxIcon.Question) == DialogResult.No)
                            {
                                return;
                            }
                        }

                        #endregion // Validation

                        // Build only packages with corresponding projects
                        // in the current solution
                        var packagesToBuild = (from p in context.PackagesInfo
                                               where p.ProjectInfo != null
                                               select p).ToList();

                        // Add NuGet packages that have no corrseponding projects in current solution,
                        // but depend on other NuGet packages that need to upgrade
                        var dependentPackagesWithoutProjects = GetDependentPackagesWithoutProjects(context);
                        packagesToBuild.AddRange(dependentPackagesWithoutProjects);

                        #region Validation

                        if (packagesToBuild.Count == 0)
                        {
                            GeneralUtils.ShowMessage(@"No NuGet package needs to be updated.
Goto: Tools -> Options -> NuGet Tool
and add path for local NuGet repositories.");
                            return;
                        }

                        #endregion // Validation

                        //RemoveCachedNuGetFiles();
                        context.Projects.CleanSolution();
                        progress.Report(1);

                        using (var currentProgress = GeneralUtils.StartProgressProgress("NuGet: Current", packagesToBuild.Count))
                        {
                            DialogResult result =
                                await BuildAndUpdate(context, packagesToBuild, currentProgress);

                            switch (result)
                            {
                            case DialogResult.Cancel:
                                GeneralUtils.ReportStatus("Operation Canceled");
                                return;

                            case DialogResult.Abort:
                                GeneralUtils.ReportStatus("Operation aborted");
                                return;
                            }
                            currentProgress.Report(packagesToBuild.Count);
                        }

                        progress.Report(5);
                        if (context.ShouldArchiveOldNuGet)
                        {
                            GeneralUtils.ReportStatus($"NuGet: Archive");
                            await CreateArchiveZipFile(context.ArchiveSession);
                        }

                        GeneralUtils.ReportStatus($"NuGet: Build");
                        progress.Report(6);
                        // Build all the other projects that don't have corresponding NuGet packages
                        await BuildProjectsWithNoPackages(context);

                        progress.Report(7);

                        GeneralUtils.ReportStatus($"NuGet: Re-open projects");
                        await TPL.Task.Factory.StartNew(() =>
                                                        context.Projects.ReOpenSolution(),
                                                        TPL.TaskCreationOptions.LongRunning);

                        progress.Report(8);
                        #region Clipboard.SetText(context.ArchiveFolder)

                        try
                        {
                            Clipboard.SetText(context.ArchiveFolder);
                        }
                        catch { }

                        #endregion // Clipboard.SetText(context.ArchiveFolder)

                        GeneralUtils.ShowMessage($@"{context.PackagesUpdatedSoFar.Count} NuGet packages have been updated
Old packages moved to [{context.ArchiveFolder}] + copied to the clipboard");
                    }
                    catch (FileNotFoundException ex)
                    {
                        MessageBox.Show($@"Make sure to build the solution before running the tool

{ex}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
        }