private static void UpgradeProject(string sourceProjectFilePath, string destProjectFilePath, IVsUpgradeLogger pLogger, string projectName) { var projectData = new ProjectUpgradeHelper(sourceProjectFilePath); if (IsNeedUpdateNemerleBinPathRootProperty(projectData.NemerleBinPathRoot)) { projectData.NemerleBinPathRoot.Value = NetFrameworkProjectConstants.NemerleBinPathRoot; projectData.NemerleBinPathRoot.SetAttributeValue("Condition", " '$(NemerleBinPathRoot)' == '' "); } else if (!Utils.Eq(projectData.NemerleBinPathRoot.Value, NetFrameworkProjectConstants.NemerleBinPathRoot)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_WARNING, projectName, sourceProjectFilePath, "The NemerleBinPathRoot property changed by user. You must update it manually."); } projectData.NemerleVersion.Value = NetFrameworkProjectConstants.NemerleVersion; if (IsNeedUpdateNemerleProperty(projectData.NemerleProperty)) { projectData.NemerleProperty.Value = NetFrameworkProjectConstants.NemerleProperty; } else if (!Utils.Eq(projectData.NemerleProperty.Value, NetFrameworkProjectConstants.NemerleProperty)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_WARNING, projectName, sourceProjectFilePath, "The Nemerle property changed by user. You must update it manually."); } projectData.NemerleProperty.Document.Save(destProjectFilePath); }
internal bool BackupProject(string backupLocation, string xprojLocation, string projectName, IVsUpgradeLogger pLogger) { var directory = Path.GetDirectoryName(xprojLocation); // Back up the xproj and project.json to the backup location. var xprojName = Path.GetFileName(xprojLocation); var backupXprojPath = Path.Combine(backupLocation, xprojName); var projectJsonPath = Path.Combine(directory, "project.json"); var backupProjectJsonPath = Path.Combine(backupLocation, "project.json"); // We don't need to check the xproj path. That's being given to us by VS and was specified in the solution. if (!_fileSystem.FileExists(projectJsonPath)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, projectJsonPath, string.Format(VSResources.XprojMigrationFailedProjectJsonFileNotFound, projectName, projectJsonPath)); return(false); } pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, xprojLocation, string.Format(VSResources.MigrationBackupFile, xprojLocation, backupXprojPath)); pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, projectJsonPath, string.Format(VSResources.MigrationBackupFile, projectJsonPath, backupProjectJsonPath)); _fileSystem.CopyFile(xprojLocation, backupXprojPath, true); _fileSystem.CopyFile(projectJsonPath, backupProjectJsonPath, true); return(true); }
public int UpgradeProject(string sourceProjectFilePath, uint fUpgradeFlag, string bstrCopyLocation, out string upgradedFullyQualifiedFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory) { pUpgradeRequired = 1; pguidNewProjectFactory = Guid.Empty; upgradedFullyQualifiedFileName = null; var projectName = Path.GetFileNameWithoutExtension(sourceProjectFilePath); try { var destProjectFilePath = sourceProjectFilePath; var backupedProject = string.IsNullOrEmpty(bstrCopyLocation) ? null : Path.Combine(bstrCopyLocation, Path.GetFileName(sourceProjectFilePath)); var projectFileName = Path.GetFileName(sourceProjectFilePath); BackupProjectForUpgrade(sourceProjectFilePath, pLogger, ref destProjectFilePath, backupedProject, projectName); upgradedFullyQualifiedFileName = destProjectFilePath; UpgradeProject(sourceProjectFilePath, destProjectFilePath, pLogger, projectName); pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, sourceProjectFilePath, "Project converted successfully"); // Tell to VS which the project converted successfull. It's a magic! :) pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_STATUSMSG, projectName, sourceProjectFilePath, // "Converted" should NOT be localized - it is referenced in the XSLT used to display the UpgradeReport "Converted"); return(VSConstants.S_OK); } catch (Exception ex) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, sourceProjectFilePath, "Error during project convertion: " + ex.Message); return(VSConstants.E_FAIL); } }
public int UpgradeProject(string sourceProjectFilePath, uint fUpgradeFlag, string bstrCopyLocation, out string upgradedFullyQualifiedFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory) { pUpgradeRequired = 1; pguidNewProjectFactory = Guid.Empty; upgradedFullyQualifiedFileName = null; var projectName = Path.GetFileNameWithoutExtension(sourceProjectFilePath); try { var destProjectFilePath = sourceProjectFilePath; var backupedProject = string.IsNullOrEmpty(bstrCopyLocation) ? null : Path.Combine(bstrCopyLocation, Path.GetFileName(sourceProjectFilePath)); var projectFileName = Path.GetFileName(sourceProjectFilePath); BackupProjectForUpgrade(sourceProjectFilePath, pLogger, ref destProjectFilePath, backupedProject, projectName); upgradedFullyQualifiedFileName = destProjectFilePath; UpgradeProject(sourceProjectFilePath, destProjectFilePath, pLogger, projectName); pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, sourceProjectFilePath, "Project converted successfully"); // Tell to VS which the project converted successfull. It's a magic! :) pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_STATUSMSG, projectName, sourceProjectFilePath, // "Converted" should NOT be localized - it is referenced in the XSLT used to display the UpgradeReport "Converted"); return VSConstants.S_OK; } catch (Exception ex) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, sourceProjectFilePath, "Error during project convertion: " + ex.Message); return VSConstants.E_FAIL; } }
internal bool MigrateProject(string projectDirectory, string xprojLocation, string projectName, IVsUpgradeLogger pLogger) { // We count on dotnet.exe being on the path var pInfo = new ProcessStartInfo("dotnet.exe", $"migrate --skip-backup -s -x \"{xprojLocation}\" \"{projectDirectory}\""); pInfo.UseShellExecute = false; pInfo.RedirectStandardError = true; pInfo.RedirectStandardOutput = true; // First time setup isn't necessary for migration, and causes a long pause with no indication anything is happening. // Skip it. pInfo.EnvironmentVariables.Add("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "true"); var process = _runner.Start(pInfo); // Create strings to hold the output and error text var outputBuilder = new StringBuilder(); var errBuilder = new StringBuilder(); process.AddOutputDataReceivedHandler(o => { outputBuilder.AppendLine(o); }); process.AddErrorDataReceivedHandler(e => { errBuilder.AppendLine(e); }); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); // TODO: we need to read the output from the migration report in addition to console output. // We'll still want to read console output in case of a bug in the dotnet cli, and it errors with some exception // https://github.com/dotnet/roslyn-project-system/issues/507 var output = outputBuilder.ToString().Trim(); var err = errBuilder.ToString().Trim(); if (!string.IsNullOrEmpty(output)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, xprojLocation, output); } if (!string.IsNullOrEmpty(err)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_WARNING, projectName, xprojLocation, err); } if (process.ExitCode != 0) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, xprojLocation, string.Format(VSResources.XprojMigrationFailed, projectName, projectDirectory, xprojLocation, process.ExitCode)); return(false); } return(true); }
internal (string logFile, int exitCode) MigrateProject(string solutionDirectory, string projectDirectory, string xprojLocation, string projectName, IVsUpgradeLogger pLogger) { var logFile = _fileSystem.GetTempDirectoryOrFileName(); // We count on dotnet.exe being on the path var pInfo = new ProcessStartInfo("dotnet.exe", GetDotnetArguments(xprojLocation, projectDirectory, logFile)) { UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true, WorkingDirectory = solutionDirectory }; // First time setup isn't necessary for migration, and causes a long pause with no indication anything is happening. // Skip it. pInfo.EnvironmentVariables.Add("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "true"); var process = _runner.Start(pInfo); // Create strings to hold the output and error text var outputBuilder = new StringBuilder(); var errBuilder = new StringBuilder(); process.AddOutputDataReceivedHandler(o => { outputBuilder.AppendLine(o); }); process.AddErrorDataReceivedHandler(e => { errBuilder.AppendLine(e); }); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); var output = outputBuilder.ToString().Trim(); var err = errBuilder.ToString().Trim(); if (!string.IsNullOrEmpty(output)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, xprojLocation, output); } if (!string.IsNullOrEmpty(err)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_WARNING, projectName, xprojLocation, err); } return(logFile, process.ExitCode); }
public void Log(__VSUL_ERRORLEVEL level, string text) { if (_logger != null) { ErrorHandler.ThrowOnFailure(_logger.LogMessage((uint)level, _projectName, _projectFile, text)); } }
int IVsSolutionEventsProjectUpgrade.OnAfterUpgradeProject(IVsHierarchy pHierarchy, uint fUpgradeFlag, string bstrCopyLocation, SYSTEMTIME stUpgradeTime, IVsUpgradeLogger pLogger) { NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); Debug.Assert(pHierarchy != null); var upgradedProject = VsHierarchyUtility.GetProjectFromHierarchy(pHierarchy); var upgradedNuGetProject = await EnvDTEProjectUtility.GetNuGetProjectAsync(upgradedProject, _solutionManager); if (ProjectRetargetingUtility.IsProjectRetargetable(upgradedNuGetProject)) { var packagesToBeReinstalled = await ProjectRetargetingUtility.GetPackagesToBeReinstalled(upgradedNuGetProject); if (packagesToBeReinstalled.Any()) { pLogger.LogMessage((int)__VSUL_ERRORLEVEL.VSUL_ERROR, upgradedProject.Name, upgradedProject.Name, string.Format(CultureInfo.CurrentCulture, Strings.ProjectUpgradeAndRetargetErrorMessage, string.Join(", ", packagesToBeReinstalled.Select(p => p.Id)))); } } }); return(VSConstants.S_OK); }
internal (string projFile, bool success) LogReport(string logFile, int processExitCode, string projectName, string xprojLocation, IVsUpgradeLogger pLogger) { (string, bool) LogAndReturnError() { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, xprojLocation, string.Format(VSResources.XprojMigrationFailedCannotReadReport, logFile)); pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, xprojLocation, GetDotnetGeneralErrorString(projectName, xprojLocation, Path.GetDirectoryName(xprojLocation), logFile, processExitCode)); return(string.Empty, false); } if (!_fileSystem.FileExists(logFile)) { return(LogAndReturnError()); } var mainReport = JsonConvert.DeserializeObject <MigrationReport>(_fileSystem.ReadAllText(logFile)); if (mainReport == null) { return(LogAndReturnError()); } // We're calling migrate on a single project and have don't follow turned on. We shouldn't see any other migration reports. Assumes.True(mainReport.ProjectMigrationReports.Count == 1); var report = mainReport.ProjectMigrationReports[0]; if (report.Failed) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, xprojLocation, GetDotnetGeneralErrorString(projectName, xprojLocation, report.ProjectDirectory, logFile, processExitCode)); } foreach (var error in report.Errors) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, xprojLocation, error.FormattedErrorMessage); } foreach (var warn in report.Warnings) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_WARNING, projectName, xprojLocation, warn); } _fileSystem.RemoveFile(logFile); return(report.OutputMSBuildProject, report.Succeeded); }
internal HResult BackupAndDeleteGlobalJson(string solutionDirectory, IVsSolution solution, string backupLocation, string projectName, IVsUpgradeLogger pLogger) { string globalJson = Path.Combine(solutionDirectory, "global.json"); if (_fileSystem.FileExists(globalJson)) { // We want to set up the remover if it hasn't been set up already. If it has been set up already, then we can just return, as backup // and parsing for the sdk element will already have occurred. if (!_globalJsonSetup.SetupRemoval(solution, _serviceProvider, _fileSystem)) { return(HResult.OK); } // We want to find the root backup directory that VS created for backup. We can't just assume it's solution/Backup, because VS will create // a new directory if that already exists. So just iterate up until we find the correct directory. solutionDirectory = solutionDirectory.TrimEnd(Path.DirectorySeparatorChar); string rootBackupDirectory = backupLocation; string levelUpBackupDirectory = Path.GetDirectoryName(rootBackupDirectory).TrimEnd(Path.DirectorySeparatorChar); while (!StringComparers.Paths.Equals(levelUpBackupDirectory, solutionDirectory)) { rootBackupDirectory = levelUpBackupDirectory; levelUpBackupDirectory = Path.GetDirectoryName(levelUpBackupDirectory).TrimEnd(Path.DirectorySeparatorChar); } // rootBackupDirectory is now the actual root backup directory. Back up the global.json and delete the existing one string globalJsonBackupPath = Path.Combine(rootBackupDirectory, "global.json"); pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, globalJson, string.Format(VSResources.MigrationBackupFile, globalJson, globalJsonBackupPath)); _fileSystem.CopyFile(globalJson, globalJsonBackupPath, true); // Now parse the global.json, and remove the "sdk" element if it exists JObject json = JsonConvert.DeserializeObject <JObject>(_fileSystem.ReadAllText(globalJson)); if (json.Remove("sdk")) { try { _fileSystem.WriteAllText(globalJson, JsonConvert.SerializeObject(json)); } catch (IOException ex) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, globalJson, ex.Message); return(ex.HResult); } } } return(HResult.OK); }
internal HResult BackupAndDeleteGlobalJson(string solutionDirectory, IVsSolution solution, string backupLocation, string xprojLocation, string projectName, IVsUpgradeLogger pLogger) { var globalJson = Path.Combine(solutionDirectory, "global.json"); if (_fileSystem.FileExists(globalJson)) { // We want to find the root backup directory that VS created for backup. We can't just assume it's solution/Backup, because VS will create // a new directory if that already exists. So just iterate up until we find the correct directory. solutionDirectory = solutionDirectory.TrimEnd(Path.DirectorySeparatorChar); var rootBackupDirectory = backupLocation; var levelUpBackupDirectory = Path.GetDirectoryName(rootBackupDirectory).TrimEnd(Path.DirectorySeparatorChar); while (!StringComparers.Paths.Equals(levelUpBackupDirectory, solutionDirectory)) { rootBackupDirectory = levelUpBackupDirectory; levelUpBackupDirectory = Path.GetDirectoryName(levelUpBackupDirectory).TrimEnd(Path.DirectorySeparatorChar); } // rootBackupDirectory is now the actual root backup directory. Back up the global.json and delete the existing one var globalJsonBackupPath = Path.Combine(rootBackupDirectory, "global.json"); pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, globalJson, string.Format(VSResources.MigrationBackupFile, globalJson, globalJsonBackupPath)); _fileSystem.CopyFile(globalJson, globalJsonBackupPath, true); try { _fileSystem.RemoveFile(globalJson); var remover = new GlobalJsonRemover(_serviceProvider); HResult hr = solution.AdviseSolutionEvents(remover, out uint cookie); if (hr.Succeeded) { remover.SolutionCookie = cookie; } } catch (IOException e) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, globalJson, e.Message); return(e.HResult); } } return(VSConstants.S_OK); }
public ProjectUpgradeLogger(IVsUpgradeLogger logger, string projectName, string projectFileName) { if (logger != null) { write = (errLevel, message) => logger.LogMessage((uint)errLevel, projectName, projectFileName, message); } else { write = delegate { }; } }
internal string GetCsproj(string projectDirectory, string projectName, string xprojLocation, IVsUpgradeLogger pLogger) { // TODO: We need to find the newly created csproj. This will only be necessary until dotnet migrate adds a Migration Report. // https://github.com/dotnet/roslyn-project-system/issues/507 var files = _fileSystem.EnumerateFiles(projectDirectory, "*", SearchOption.TopDirectoryOnly); var csproj = files.FirstOrDefault(file => file.EndsWith(".csproj")) ?? ""; if (string.IsNullOrEmpty(csproj)) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, xprojLocation, string.Format(VSResources.NoMigratedCSProjFound, projectDirectory)); } return(csproj); }
private static void BackupProjectForUpgrade(string sourceProjectFilePath, IVsUpgradeLogger pLogger, ref string destProjectFilePath, string backupedProject, string projectName) { var dlg = new PromptProjectRenameForm(projectName); Form parent = null; foreach (Form item in Application.OpenForms) { if (item.GetType().Name == "UpgradeWizard_Dialog") { parent = item; break; } } var result = dlg.ShowDialog(parent); if (result == DialogResult.Yes) { destProjectFilePath = Path.Combine(Path.GetDirectoryName(sourceProjectFilePath), dlg.ProjectName + Path.GetExtension(sourceProjectFilePath)); if (Utils.Eq(sourceProjectFilePath, destProjectFilePath)) { throw new ApplicationException("Can't rename project to itself name."); } File.Copy(sourceProjectFilePath, destProjectFilePath); //File successfully backed up as pLogger.LogMessage(0, projectName, sourceProjectFilePath, "The project file has been renamed to '" + Path.GetFileName(destProjectFilePath) + "' ('" + destProjectFilePath + "'). The old project file remain unchanged."); } else if (!string.IsNullOrEmpty(backupedProject)) { File.Copy(sourceProjectFilePath, backupedProject); pLogger.LogMessage(0, projectName, sourceProjectFilePath, "File successfully backed up as " + backupedProject); } }
internal static void SqlDatabaseFileUpgradeService_OnUpgradeProject( IVsHierarchy hierarchy, string databaseFile, string newConnectionString, IVsUpgradeLogger logger) { if (PackageManager.Package != null && PackageManager.Package.ModelManager != null) { var project = VSHelpers.GetProject(hierarchy); // skip the step if it is a miscellaneous project or if the project is using IIS // (projects using IIS should not be upgraded - see bug 812074) if (project != null && !VsUtils.IsMiscellaneousProject(project) && !IsUsingIIS(project)) { // update the config file as needed IDictionary <string, object> documentMap = new Dictionary <string, object>(); var configFilePath = ConnectionManager.GetConfigFilePath(project, false); try { if (false == string.IsNullOrWhiteSpace(configFilePath)) // check config file exists { XmlDocument configXmlDoc; if (ConnectionManager.UpdateSqlDatabaseFileDataSourceInConnectionStrings(configFilePath, out configXmlDoc)) { documentMap.Add(configFilePath, configXmlDoc); } } } catch (Exception ex) { // if there were errors above then do not try to change the files on disk - just log the message and return var errMsg = String.Format( CultureInfo.CurrentCulture, Resources.ErrorDuringSqlDatabaseFileUpgrade, configFilePath, ex.Message); logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFilePath, errMsg); return; } // Actually update the file here if (documentMap.Count > 0) { VsUtils.WriteCheckoutXmlFilesInProject(documentMap); } } } }
int IVsSolutionEventsProjectUpgrade.OnAfterUpgradeProject(IVsHierarchy pHierarchy, uint fUpgradeFlag, string bstrCopyLocation, SYSTEMTIME stUpgradeTime, IVsUpgradeLogger pLogger) { Debug.Assert(pHierarchy != null); Project upgradedProject = VsUtility.GetProjectFromHierarchy(pHierarchy); if (upgradedProject != null) { IList<IPackage> packagesToBeReinstalled = ProjectRetargetingUtility.GetPackagesToBeReinstalled(upgradedProject); if (!packagesToBeReinstalled.IsEmpty()) { pLogger.LogMessage((int)__VSUL_ERRORLEVEL.VSUL_ERROR, upgradedProject.Name, upgradedProject.Name, String.Format(CultureInfo.CurrentCulture, Resources.ProjectUpgradeAndRetargetErrorMessage, String.Join(", ", packagesToBeReinstalled.Select(p => p.Id)))); } } return VSConstants.S_OK; }
int IVsSolutionEventsProjectUpgrade.OnAfterUpgradeProject(IVsHierarchy pHierarchy, uint fUpgradeFlag, string bstrCopyLocation, SYSTEMTIME stUpgradeTime, IVsUpgradeLogger pLogger) { Debug.Assert(pHierarchy != null); Project upgradedProject = VsUtility.GetProjectFromHierarchy(pHierarchy); if (upgradedProject != null) { IList <IPackage> packagesToBeReinstalled = ProjectRetargetingUtility.GetPackagesToBeReinstalled(upgradedProject); if (!packagesToBeReinstalled.IsEmpty()) { pLogger.LogMessage((int)__VSUL_ERRORLEVEL.VSUL_ERROR, upgradedProject.Name, upgradedProject.Name, String.Format(CultureInfo.CurrentCulture, Resources.ProjectUpgradeAndRetargetErrorMessage, String.Join(", ", packagesToBeReinstalled.Select(p => p.Id)))); } } return(VSConstants.S_OK); }
internal static void UpdateConfigForSqlDbFileUpgrade(ConfigFileUtils configFileUtils, Project project, IVsUpgradeLogger logger) { try { var configXmlDoc = configFileUtils.LoadConfig(); if (configXmlDoc != null) // check config file exists { if (ConnectionManager.UpdateSqlDatabaseFileDataSourceInConnectionStrings(configXmlDoc)) { configFileUtils.SaveConfig(configXmlDoc); } } } catch (Exception ex) { // if there were errors above then do not try to change the files on disk - just log the message and return var errMsg = String.Format( CultureInfo.CurrentCulture, Resources.ErrorDuringSqlDatabaseFileUpgrade, configFileUtils.GetConfigPath(), ex.Message); logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFileUtils.GetConfigPath(), errMsg); } }
public void UpgradeProject_CheckOnly( string fileName, IVsUpgradeLogger?logger, out uint upgradeRequired, out Guid migratedProjectFactory, out uint upgradeProjectCapabilityFlags) { // Xproj is deprecated. It cannot be upgraded, and cannot be loaded. upgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_DEPRECATED; migratedProjectFactory = GetType().GUID; upgradeProjectCapabilityFlags = 0; // Log a message explaining that the project cannot be automatically upgraded // and how to perform the upgrade manually. This message will be presented in // the upgrade report. logger?.LogMessage( (uint)__VSUL_ERRORLEVEL.VSUL_ERROR, Path.GetFileNameWithoutExtension(fileName), fileName, VSResources.XprojNotSupported); }
private static void BackupProjectForUpgrade(string sourceProjectFilePath, IVsUpgradeLogger pLogger, ref string destProjectFilePath, string backupedProject, string projectName) { var dlg = new PromptProjectRenameForm(projectName); Form parent = null; foreach (Form item in Application.OpenForms) if (item.GetType().Name == "UpgradeWizard_Dialog") { parent = item; break; } var result = dlg.ShowDialog(parent); if (result == DialogResult.Yes) { destProjectFilePath = Path.Combine(Path.GetDirectoryName(sourceProjectFilePath), dlg.ProjectName + Path.GetExtension(sourceProjectFilePath)); if (Utils.Eq(sourceProjectFilePath, destProjectFilePath)) throw new ApplicationException("Can't rename project to itself name."); File.Copy(sourceProjectFilePath, destProjectFilePath); //File successfully backed up as pLogger.LogMessage(0, projectName, sourceProjectFilePath, "The project file has been renamed to '" + Path.GetFileName(destProjectFilePath) + "' ('" + destProjectFilePath + "'). The old project file remain unchanged."); } else if (!string.IsNullOrEmpty(backupedProject)) { File.Copy(sourceProjectFilePath, backupedProject); pLogger.LogMessage(0, projectName, sourceProjectFilePath, "File successfully backed up as " + backupedProject); } }
public ProjectUpgradeLogger(IVsUpgradeLogger logger, string projectName, string projectFileName) { if (logger != null) { write = (errLevel, message) => logger.LogMessage((uint)errLevel, projectName, projectFileName, message) ; } else { write = delegate { }; } }
public virtual int UpgradeProject(string projectFileName, uint upgradeFlag, string copyLocation, out string upgradeFullyQualifiedFileName, IVsUpgradeLogger logger, out int upgradeRequired, out Guid newProjectFactory) { uint ignore; this.UpgradeProject_CheckOnly(projectFileName, logger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { upgradeFullyQualifiedFileName = projectFileName; return(VSConstants.S_OK); } string projectName = Path.GetFileNameWithoutExtension(projectFileName); upgradeFullyQualifiedFileName = projectFileName; // Query for edit IVsQueryEditQuerySave2 queryEdit = site.GetService(typeof(SVsQueryEditQuerySave)) as IVsQueryEditQuerySave2; if (queryEdit != null) { uint editVerdict; uint queryEditMoreInfo; const tagVSQueryEditFlags tagVSQueryEditFlags_QEF_AllowUnopenedProjects = (tagVSQueryEditFlags)0x80; int hr = queryEdit.QueryEditFiles( (uint)(tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting | tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | tagVSQueryEditFlags_QEF_AllowUnopenedProjects), 1, new[] { projectFileName }, null, null, out editVerdict, out queryEditMoreInfo); if (ErrorHandler.Failed(hr)) { return(VSConstants.E_FAIL); } if (editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, projectFileName, SR.GetString(SR.UpgradeCannotOpenProjectFileForEdit)); } return(VSConstants.E_FAIL); } // If file was modified during the checkout, maybe upgrade is not needed if ((queryEditMoreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { this.UpgradeProject_CheckOnly(projectFileName, logger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, projectFileName, SR.GetString(SR.UpgradeNoNeedToUpgradeAfterCheckout)); } return(VSConstants.S_OK); } } } // Convert the project Microsoft.Build.Conversion.ProjectFileConverter projectConverter = new Microsoft.Build.Conversion.ProjectFileConverter(); projectConverter.OldProjectFile = projectFileName; projectConverter.NewProjectFile = projectFileName; ProjectRootElement convertedProject = null; try { convertedProject = projectConverter.ConvertInMemory(); } catch (Exception ex) { if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, projectFileName, ex.Message); } } if (convertedProject != null) { this.m_lastUpgradedProjectFile = projectFileName; foreach (ProjectPropertyElement property in convertedProject.Properties) { switch (property.Name) { case SCC_LOCAL_PATH: this.m_sccLocalPath = property.Value; break; case SCC_AUX_PATH: this.m_sccAuxPath = property.Value; break; case SCC_PROVIDER: this.m_sccProvider = property.Value; break; case SCC_PROJECT_NAME: this.m_sccProjectName = property.Value; break; default: break; } } try { convertedProject.Save(projectFileName); } catch (Exception ex) { if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, projectFileName, ex.Message); } return(VSConstants.E_FAIL); } if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_STATUSMSG, projectName, projectFileName, SR.GetString(SR.UpgradeSuccessful)); } return(VSConstants.S_OK); } this.m_lastUpgradedProjectFile = null; upgradeFullyQualifiedFileName = ""; return(VSConstants.E_FAIL); }
public override int UpgradeProject(string fileName, uint upgradeFlag, string copyLocation, out string upgradedFullyQualifiedFileName, IVsUpgradeLogger logger, out int upgradeRequired, out Guid newProjectFactory) { uint ignore; string projectName = Path.GetFileNameWithoutExtension(fileName); upgradedFullyQualifiedFileName = fileName; this.UpgradeProject_CheckOnly(fileName, logger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { upgradedFullyQualifiedFileName = fileName; return(VSConstants.S_OK); } IVsQueryEditQuerySave2 queryEditQuerySave = WixHelperMethods.GetService <IVsQueryEditQuerySave2, SVsQueryEditQuerySave>(this.Site); int qef = (int)tagVSQueryEditFlags.QEF_ReportOnly | (int)__VSQueryEditFlags2.QEF_AllowUnopenedProjects; uint verdict; uint moreInfo; string[] files = new string[1]; files[0] = fileName; bool continueUpgrade = false; ErrorHandler.ThrowOnFailure(queryEditQuerySave.QueryEditFiles((uint)qef, 1, files, null, null, out verdict, out moreInfo)); if (verdict == (uint)tagVSQueryEditResult.QER_EditOK) { continueUpgrade = true; } if (verdict == (uint)tagVSQueryEditResult.QER_EditNotOK) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, fileName, WixStrings.ReadOnlyFile); if ((moreInfo & (uint)tagVSQueryEditResultFlags.QER_ReadOnlyUnderScc) != 0) { qef = (int)tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | (int)__VSQueryEditFlags2.QEF_AllowUnopenedProjects | (int)tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting; ErrorHandler.ThrowOnFailure(queryEditQuerySave.QueryEditFiles((uint)qef, 1, files, null, null, out verdict, out moreInfo)); if (verdict == (uint)tagVSQueryEditResult.QER_EditOK) { continueUpgrade = true; } } if (continueUpgrade) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, fileName, WixStrings.CheckoutSuccess); } else { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, fileName, WixStrings.FailedToCheckoutProject); throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, WixStrings.FailedToCheckoutFile, fileName)); } } // If file was modified during the checkout, maybe upgrade is not needed if ((moreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { this.UpgradeProject_CheckOnly(fileName, logger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, fileName, WixStrings.UpgradeNoNeedToUpgradeAfterCheckout); } return(VSConstants.S_OK); } } if (continueUpgrade) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fileName); xmlDoc.DocumentElement.SetAttribute(WixProjectFileConstants.ToolsVersion, "4.0"); bool targetsPathUpdated = false; foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { if (WixProjectFileConstants.PropertyGroup == node.Name) { foreach (XmlNode propertyNode in node.ChildNodes) { if (WixProjectFileConstants.WixTargetsPath == propertyNode.Name) { if (propertyNode.InnerText.Contains("\\Microsoft\\WiX\\v3.0\\")) { targetsPathUpdated = true; propertyNode.InnerText = propertyNode.InnerText.Replace("\\Microsoft\\WiX\\v3.0\\", "\\Microsoft\\WiX\\v3.x\\"); } else if (propertyNode.InnerText.Contains("\\Microsoft\\WiX\\v3.5\\")) { targetsPathUpdated = true; propertyNode.InnerText = propertyNode.InnerText.Replace("\\Microsoft\\WiX\\v3.5\\", "\\Microsoft\\WiX\\v3.x\\"); } if (propertyNode.InnerText.Contains("\\Wix2010.targets")) { targetsPathUpdated = true; propertyNode.InnerText = propertyNode.InnerText.Replace("\\Wix2010.targets", "\\Wix.targets"); } } } } } if (targetsPathUpdated) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, fileName, WixStrings.WixTargetsPathUpdated); } xmlDoc.Save(fileName); upgradedFullyQualifiedFileName = fileName; } return(VSConstants.S_OK); }
internal static void UpdateConfigForSqlDbFileUpgrade(ConfigFileUtils configFileUtils, Project project, IVsUpgradeLogger logger) { try { var configXmlDoc = configFileUtils.LoadConfig(); if (configXmlDoc != null) // check config file exists { if (ConnectionManager.UpdateSqlDatabaseFileDataSourceInConnectionStrings(configXmlDoc)) { configFileUtils.SaveConfig(configXmlDoc); } } } catch (Exception ex) { // if there were errors above then do not try to change the files on disk - just log the message and return var errMsg = String.Format( CultureInfo.CurrentCulture, Resources.ErrorDuringSqlDatabaseFileUpgrade, configFileUtils.GetConfigPath(), ex.Message); logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFileUtils.GetConfigPath(), errMsg); } }
internal static void SqlCeUpgradeService_OnUpgradeProject(IVsHierarchy hierarchy, IVsUpgradeLogger logger) { if (PackageManager.Package != null && PackageManager.Package.ModelManager != null) { // since this is about retargeting EDMX files on disk, no need to process other file extensions from any converters var fileFinder = new VSFileFinder(EntityDesignArtifact.ExtensionEdmx); fileFinder.FindInProject(hierarchy); var project = VSHelpers.GetProject(hierarchy); // skip the step if it is a miscellaneous project. if (project != null && !VsUtils.IsMiscellaneousProject(project)) { IDictionary<string, object> documentMap = new Dictionary<string, object>(); foreach (var vsFileInfo in fileFinder.MatchingFiles) { try { var projectItem = VsUtils.GetProjectItem(hierarchy, vsFileInfo.ItemId); // Dev 10 bug 648969: skip the process for astoria edmx file. if (EdmUtils.IsDataServicesEdmx(projectItem.get_FileNames(1))) { continue; } // Check whether project item is a linked item var isLinkItem = VsUtils.IsLinkProjectItem(projectItem); if (!isLinkItem) { var doc = MetadataConverterDriver.SqlCeInstance.Convert(SafeLoadXmlFromPath(vsFileInfo.Path)); if (doc != null) { documentMap.Add(vsFileInfo.Path, doc); } } } catch (Exception ex) { var errMsg = String.Format( CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, vsFileInfo.Path, ex.Message); logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, vsFileInfo.Path, errMsg); return; } } if (documentMap.Count > 0) { VsUtils.WriteCheckoutXmlFilesInProject(documentMap); } // now update the config file as needed var configFileUtils = new ConfigFileUtils(project, PackageManager.Package); try { var configXmlDoc = configFileUtils.LoadConfig(); if (configXmlDoc != null) // check config file exists { if (ConnectionManager.UpdateSqlCeProviderInConnectionStrings(configXmlDoc)) { configFileUtils.SaveConfig(configXmlDoc); } } } catch (Exception ex) { var errMsg = String.Format( CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, configFileUtils.GetConfigPath(), ex.Message); logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFileUtils.GetConfigPath(), errMsg); } } } }
/// <inheritdoc /> public int UpgradeProject(string bstrFileName, uint fUpgradeFlag, string bstrCopyLocation, out string pbstrUpgradedFullyQualifiedFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory) { uint verdict, moreInfo, ignored; string[] files = new string[1] { bstrFileName }; string projectName = Path.GetFileNameWithoutExtension(bstrFileName); bool continueUpgrade = false; pbstrUpgradedFullyQualifiedFileName = bstrFileName; // Be sure we need an upgrade this.UpgradeProject_CheckOnly(bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out ignored); if (pUpgradeRequired == 0) { return(VSConstants.S_OK); } // See if the file is editable IVsQueryEditQuerySave2 qes = Utility.GetServiceFromPackage <IVsQueryEditQuerySave2, SVsQueryEditQuerySave>(true); ErrorHandler.ThrowOnFailure(qes.QueryEditFiles((uint)tagVSQueryEditFlags.QEF_ReportOnly | (uint)__VSQueryEditFlags2.QEF_AllowUnopenedProjects, 1, files, null, null, out verdict, out moreInfo)); if (verdict == (uint)tagVSQueryEditResult.QER_EditOK) { continueUpgrade = true; } if (verdict == (uint)tagVSQueryEditResult.QER_EditNotOK) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, bstrFileName, "The project file is read-only. An attempt will be made to check it out if under source control."); if ((moreInfo & (uint)tagVSQueryEditResultFlags.QER_ReadOnlyUnderScc) != 0) { ErrorHandler.ThrowOnFailure(qes.QueryEditFiles( (uint)tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | (uint)__VSQueryEditFlags2.QEF_AllowUnopenedProjects | (uint)tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting, 1, files, null, null, out verdict, out moreInfo)); if (verdict == (uint)tagVSQueryEditResult.QER_EditOK) { continueUpgrade = true; } } if (continueUpgrade) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, bstrFileName, "The project file was successfully checked out."); } else { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, bstrFileName, "Unable to check project out of source control. Upgrade failed."); throw new InvalidOperationException("Unable to check out project file for upgrade: " + bstrFileName); } } // If file was modified during the checkout, confirm that it still needs upgrading if ((moreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { this.UpgradeProject_CheckOnly(bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out ignored); if (pUpgradeRequired == 0) { if (pLogger != null) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, bstrFileName, "The project file was checked out and is already up to date. No upgrade needed."); } return(VSConstants.S_OK); } } if (continueUpgrade) { // Make a backup? if (fUpgradeFlag == PUVFF_SXSBACKUP) { File.Copy(bstrFileName, bstrFileName + ".backup", true); } // The SancastleProject class contains all the code needed to update the project so all we need // to do is load a copy and force it to save a new copy. using (SandcastleProject p = new SandcastleProject(bstrFileName, true)) { p.UpgradeProjectProperties(); p.SaveProject(bstrFileName); } pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, bstrFileName, "The project file was upgraded successfully."); } return(VSConstants.S_OK); }
internal static void SqlCeUpgradeService_OnUpgradeProject(IVsHierarchy hierarchy, IVsUpgradeLogger logger) { if (PackageManager.Package != null && PackageManager.Package.ModelManager != null) { // since this is about retargeting EDMX files on disk, no need to process other file extensions from any converters var fileFinder = new VSFileFinder(EntityDesignArtifact.ExtensionEdmx); fileFinder.FindInProject(hierarchy); var project = VSHelpers.GetProject(hierarchy); // skip the step if it is a miscellaneous project. if (project != null && !VsUtils.IsMiscellaneousProject(project)) { IDictionary <string, object> documentMap = new Dictionary <string, object>(); foreach (var vsFileInfo in fileFinder.MatchingFiles) { try { var projectItem = VsUtils.GetProjectItem(hierarchy, vsFileInfo.ItemId); // Dev 10 bug 648969: skip the process for astoria edmx file. if (EdmUtils.IsDataServicesEdmx(projectItem.get_FileNames(1))) { continue; } // Check whether project item is a linked item var isLinkItem = VsUtils.IsLinkProjectItem(projectItem); if (!isLinkItem) { var doc = MetadataConverterDriver.SqlCeInstance.Convert(SafeLoadXmlFromPath(vsFileInfo.Path)); if (doc != null) { documentMap.Add(vsFileInfo.Path, doc); } } } catch (Exception ex) { var errMsg = String.Format( CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, vsFileInfo.Path, ex.Message); logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, vsFileInfo.Path, errMsg); return; } } if (documentMap.Count > 0) { VsUtils.WriteCheckoutXmlFilesInProject(documentMap); } // now update the config file as needed var configFileUtils = new ConfigFileUtils(project, PackageManager.Package); try { var configXmlDoc = configFileUtils.LoadConfig(); if (configXmlDoc != null) // check config file exists { if (ConnectionManager.UpdateSqlCeProviderInConnectionStrings(configXmlDoc)) { configFileUtils.SaveConfig(configXmlDoc); } } } catch (Exception ex) { var errMsg = String.Format( CultureInfo.CurrentCulture, Resources.ErrorDuringSqlCeUpgrade, configFileUtils.GetConfigPath(), ex.Message); logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, project.Name, configFileUtils.GetConfigPath(), errMsg); } } } }
/// <inheritdoc /> public int UpgradeProject(string bstrFileName, uint fUpgradeFlag, string bstrCopyLocation, out string pbstrUpgradedFullyQualifiedFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory) { uint verdict, moreInfo, ignored; string[] files = new string[1] { bstrFileName }; string projectName = Path.GetFileNameWithoutExtension(bstrFileName); bool continueUpgrade = false; pbstrUpgradedFullyQualifiedFileName = bstrFileName; // Be sure we need an upgrade this.UpgradeProject_CheckOnly(bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out ignored); if(pUpgradeRequired == 0) return VSConstants.S_OK; // See if the file is editable IVsQueryEditQuerySave2 qes = Utility.GetServiceFromPackage<IVsQueryEditQuerySave2, SVsQueryEditQuerySave>(true); ErrorHandler.ThrowOnFailure(qes.QueryEditFiles((uint)tagVSQueryEditFlags.QEF_ReportOnly | (uint)__VSQueryEditFlags2.QEF_AllowUnopenedProjects, 1, files, null, null, out verdict, out moreInfo)); if(verdict == (uint)tagVSQueryEditResult.QER_EditOK) continueUpgrade = true; if(verdict == (uint)tagVSQueryEditResult.QER_EditNotOK) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, bstrFileName, "The project file is read-only. An attempt will be made to check it out if under source control."); if((moreInfo & (uint)tagVSQueryEditResultFlags.QER_ReadOnlyUnderScc) != 0) { ErrorHandler.ThrowOnFailure(qes.QueryEditFiles( (uint)tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | (uint)__VSQueryEditFlags2.QEF_AllowUnopenedProjects | (uint)tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting, 1, files, null, null, out verdict, out moreInfo)); if(verdict == (uint)tagVSQueryEditResult.QER_EditOK) continueUpgrade = true; } if(continueUpgrade) pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, bstrFileName, "The project file was successfully checked out."); else { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, bstrFileName, "Unable to check project out of source control. Upgrade failed."); throw new InvalidOperationException("Unable to check out project file for upgrade: " + bstrFileName); } } // If file was modified during the checkout, confirm that it still needs upgrading if((moreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { this.UpgradeProject_CheckOnly(bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out ignored); if(pUpgradeRequired == 0) { if(pLogger != null) pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, bstrFileName, "The project file was checked out and is already up to date. No upgrade needed."); return VSConstants.S_OK; } } if(continueUpgrade) { // Make a backup? if(fUpgradeFlag == PUVFF_SXSBACKUP) File.Copy(bstrFileName, bstrFileName + ".backup", true); // The SancastleProject class contains all the code needed to update the project so all we need // to do is load a copy and force it to save a new copy. using(SandcastleProject p = new SandcastleProject(bstrFileName, true, false)) { p.SaveProject(bstrFileName); } pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, bstrFileName, "The project file was upgraded successfully."); } return VSConstants.S_OK; }
public int UpgradeProject(string fileName, uint upgradeFlag, string copyLocation, out string upgradedFullyQualifiedFileName, IVsUpgradeLogger logger, out int upgradeRequired, out Guid newProjectFactory) { uint ignore; string projectName = Path.GetFileNameWithoutExtension(fileName); upgradedFullyQualifiedFileName = fileName; this.UpgradeProject_CheckOnly(fileName, logger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { upgradedFullyQualifiedFileName = fileName; return VSConstants.S_OK; } IVsQueryEditQuerySave2 queryEditQuerySave = WixHelperMethods.GetService<IVsQueryEditQuerySave2, SVsQueryEditQuerySave>(this.Site); int qef = (int)tagVSQueryEditFlags.QEF_ReportOnly | (int)__VSQueryEditFlags2.QEF_AllowUnopenedProjects; uint verdict; uint moreInfo; string[] files = new string[1]; files[0] = fileName; bool continueUpgrade = false; ErrorHandler.ThrowOnFailure(queryEditQuerySave.QueryEditFiles((uint)qef, 1, files, null, null, out verdict, out moreInfo)); if (verdict == (uint)tagVSQueryEditResult.QER_EditOK) { continueUpgrade = true; } if (verdict == (uint)tagVSQueryEditResult.QER_EditNotOK) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, fileName, WixStrings.ReadOnlyFile); if ((moreInfo & (uint)tagVSQueryEditResultFlags.QER_ReadOnlyUnderScc) != 0) { qef = (int)tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | (int)__VSQueryEditFlags2.QEF_AllowUnopenedProjects | (int)tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting; ErrorHandler.ThrowOnFailure(queryEditQuerySave.QueryEditFiles((uint)qef, 1, files, null, null, out verdict, out moreInfo)); if (verdict == (uint)tagVSQueryEditResult.QER_EditOK) { continueUpgrade = true; } } if (continueUpgrade) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, fileName, WixStrings.CheckoutSuccess); } else { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, fileName, WixStrings.FailedToCheckoutProject); throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, WixStrings.FailedToCheckoutFile, fileName)); } } // If file was modified during the checkout, maybe upgrade is not needed if ((moreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { this.UpgradeProject_CheckOnly(fileName, logger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, fileName, WixStrings.UpgradeNoNeedToUpgradeAfterCheckout); } return VSConstants.S_OK; } } if (continueUpgrade) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fileName); bool targetsPathUpdated = false; foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { if (WixProjectFileConstants.PropertyGroup == node.Name) { foreach (XmlNode propertyNode in node.ChildNodes) { if (WixProjectFileConstants.WixTargetsPath == propertyNode.Name) { if (propertyNode.InnerText.Contains("\\Microsoft\\WiX\\v3.0\\")) { targetsPathUpdated = true; propertyNode.InnerText = propertyNode.InnerText.Replace("\\Microsoft\\WiX\\v3.0\\", "\\Microsoft\\WiX\\v3.x\\"); } else if (propertyNode.InnerText.Contains("\\Microsoft\\WiX\\v3.5\\")) { targetsPathUpdated = true; propertyNode.InnerText = propertyNode.InnerText.Replace("\\Microsoft\\WiX\\v3.5\\", "\\Microsoft\\WiX\\v3.x\\"); } } } } } if (targetsPathUpdated) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, fileName, WixStrings.WixTargetsPathUpdated); } xmlDoc.Save(fileName); upgradedFullyQualifiedFileName = fileName; } return VSConstants.S_OK; }
public int UpgradeProject(string bstrFileName, uint fUpgradeFlag, string bstrCopyLocation, out string pbstrUpgradedFullyQualifiedFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory) { ThreadHelper.ThrowIfNotOnUIThread(); var projectDir = new DirectoryInfo(Path.GetDirectoryName(bstrFileName)); var projectName = Path.GetFileNameWithoutExtension(bstrFileName); string codeProjectPath; UpgradeProject_CheckOnly(bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out var flags); using (var projectStream = File.OpenRead(bstrFileName)) { var document = XDocument.Load(projectStream); var itemGroups = document.Root.Descendants().Where(e => XNameEqualsString(e.Name, ItemGroup)); var projectReferences = itemGroups.Descendants().Where(e => XNameEqualsString(e.Name, ProjectReference)); if (!projectReferences.Any()) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, bstrFileName, "Invalid project!"); pbstrUpgradedFullyQualifiedFileName = bstrFileName; return(VSConstants.VS_E_PROJECTMIGRATIONFAILED); } else if (projectReferences.Count() == 1) { var codeProject = projectReferences.Single().Attributes().Where( a => XNameEqualsString(a.Name, Include)).Single().Value; codeProjectPath = Path.IsPathRooted(codeProject) ? codeProject : Path.GetFullPath(Path.Combine(projectDir.FullName, codeProject)); } else { var projectReferencesWithoutPlugsProjects = projectReferences.Where( p => !PlugsProjects.Contains( Path.GetFileNameWithoutExtension( p.Attributes().Where( a => XNameEqualsString(a.Name, Include)).Single().Value), StringComparer.OrdinalIgnoreCase)); if (projectReferencesWithoutPlugsProjects.Count() > 1) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_WARNING, projectName, bstrFileName, "Selecting project reference based on Cosmos project name!"); var codeProjectName = projectName.EndsWith("Boot") ? projectName.TrimSuffix("Boot") : projectName; var codeProjectPathWithoutExtension = Path.Combine(projectDir.FullName, codeProjectName); var possibleCodeProjects = projectReferences.Where( p => StringEquals( Path.GetFileNameWithoutExtension( p.Attributes().Where( a => XNameEqualsString(a.Name, Include)).Single().Value), codeProjectName)); if (possibleCodeProjects.Count() != 1) { pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, bstrFileName, "Cannot find the code project!"); pbstrUpgradedFullyQualifiedFileName = bstrFileName; return(VSConstants.VS_E_PROJECTMIGRATIONFAILED); } var codeProject = possibleCodeProjects.Single().Attributes().Where(a => XNameEqualsString(a.Name, Include)).Single().Value; codeProjectPath = Path.IsPathRooted(codeProject) ? codeProject : Path.GetFullPath(Path.Combine(projectDir.FullName, codeProject)); } else { var codeProject = projectReferencesWithoutPlugsProjects .Single().Attributes().Where(a => XNameEqualsString(a.Name, Include)).Single().Value; codeProjectPath = Path.IsPathRooted(codeProject) ? codeProject : Path.GetFullPath(Path.Combine(projectDir.FullName, codeProject)); } } } File.Copy(bstrFileName, Path.Combine(bstrCopyLocation, Path.GetFileName(bstrFileName))); File.Copy(codeProjectPath, Path.Combine(bstrCopyLocation, Path.GetFileName(codeProjectPath))); MigrateProject(bstrFileName, codeProjectPath); pbstrUpgradedFullyQualifiedFileName = null; return(VSConstants.S_OK); }
public virtual int UpgradeProject(string projectFileName, uint upgradeFlag, string copyLocation, out string upgradeFullyQualifiedFileName, IVsUpgradeLogger logger, out int upgradeRequired, out Guid newProjectFactory) { uint ignore; this.UpgradeProject_CheckOnly(projectFileName, logger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { upgradeFullyQualifiedFileName = projectFileName; return VSConstants.S_OK; } string projectName = Path.GetFileNameWithoutExtension(projectFileName); upgradeFullyQualifiedFileName = projectFileName; // Query for edit IVsQueryEditQuerySave2 queryEdit = site.GetService(typeof(SVsQueryEditQuerySave)) as IVsQueryEditQuerySave2; if (queryEdit != null) { uint editVerdict; uint queryEditMoreInfo; const tagVSQueryEditFlags tagVSQueryEditFlags_QEF_AllowUnopenedProjects = (tagVSQueryEditFlags)0x80; int hr = queryEdit.QueryEditFiles( (uint)(tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting | tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | tagVSQueryEditFlags_QEF_AllowUnopenedProjects), 1, new[] { projectFileName }, null, null, out editVerdict, out queryEditMoreInfo); if (ErrorHandler.Failed(hr)) { return VSConstants.E_FAIL; } if (editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, projectFileName, SR.GetString(SR.UpgradeCannotOpenProjectFileForEdit)); } return VSConstants.E_FAIL; } // If file was modified during the checkout, maybe upgrade is not needed if ((queryEditMoreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { this.UpgradeProject_CheckOnly(projectFileName, logger, out upgradeRequired, out newProjectFactory, out ignore); if (upgradeRequired == 0) { if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, projectName, projectFileName, SR.GetString(SR.UpgradeNoNeedToUpgradeAfterCheckout)); } return VSConstants.S_OK; } } } // Convert the project Microsoft.Build.Conversion.ProjectFileConverter projectConverter = new Microsoft.Build.Conversion.ProjectFileConverter(); projectConverter.OldProjectFile = projectFileName; projectConverter.NewProjectFile = projectFileName; ProjectRootElement convertedProject = null; try { convertedProject = projectConverter.ConvertInMemory(); } catch (Exception ex) { if (logger != null) logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, projectFileName, ex.Message); } if (convertedProject != null) { this.m_lastUpgradedProjectFile = projectFileName; foreach (ProjectPropertyElement property in convertedProject.Properties) { switch (property.Name) { case SCC_LOCAL_PATH: this.m_sccLocalPath = property.Value; break; case SCC_AUX_PATH: this.m_sccAuxPath = property.Value; break; case SCC_PROVIDER: this.m_sccProvider = property.Value; break; case SCC_PROJECT_NAME: this.m_sccProjectName = property.Value; break; default: break; } } try { convertedProject.Save(projectFileName); } catch (Exception ex) { if (logger != null) logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_ERROR, projectName, projectFileName, ex.Message); return VSConstants.E_FAIL; } if (logger != null) { logger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_STATUSMSG, projectName, projectFileName, SR.GetString(SR.UpgradeSuccessful)); } return VSConstants.S_OK; } this.m_lastUpgradedProjectFile = null; upgradeFullyQualifiedFileName = ""; return VSConstants.E_FAIL; }
private static void UpgradeProject(string sourceProjectFilePath, string destProjectFilePath, IVsUpgradeLogger pLogger, string projectName) { var projectData = new ProjectUpgradeHelper(sourceProjectFilePath); projectData.ToolsVersion.Value = Default.ToolsVersion; if (IsNeedUpdateNemerleBinPathRootProperty(projectData.NemerleBinPathRoot)) { projectData.NemerleBinPathRoot.Value = Default.NemerleBinPathRoot; projectData.NemerleBinPathRoot.SetAttributeValue("Condition", " '$(NemerleBinPathRoot)' == '' "); } else if (!Utils.Eq(projectData.NemerleBinPathRoot.Value, Default.NemerleBinPathRoot)) pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_WARNING, projectName, sourceProjectFilePath, "The NemerleBinPathRoot property changed by user. You must update it manually."); projectData.NemerleVersion.Value = Default.NemerleVersion; if (IsNeedUpdateNemerleProperty(projectData.NemerleProperty)) projectData.NemerleProperty.Value = Default.NemerleProperty; else if (!Utils.Eq(projectData.NemerleProperty.Value, Default.NemerleProperty)) pLogger.LogMessage((uint)__VSUL_ERRORLEVEL.VSUL_WARNING, projectName, sourceProjectFilePath, "The Nemerle property changed by user. You must update it manually."); projectData.TargetFrameworkVersion.Value = Default.TargetFrameworkVersion; projectData.NemerleProperty.Document.Save(destProjectFilePath); }