private async Task BeforeQueryStatusAsync(object sender, EventArgs e) { var button = (OleMenuCommand)sender; button.Visible = button.Enabled = false; if (VsHelpers.DTE.SelectedItems.MultiSelect) { return; } ProjectItem item = await VsHelpers.GetSelectedItemAsync(); if (item != null && item.IsConfigFile()) { button.Visible = true; button.Enabled = KnownUIContexts.SolutionExistsAndNotBuildingAndNotDebuggingContext.IsActive; _isPackageInstalled = IsPackageInstalled(item.ContainingProject); if (_isPackageInstalled) { button.Text = Resources.Text.DisableRestoreOnBuild; } else { button.Text = Resources.Text.EnableRestoreOnBuild; } } }
private async Task ExecuteAsync(object sender, EventArgs e) { Telemetry.TrackUserTask("Execute-ManageLibrariesCommand"); Project project = await VsHelpers.GetProjectOfSelectedItemAsync(); if (project != null) { string rootFolder = await project.GetRootFolderAsync(); string configFilePath = Path.Combine(rootFolder, Constants.ConfigFileName); if (File.Exists(configFilePath)) { await VsHelpers.OpenFileAsync(configFilePath); } else { var dependencies = _dependenciesFactory.FromConfigFile(configFilePath); Manifest manifest = await Manifest.FromFileAsync(configFilePath, dependencies, CancellationToken.None); manifest.DefaultProvider = "cdnjs"; manifest.Version = Manifest.SupportedVersions.Max().ToString(); await manifest.SaveAsync(configFilePath, CancellationToken.None); await project.AddFileToProjectAsync(configFilePath); Telemetry.TrackUserTask("Create-ConfigFile"); } await VsHelpers.OpenFileAsync(configFilePath); } }
public void DeleteFiles(params string[] relativeFilePaths) { foreach (string relativeFilePath in relativeFilePaths) { string absoluteFile = new FileInfo(Path.Combine(WorkingDirectory, relativeFilePath)).FullName; try { ProjectItem item = VsHelpers.DTE.Solution.FindProjectItem(absoluteFile); Project project = item?.ContainingProject; if (project != null) { item.Delete(); } else { VsHelpers.CheckFileOutOfSourceControl(absoluteFile); File.Delete(absoluteFile); } Logger.Log(string.Format(LibraryManager.Resources.Text.FileDeleted, relativeFilePath), LogLevel.Operation); } catch (Exception) { Logger.Log(string.Format(LibraryManager.Resources.Text.FileDeleteFail, relativeFilePath), LogLevel.Operation); } } }
private async Task CleanLibrariesAsync(ProjectItem configProjectItem, CancellationToken cancellationToken) { Logger.LogEventsHeader(OperationType.Clean, string.Empty); try { Stopwatch sw = new Stopwatch(); sw.Start(); string configFileName = configProjectItem.FileNames[1]; var dependencies = Dependencies.FromConfigFile(configFileName); Project project = VsHelpers.GetDTEProjectFromConfig(configFileName); Manifest manifest = await Manifest.FromFileAsync(configFileName, dependencies, CancellationToken.None).ConfigureAwait(false); IEnumerable <ILibraryOperationResult> results = new List <ILibraryOperationResult>(); if (manifest != null) { IHostInteraction hostInteraction = dependencies.GetHostInteractions(); results = await manifest.CleanAsync(async (filesPaths) => await hostInteraction.DeleteFilesAsync(filesPaths, cancellationToken), cancellationToken); } sw.Stop(); AddErrorsToErrorList(project?.Name, configFileName, results); Logger.LogEventsSummary(results, OperationType.Clean, sw.Elapsed); } catch (OperationCanceledException) { Logger.LogEvent(LibraryManager.Resources.Text.Clean_OperationCancelled, LogLevel.Task); } }
public async Task <bool> DeleteFilesAsync(IEnumerable <string> relativeFilePaths, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); List <string> absolutePaths = new List <string>(); foreach (string filePath in relativeFilePaths) { string absoluteFilePath = Path.Combine(WorkingDirectory, filePath); FileInfo file = new FileInfo(absoluteFilePath); if (file.Exists) { absolutePaths.Add(absoluteFilePath); } } //Delete from project Project project = VsHelpers.GetDTEProjectFromConfig(_configFilePath); bool isCoreProject = await VsHelpers.IsDotNetCoreWebProjectAsync(project); if (!isCoreProject) { var logAction = new Action <string, LogLevel>((message, level) => { Logger.Log(message, level); }); bool deleteFromProject = await VsHelpers.DeleteFilesFromProjectAsync(project, absolutePaths, logAction, cancellationToken); if (deleteFromProject) { return(true); } } // Delete from file system return(await DeleteFilesFromDisk(absolutePaths, cancellationToken)); }
private async Task AddFilesToProjectAsync(string configFilePath, Project project, IEnumerable <ILibraryOperationResult> results, CancellationToken cancellationToken) { string workingDirectory = Path.GetDirectoryName(configFilePath); var files = new List <string>(); if (project != null) { foreach (ILibraryOperationResult state in results) { if (state.Success && !state.UpToDate && state.InstallationState.Files != null) { IEnumerable <string> absoluteFiles = state.InstallationState.Files .Select(file => Path.Combine(workingDirectory, state.InstallationState.DestinationPath, file) .Replace('/', Path.DirectorySeparatorChar)); files.AddRange(absoluteFiles); } } if (files.Count > 0) { var logAction = new Action <string, LogLevel>((message, level) => { Logger.LogEvent(message, level); }); await VsHelpers.AddFilesToProjectAsync(project, files, logAction, cancellationToken); } } }
public async Task <bool> WriteFileAsync(string relativePath, Func <Stream> content, ILibraryInstallationState state, CancellationToken cancellationToken) { FileInfo absolutePath = new FileInfo(Path.Combine(WorkingDirectory, relativePath)); if (absolutePath.Exists) { return(true); } if (!absolutePath.FullName.StartsWith(WorkingDirectory)) { throw new UnauthorizedAccessException(); } absolutePath.Directory.Create(); using (Stream stream = content.Invoke()) { if (stream == null) { return(false); } await VsHelpers.CheckFileOutOfSourceControlAsync(absolutePath.FullName); await FileHelpers.SafeWriteToFileAsync(absolutePath.FullName, stream, cancellationToken); } Logger.Log(string.Format(LibraryManager.Resources.Text.FileWrittenToDisk, relativePath.Replace(Path.DirectorySeparatorChar, '/')), LogLevel.Operation); return(true); }
private void BeforeQueryStatus(object sender, EventArgs e) { var button = (OleMenuCommand)sender; button.Visible = button.Enabled = false; if (VsHelpers.DTE.SelectedItems.MultiSelect) { return; } ProjectItem item = VsHelpers.DTE.SelectedItems.Item(1).ProjectItem; if (item.IsConfigFile() && (item.ContainingProject.IsKind(Constants.WAP) || VsHelpers.IsCapabilityMatch(item.ContainingProject, Constants.DotNetCoreWebCapability))) { button.Visible = true; button.Enabled = KnownUIContexts.SolutionExistsAndNotBuildingAndNotDebuggingContext.IsActive; _isPackageInstalled = IsPackageInstalled(item.ContainingProject); if (_isPackageInstalled) { button.Text = Resources.Text.DisableRestoreOnBuild; } else { button.Text = Resources.Text.EnableRestoreOnBuild; } } }
private async Task ExecuteAsync(object sender, EventArgs e) { Telemetry.TrackUserTask("installdialogopened"); ProjectItem item = await VsHelpers.GetSelectedItemAsync().ConfigureAwait(false); if (item != null) { string target = item.FileNames[1]; Project project = await VsHelpers.GetProjectOfSelectedItemAsync().ConfigureAwait(false); if (project != null) { string rootFolder = await project.GetRootFolderAsync().ConfigureAwait(false); string configFilePath = Path.Combine(rootFolder, Constants.ConfigFileName); IDependencies dependencies = Dependencies.FromConfigFile(configFilePath); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); UI.InstallDialog dialog = new UI.InstallDialog(dependencies, _libraryCommandService, configFilePath, target, rootFolder); var dte = (DTE)Package.GetGlobalService(typeof(SDTE)); int hwnd = dte.MainWindow.HWnd; WindowInteropHelper windowInteropHelper = new WindowInteropHelper(dialog); // Set visual studio window's handle as the owner of the dialog. // This will remove the dialog from alt-tab list and will not allow the user to switch the dialog box to the background windowInteropHelper.Owner = new IntPtr(hwnd); dialog.ShowDialog(); } } }
private async Task ExecuteAsync(object sender, EventArgs e) { ProjectItem configProjectItem = await VsHelpers.GetSelectedItemAsync(); if (configProjectItem != null) { await _libraryCommandService.RestoreAsync(configProjectItem.FileNames[1], CancellationToken.None); } }
private async Task ExecuteAsync() { ProjectItem configProjectItem = await VsHelpers.GetSelectedItemAsync(); if (configProjectItem != null) { await _libraryCommandService.CleanAsync(configProjectItem, CancellationToken.None); } }
private async Task ExecuteAsync(object sender, EventArgs e) { Telemetry.TrackUserTask("Execute-InstallLibraryCommand"); ProjectItem item = await VsHelpers.GetSelectedItemAsync().ConfigureAwait(false); Project project = await VsHelpers.GetProjectOfSelectedItemAsync().ConfigureAwait(false); if (project != null) { string target = string.Empty; string rootFolder = await project.GetRootFolderAsync().ConfigureAwait(false); // Install command was invoked from a folder. // So the initial target location should be name of the folder from which // the command was invoked. if (item != null) { target = item.FileNames[1]; } else { // Install command was invoked from project scope. // If wwwroot exists, initial target location should be - wwwroot/lib. // Else, target location should be - lib if (Directory.Exists(Path.Combine(rootFolder, "wwwroot"))) { target = Path.Combine(rootFolder, "wwwroot", "lib") + Path.DirectorySeparatorChar; } else { target = Path.Combine(rootFolder, "lib") + Path.DirectorySeparatorChar; } } string configFilePath = Path.Combine(rootFolder, Constants.ConfigFileName); IDependencies dependencies = Dependencies.FromConfigFile(configFilePath); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); UI.InstallDialog dialog = new UI.InstallDialog(dependencies, _libraryCommandService, configFilePath, target, rootFolder); var dte = (DTE)Package.GetGlobalService(typeof(SDTE)); int hwnd = dte.MainWindow.HWnd; WindowInteropHelper windowInteropHelper = new WindowInteropHelper(dialog); // Set visual studio window's handle as the owner of the dialog. // This will remove the dialog from alt-tab list and will not allow the user to switch the dialog box to the background windowInteropHelper.Owner = new IntPtr(hwnd); dialog.ShowDialog(); Telemetry.TrackUserTask("Open-InstallDialog"); } }
private RestoreOnBuildCommand(Package package, OleMenuCommandService commandService) { _package = package; _componentModel = VsHelpers.GetService <SComponentModel, IComponentModel>(); var cmdId = new CommandID(PackageGuids.guidLibraryManagerPackageCmdSet, PackageIds.RestoreOnBuild); var cmd = new OleMenuCommand(ExecuteHandlerAsync, cmdId); cmd.BeforeQueryStatus += BeforeQueryStatusHandlerAsync; commandService.AddCommand(cmd); }
private RestoreOnBuildCommand(AsyncPackage package, OleMenuCommandService commandService, IDependenciesFactory dependenciesFactory) { _package = package; _componentModel = VsHelpers.GetService <SComponentModel, IComponentModel>(); _dependenciesFactory = dependenciesFactory; var cmdId = new CommandID(PackageGuids.guidLibraryManagerPackageCmdSet, PackageIds.RestoreOnBuild); var cmd = new OleMenuCommand((s, e) => _package.JoinableTaskFactory.RunAsync(() => ExecuteAsync(s, e)), cmdId); cmd.BeforeQueryStatus += (s, e) => _package.JoinableTaskFactory.RunAsync(() => BeforeQueryStatusAsync(s, e)); commandService.AddCommand(cmd); }
private async Task RestoreInternalAsync(IDictionary <string, Manifest> manifests, CancellationToken cancellationToken) { Logger.LogEventsHeader(OperationType.Restore, string.Empty); try { Stopwatch swTotal = new Stopwatch(); swTotal.Start(); foreach (KeyValuePair <string, Manifest> manifest in manifests) { cancellationToken.ThrowIfCancellationRequested(); Stopwatch swLocal = new Stopwatch(); swLocal.Start(); IDependencies dependencies = Dependencies.FromConfigFile(manifest.Key); Project project = VsHelpers.GetDTEProjectFromConfig(manifest.Key); Logger.LogEvent(string.Format(LibraryManager.Resources.Text.Restore_LibrariesForProject, project?.Name), LogLevel.Operation); IEnumerable <ILibraryOperationResult> validationResults = await LibrariesValidator.GetManifestErrorsAsync(manifest.Value, dependencies, cancellationToken).ConfigureAwait(false); if (!validationResults.All(r => r.Success)) { swLocal.Stop(); AddErrorsToErrorList(project?.Name, manifest.Key, validationResults); Logger.LogErrorsSummary(validationResults, OperationType.Restore, false); Telemetry.LogErrors($"FailValidation_{OperationType.Restore}", validationResults); } else { IEnumerable <ILibraryOperationResult> results = await RestoreLibrariesAsync(manifest.Value, cancellationToken).ConfigureAwait(false); await AddFilesToProjectAsync(manifest.Key, project, results.Where(r => r.Success && !r.UpToDate), cancellationToken).ConfigureAwait(false); swLocal.Stop(); AddErrorsToErrorList(project?.Name, manifest.Key, results); Logger.LogEventsSummary(results, OperationType.Restore, swLocal.Elapsed, false); Telemetry.LogEventsSummary(results, OperationType.Restore, swLocal.Elapsed); } } swTotal.Stop(); Logger.LogEventsFooter(OperationType.Restore, swTotal.Elapsed); } catch (OperationCanceledException ex) { Logger.LogEvent(LibraryManager.Resources.Text.Restore_OperationCancelled, LogLevel.Task); Telemetry.TrackException($@"{OperationType.Restore}Cancelled", ex); } }
private async Task BeforeQueryStatusAsync(object sender, EventArgs e) { var button = (OleMenuCommand)sender; button.Visible = button.Enabled = false; ProjectItem item = await VsHelpers.GetSelectedItemAsync(); if (item != null && item.Name.Equals(Constants.ConfigFileName, StringComparison.OrdinalIgnoreCase)) { button.Visible = true; button.Enabled = KnownUIContexts.SolutionExistsAndNotBuildingAndNotDebuggingContext.IsActive && !_libraryCommandService.IsOperationInProgress; } }
private async Task CleanLibrariesAsync(ProjectItem configProjectItem, CancellationToken cancellationToken) { Logger.LogEventsHeader(OperationType.Clean, string.Empty); try { Stopwatch sw = new Stopwatch(); sw.Start(); string configFileName = configProjectItem.FileNames[1]; var dependencies = _dependenciesFactory.FromConfigFile(configFileName); Project project = VsHelpers.GetDTEProjectFromConfig(configFileName); Manifest manifest = await Manifest.FromFileAsync(configFileName, dependencies, CancellationToken.None).ConfigureAwait(false); IEnumerable <ILibraryOperationResult> results = new List <ILibraryOperationResult>(); if (manifest != null) { IEnumerable <ILibraryOperationResult> validationResults = await LibrariesValidator.GetManifestErrorsAsync(manifest, dependencies, cancellationToken).ConfigureAwait(false); if (!validationResults.All(r => r.Success)) { sw.Stop(); AddErrorsToErrorList(project?.Name, configFileName, validationResults); Logger.LogErrorsSummary(validationResults, OperationType.Clean); Telemetry.LogErrors($"FailValidation_{OperationType.Clean}", validationResults); } else { IHostInteraction hostInteraction = dependencies.GetHostInteractions(); results = await manifest.CleanAsync(async (filesPaths) => await hostInteraction.DeleteFilesAsync(filesPaths, cancellationToken), cancellationToken); sw.Stop(); AddErrorsToErrorList(project?.Name, configFileName, results); Logger.LogEventsSummary(results, OperationType.Clean, sw.Elapsed); Telemetry.LogEventsSummary(results, OperationType.Clean, sw.Elapsed); } } } catch (OperationCanceledException ex) { Logger.LogEvent(LibraryManager.Resources.Text.Clean_OperationCancelled, LogLevel.Task); Telemetry.TrackException($@"{OperationType.Clean}Cancelled", ex); } }
private async Task BeforeQueryStatusAsync(object sender, EventArgs e) { OleMenuCommand button = (OleMenuCommand)sender; button.Visible = button.Enabled = false; ProjectItem item = await VsHelpers.GetSelectedItemAsync(); if (item?.ContainingProject == null) { return; } if (VSConstants.ItemTypeGuid.PhysicalFolder_string.Equals(item.Kind, StringComparison.OrdinalIgnoreCase)) { button.Visible = true; button.Enabled = KnownUIContexts.SolutionExistsAndNotBuildingAndNotDebuggingContext.IsActive && !_libraryCommandService.IsOperationInProgress; } }
private void BeforeQueryStatus(object sender, EventArgs e) { var button = (OleMenuCommand)sender; button.Visible = button.Enabled = false; if (VsHelpers.DTE.SelectedItems.MultiSelect) { return; } var solution = (IVsSolution)ServiceProvider.GetService(typeof(SVsSolution)); if (VsHelpers.SolutionContainsManifestFile(solution)) { button.Visible = true; button.Enabled = KnownUIContexts.SolutionExistsAndNotBuildingAndNotDebuggingContext.IsActive; } }
private async Task BeforeQueryStatusAsync(object sender, EventArgs e) { var button = (OleMenuCommand)sender; button.Visible = button.Enabled = false; if (VsHelpers.DTE.SelectedItems.MultiSelect) { return; } var solution = (IVsSolution)ServiceProvider.GetService(typeof(SVsSolution)); if (await VsHelpers.SolutionContainsManifestFileAsync(solution)) { button.Visible = true; button.Enabled = KnownUIContexts.SolutionExistsAndNotBuildingAndNotDebuggingContext.IsActive && !_libraryCommandService.IsOperationInProgress; } }
private async void ExecuteAsync(object sender, EventArgs e) { var solution = (IVsSolution)ServiceProvider.GetService(typeof(SVsSolution)); IEnumerable <IVsHierarchy> hierarchies = VsHelpers.GetProjectsInSolution(solution, __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION); var configFiles = new List <string>(); foreach (IVsHierarchy hierarchy in hierarchies) { Project project = VsHelpers.GetDTEProject(hierarchy); if (VsHelpers.ProjectContainsManifestFile(project)) { string configFilePath = Path.Combine(project.GetRootFolder(), Constants.ConfigFileName); configFiles.Add(configFilePath); } } await LibraryHelpers.RestoreAsync(configFiles); Telemetry.TrackUserTask("restoresolution"); }
private async Task BeforeQueryStatusAsync(object sender, EventArgs e) { OleMenuCommand button = (OleMenuCommand)sender; button.Visible = button.Enabled = false; // When command is invooked from a folder ProjectItem item = await VsHelpers.GetSelectedItemAsync().ConfigureAwait(false); // When command is invoked from project scope Project project = await VsHelpers.GetProjectOfSelectedItemAsync().ConfigureAwait(false); // We won't enable the command if it was not invoked from a project or a folder if (item?.ContainingProject == null && project == null) { return; } button.Visible = true; button.Enabled = KnownUIContexts.SolutionExistsAndNotBuildingAndNotDebuggingContext.IsActive && !_libraryCommandService.IsOperationInProgress; }
public async Task <bool> WriteFileAsync(string path, Func <Stream> content, ILibraryInstallationState state, CancellationToken cancellationToken) { var absolutePath = new FileInfo(Path.Combine(WorkingDirectory, path)); if (absolutePath.Exists) { return(true); } if (!absolutePath.FullName.StartsWith(WorkingDirectory)) { throw new UnauthorizedAccessException(); } absolutePath.Directory.Create(); using (Stream stream = content.Invoke()) { if (stream == null) { return(false); } VsHelpers.CheckFileOutOfSourceControl(absolutePath.FullName); using (FileStream writer = File.Create(absolutePath.FullName, 4096, FileOptions.Asynchronous)) { if (stream.CanSeek) { stream.Seek(0, SeekOrigin.Begin); } await stream.CopyToAsync(writer, 8192, cancellationToken).ConfigureAwait(false); } } Logger.Log(string.Format(LibraryManager.Resources.Text.FileWrittenToDisk, path.Replace(Path.DirectorySeparatorChar, '/')), LogLevel.Operation); return(true); }
/// <inheritdoc /> public async Task <bool> CopyFileAsync(string sourcePath, string destinationPath, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); string absoluteDestinationPath = Path.Combine(WorkingDirectory, destinationPath); if (!FileHelpers.IsUnderRootDirectory(absoluteDestinationPath, WorkingDirectory)) { throw new UnauthorizedAccessException(); } await VsHelpers.CheckFileOutOfSourceControlAsync(absoluteDestinationPath); bool result = await FileHelpers.CopyFileAsync(sourcePath, absoluteDestinationPath, cancellationToken); if (result) { Logger.Log(string.Format(LibraryManager.Resources.Text.FileWrittenToDisk, destinationPath.Replace(Path.DirectorySeparatorChar, '/')), LogLevel.Operation); } return(result); }
private async Task RestoreInternalAsync(IDictionary <string, Manifest> manifests, CancellationToken cancellationToken) { Logger.LogEventsHeader(OperationType.Restore, string.Empty); List <ILibraryOperationResult> totalResults = new List <ILibraryOperationResult>(); try { Stopwatch sw = new Stopwatch(); sw.Start(); foreach (KeyValuePair <string, Manifest> manifest in manifests) { cancellationToken.ThrowIfCancellationRequested(); Project project = VsHelpers.GetDTEProjectFromConfig(manifest.Key); Logger.LogEvent(string.Format(LibraryManager.Resources.Text.Restore_LibrariesForProject, project?.Name), LogLevel.Operation); IEnumerable <ILibraryOperationResult> results = await RestoreLibrariesAsync(manifest.Value, cancellationToken).ConfigureAwait(false); await AddFilesToProjectAsync(manifest.Key, project, results.Where(r => r.Success && !r.UpToDate), cancellationToken).ConfigureAwait(false); AddErrorsToErrorList(project?.Name, manifest.Key, results); totalResults.AddRange(results); } sw.Stop(); Logger.LogEventsSummary(totalResults, OperationType.Restore, sw.Elapsed); Telemetry.LogEventsSummary(totalResults, OperationType.Restore, sw.Elapsed); } catch (OperationCanceledException ex) { Logger.LogEvent(LibraryManager.Resources.Text.Restore_OperationCancelled, LogLevel.Task); Telemetry.TrackException($@"{OperationType.Restore}Cancelled", ex); } }
private async Task ExecuteAsync(object sender, EventArgs e) { Telemetry.TrackUserTask("Execute-RestoreSolutionCommand"); var solution = (IVsSolution)ServiceProvider.GetService(typeof(SVsSolution)); IEnumerable <IVsHierarchy> hierarchies = VsHelpers.GetProjectsInSolution(solution, __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION); var configFiles = new List <string>(); foreach (IVsHierarchy hierarchy in hierarchies) { Project project = VsHelpers.GetDTEProject(hierarchy); if (await VsHelpers.ProjectContainsManifestFileAsync(project)) { string rootPath = await project.GetRootFolderAsync(); string configFilePath = Path.Combine(rootPath, Constants.ConfigFileName); configFiles.Add(configFilePath); } } await _libraryCommandService.RestoreAsync(configFiles, CancellationToken.None); }
private async Task ExecuteAsync(object sender, EventArgs e) { ProjectItem projectItem = await VsHelpers.GetSelectedItemAsync(); Project project = await VsHelpers.GetProjectOfSelectedItemAsync(); try { var dependencies = _dependenciesFactory.FromConfigFile(projectItem.FileNames[1]); IEnumerable <string> packageIds = dependencies.Providers .Where(p => p.NuGetPackageId != null) .Select(p => p.NuGetPackageId) .Distinct(); if (!_isPackageInstalled) { if (!UserWantsToInstall()) { return; } await Task.Run(() => { Logger.LogEvent(Resources.Text.Nuget_InstallingPackage, LogLevel.Status); try { foreach (string packageId in packageIds) { IVsPackageInstaller2 installer = _componentModel.GetService <IVsPackageInstaller2>(); installer.InstallLatestPackage(null, project, packageId, true, false); } Telemetry.TrackUserTask("Install-NugetPackage"); Logger.LogEvent(Resources.Text.Nuget_PackageInstalled, LogLevel.Status); } catch (Exception ex) { Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex); Logger.LogEvent(Resources.Text.Nuget_PackageFailedToInstall, LogLevel.Status); } }); } else { await Task.Run(() => { Logger.LogEvent(Resources.Text.Nuget_UninstallingPackage, LogLevel.Status); try { foreach (string packageId in packageIds) { IVsPackageUninstaller uninstaller = _componentModel.GetService <IVsPackageUninstaller>(); uninstaller.UninstallPackage(project, packageId, false); } Telemetry.TrackUserTask("Uninstall-NugetPackage"); Logger.LogEvent(Resources.Text.Nuget_PackageUninstalled, LogLevel.Status); } catch (Exception ex) { Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex); Logger.LogEvent(Resources.Text.Nuget_PackageFailedToUninstall, LogLevel.Status); } }); } } catch (Exception ex) { Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex); Logger.LogEvent(Resources.Text.Nuget_PackageFailedToInstall, LogLevel.Status); } }
private async Task ExecuteAsync(object sender, EventArgs e) { Telemetry.TrackUserTask("Execute-InstallLibraryCommand"); ProjectItem item = await VsHelpers.GetSelectedItemAsync().ConfigureAwait(false); Project project = await VsHelpers.GetProjectOfSelectedItemAsync().ConfigureAwait(false); if (project != null) { string rootFolder = await project.GetRootFolderAsync().ConfigureAwait(false); string configFilePath = Path.Combine(rootFolder, Constants.ConfigFileName); IDependencies dependencies = _dependenciesFactory.FromConfigFile(configFilePath); Manifest manifest = await GetManifestAsync(configFilePath, dependencies).ConfigureAwait(false); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // If the manifest contains errors, we will not invoke the "Add Client-Side libraries" dialog // Instead we will display a message box indicating the syntax errors in manifest file. if (manifest == null) { IVsUIShell shell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell; int result; shell.ShowMessageBox(dwCompRole: 0, rclsidComp: Guid.Empty, pszTitle: null, pszText: PredefinedErrors.ManifestMalformed().Message, pszHelpFile: null, dwHelpContextID: 0, msgbtn: OLEMSGBUTTON.OLEMSGBUTTON_OK, msgdefbtn: OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, msgicon: OLEMSGICON.OLEMSGICON_WARNING, fSysAlert: 0, pnResult: out result); return; } string target = string.Empty; // Install command was invoked from a folder. // So the initial target location should be name of the folder from which // the command was invoked. if (item != null) { target = item.FileNames[1]; } else { // Install command was invoked from project scope. // If wwwroot exists, initial target location should be - wwwroot/lib. // Else, target location should be - lib if (Directory.Exists(Path.Combine(rootFolder, "wwwroot"))) { target = Path.Combine(rootFolder, "wwwroot", "lib") + Path.DirectorySeparatorChar; } else { target = Path.Combine(rootFolder, "lib") + Path.DirectorySeparatorChar; } } string initialTargetLocation = CalculateSuggestedInstallPath(target, rootFolder); var selectedProviderBinding = new SelectedProviderBinding(); var libraryIdViewModel = new LibraryIdViewModel(new ProviderCatalogSearchService(() => selectedProviderBinding.SelectedProvider), string.Empty); var libraryNameBinding = new LibraryNameBinding(); var targetLocationViewModel = new TargetLocationViewModel(initialTargetLocation, libraryNameBinding, new LocationSearchService(dependencies.GetHostInteractions())); var dialogViewModel = new InstallDialogViewModel( _libraryCommandService, configFilePath, dependencies, libraryIdViewModel, targetLocationViewModel, selectedProviderBinding, libraryNameBinding, target, project); var dialog = new UI.InstallDialog(dialogViewModel); dialog.ShowModal(); Telemetry.TrackUserTask("Open-InstallDialog"); } }
private async Task ExecuteAsync(object sender, EventArgs e) { Telemetry.TrackUserTask("Execute-InstallLibraryCommand"); ProjectItem item = await VsHelpers.GetSelectedItemAsync().ConfigureAwait(false); Project project = await VsHelpers.GetProjectOfSelectedItemAsync().ConfigureAwait(false); if (project != null) { string rootFolder = await project.GetRootFolderAsync().ConfigureAwait(false); string configFilePath = Path.Combine(rootFolder, Constants.ConfigFileName); IDependencies dependencies = Dependencies.FromConfigFile(configFilePath); Manifest manifest = await GetManifestAsync(configFilePath, dependencies).ConfigureAwait(false); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // If the manifest contains errors, we will not invoke the "Add Client-Side libraries" dialog // Instead we will display a message box indicating the syntax errors in manifest file. if (manifest == null) { IVsUIShell shell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell; int result; shell.ShowMessageBox(dwCompRole: 0, rclsidComp: Guid.Empty, pszTitle: null, pszText: PredefinedErrors.ManifestMalformed().Message, pszHelpFile: null, dwHelpContextID: 0, msgbtn: OLEMSGBUTTON.OLEMSGBUTTON_OK, msgdefbtn: OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, msgicon: OLEMSGICON.OLEMSGICON_WARNING, fSysAlert: 0, pnResult: out result); return; } string target = string.Empty; // Install command was invoked from a folder. // So the initial target location should be name of the folder from which // the command was invoked. if (item != null) { target = item.FileNames[1]; } else { // Install command was invoked from project scope. // If wwwroot exists, initial target location should be - wwwroot/lib. // Else, target location should be - lib if (Directory.Exists(Path.Combine(rootFolder, "wwwroot"))) { target = Path.Combine(rootFolder, "wwwroot", "lib") + Path.DirectorySeparatorChar; } else { target = Path.Combine(rootFolder, "lib") + Path.DirectorySeparatorChar; } } UI.InstallDialog dialog = new UI.InstallDialog(dependencies, _libraryCommandService, configFilePath, target, rootFolder, project); var dte = (DTE)Package.GetGlobalService(typeof(SDTE)); int hwnd = dte.MainWindow.HWnd; WindowInteropHelper windowInteropHelper = new WindowInteropHelper(dialog); // Set visual studio window's handle as the owner of the dialog. // This will remove the dialog from alt-tab list and will not allow the user to switch the dialog box to the background windowInteropHelper.Owner = new IntPtr(hwnd); dialog.ShowDialog(); Telemetry.TrackUserTask("Open-InstallDialog"); } }