public void AddBindingRedirects() { var settings = ServiceLocator.GetInstanceSafe <Configuration.ISettings>(); var behavior = new BindingRedirectBehavior(settings); if (!behavior.IsSkipped) { NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { try { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); InitForBindingRedirects(); if (IsBindingRedirectSupported && VSSolutionManager != null) { await RuntimeHelpers.AddBindingRedirectsAsync(VSSolutionManager, VsProjectAdapter, VSFrameworkMultiTargeting, NuGetProjectContext); } } catch (Exception ex) { var fileName = VsProjectAdapter.UniqueName; var level = behavior.FailOperations ? ProjectManagement.MessageLevel.Error : ProjectManagement.MessageLevel.Warning; NuGetProjectContext.Log(level, Strings.FailedToUpdateBindingRedirects, fileName, ex.Message); if (behavior.FailOperations) { throw; } } }); } }
public void AddFrameworkReference(string name, string packageId) { ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); try { // Add a reference to the project AddGacReference(name); NuGetProjectContext.Log(ProjectManagement.MessageLevel.Debug, Strings.Debug_AddGacReference, name, ProjectName); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Strings.FailedToAddGacReference, packageId, name), e); } }); }
protected override async Task AddFileToProjectAsync(string path) { if (ExcludeFile(path)) { return; } await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Get the project items for the folder path string folderPath = Path.GetDirectoryName(path); string fullPath = FileSystemUtility.GetFullPath(ProjectFullPath, path); ; VCProjectHelper.AddFileToProject(EnvDTEProject.Object, fullPath, folderPath); NuGetProjectContext.Log(ProjectManagement.MessageLevel.Debug, Strings.Debug_AddedFileToProject, path, ProjectName); }
/// <summary> /// This method should be on the UI thread. The overrides should ensure that /// </summary> protected virtual async Task AddFileToProjectAsync(string path) { Debug.Assert(ThreadHelper.CheckAccess()); if (ExcludeFile(path)) { return; } // Get the project items for the folder path string folderPath = Path.GetDirectoryName(path); string fullPath = FileSystemUtility.GetFullPath(ProjectFullPath, path); var container = await EnvDTEProjectUtility.GetProjectItemsAsync(EnvDTEProject, folderPath, createIfNotExists : true); // Add the file to project or folder AddFileToContainer(fullPath, folderPath, container); NuGetProjectContext.Log(ProjectManagement.MessageLevel.Debug, Strings.Debug_AddedFileToProject, path, ProjectName); }
protected virtual void AddFileToProject(string path) { if (ExcludeFile(path)) { return; } // Get the project items for the folder path string folderPath = Path.GetDirectoryName(path); string fullPath = FileSystemUtility.GetFullPath(ProjectFullPath, path); ThreadHelper.Generic.Invoke(() => { EnvDTEProjectItems container = EnvDTEProjectUtility.GetProjectItems(EnvDTEProject, folderPath, createIfNotExists: true); // Add the file to project or folder AddFileToContainer(fullPath, folderPath, container); }); NuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_AddedFileToProject, path, ProjectName); }
public override void AddReference(string referencePath) { string name = Path.GetFileNameWithoutExtension(referencePath); try { var root = EnvDTEProjectUtility.GetFullPath(EnvDTEProject); EnvDTEProjectUtility.GetAssemblyReferences(EnvDTEProject).AddFromFile(PathUtility.GetAbsolutePath(root, referencePath)); // Always create a refresh file. Vs does this for us in most cases, however for GACed binaries, it resorts to adding a web.config entry instead. // This may result in deployment issues. To work around ths, we'll always attempt to add a file to the bin. RefreshFileUtility.CreateRefreshFile(root, PathUtility.GetAbsolutePath(EnvDTEProjectUtility.GetFullPath(EnvDTEProject), referencePath), this); NuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_AddReference, name, ProjectName); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Strings.FailedToAddReference, name), e); } }
public virtual void RemoveFile(string path) { NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var deleteProjectItem = await EnvDTEProjectUtility.DeleteProjectItemAsync(EnvDTEProject, path); if (deleteProjectItem) { string folderPath = Path.GetDirectoryName(path); if (!String.IsNullOrEmpty(folderPath)) { NuGetProjectContext.Log(ProjectManagement.MessageLevel.Debug, Strings.Debug_RemovedFileFromFolder, Path.GetFileName(path), folderPath); } else { NuGetProjectContext.Log(ProjectManagement.MessageLevel.Debug, Strings.Debug_RemovedFile, Path.GetFileName(path)); } } }); }
public virtual void AddExistingFile(string path) { var fullPath = Path.Combine(ProjectFullPath, path); if (!File.Exists(fullPath)) { throw new ArgumentNullException("PathToExistingFileNotPresent"); } // TODO var resolveFileConflict = NuGetProjectContext.ResolveFileConflict(""); if (resolveFileConflict == FileConflictAction.Overwrite || resolveFileConflict == FileConflictAction.OverwriteAll) { AddFileCore(path, null); } else { AddFileCore(path, null); } }
public override async Task AddReferenceAsync(string referencePath) { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); var name = Path.GetFileNameWithoutExtension(referencePath); try { EnvDTEProjectUtility.GetAssemblyReferences(VsProjectAdapter.Project).AddFromFile(PathUtility.GetAbsolutePath(ProjectFullPath, referencePath)); // Always create a refresh file. Vs does this for us in most cases, however for GACed binaries, it resorts to adding a web.config entry instead. // This may result in deployment issues. To work around ths, we'll always attempt to add a file to the bin. RefreshFileUtility.CreateRefreshFile(ProjectFullPath, PathUtility.GetAbsolutePath(ProjectFullPath, referencePath), this); NuGetProjectContext.Log(ProjectManagement.MessageLevel.Debug, $"Added reference '{name}' to project:'{ProjectName}' "); } catch (Exception e) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.FailedToAddReference, name), e); } }
private Task AddFileCoreAsync(string path, Action addFile) { // Do not try to add file to project, if the path is null or empty. if (string.IsNullOrEmpty(path)) { return(Task.FromResult(false)); } var fileExistsInProject = FileExistsInProject(path); // If the file exists on disk but not in the project then skip it. // One exception is the 'packages.config' file, in which case we want to include // it into the project. // Other exceptions are 'web.config' and 'app.config' var fileName = Path.GetFileName(path); var lockFileFullPath = PackagesConfigLockFileUtility.GetPackagesLockFilePath(ProjectFullPath, GetPropertyValue("NuGetLockFilePath")?.ToString(), ProjectName); if (File.Exists(Path.Combine(ProjectFullPath, path)) && !fileExistsInProject && !fileName.Equals(ProjectManagement.Constants.PackageReferenceFile) && !fileName.Equals("packages." + ProjectName + ".config") && !fileName.Equals(EnvDTEProjectInfoUtility.WebConfig) && !fileName.Equals(EnvDTEProjectInfoUtility.AppConfig) && !fileName.Equals(Path.GetFileName(lockFileFullPath)) ) { NuGetProjectContext.Log(ProjectManagement.MessageLevel.Warning, Strings.Warning_FileAlreadyExists, path); } else { EnvDTEProjectUtility.EnsureCheckedOutIfExists(VsProjectAdapter.Project, ProjectFullPath, path); addFile(); if (!fileExistsInProject) { return(AddFileToProjectAsync(path)); } } return(Task.FromResult(false)); }
public override void RemoveReference(string name) { // Remove the reference via DTE. RemoveDTEReference(name); // For GACed binaries, VS would not clear the refresh files for us since it assumes the reference exists in web.config. // We'll clean up any remaining .refresh files. var refreshFilePath = Path.Combine("bin", Path.GetFileName(name) + ".refresh"); var root = EnvDTEProjectUtility.GetFullPath(EnvDTEProject); var refreshFileFullPath = FileSystemUtility.GetFullPath(root, refreshFilePath); if (File.Exists(refreshFileFullPath)) { try { FileSystemUtility.DeleteFile(refreshFileFullPath, NuGetProjectContext); } catch (Exception e) { NuGetProjectContext.Log(MessageLevel.Warning, e.Message); } } }
public override async Task RemoveReferenceAsync(string name) { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Remove the reference via DTE. RemoveDTEReference(name); // For GACed binaries, VS would not clear the refresh files for us since it assumes the reference exists in web.config. // We'll clean up any remaining .refresh files. var refreshFilePath = Path.Combine("bin", Path.GetFileName(name) + ".refresh"); var refreshFileFullPath = FileSystemUtility.GetFullPath(ProjectFullPath, refreshFilePath); if (File.Exists(refreshFileFullPath)) { try { FileSystemUtility.DeleteFile(refreshFileFullPath, NuGetProjectContext); } catch (Exception e) { NuGetProjectContext.Log(ProjectManagement.MessageLevel.Warning, e.Message); } } }
public virtual void AddReference(string referencePath) { if (referencePath == null) { throw new ArgumentNullException(nameof(referencePath)); } var name = Path.GetFileNameWithoutExtension(referencePath); var projectName = string.Empty; var projectFullPath = string.Empty; var assemblyFullPath = string.Empty; var dteProjectFullName = string.Empty; var dteOriginalPath = string.Empty; var resolvedToPackage = false; try { // Perform all DTE operations on the UI thread NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Read DTE properties from the UI thread projectFullPath = ProjectFullPath; projectName = ProjectName; dteProjectFullName = EnvDTEProject.FullName; // Get the full path to the reference assemblyFullPath = Path.Combine(projectFullPath, referencePath); // Add a reference to the project var references = EnvDTEProjectUtility.GetReferences(EnvDTEProject); dynamic reference = references.Add(assemblyFullPath); if (reference != null) { dteOriginalPath = GetReferencePath(reference); // If path != fullPath, we need to set CopyLocal thru msbuild by setting Private // to true. // This happens if the assembly appears in any of the search paths that VS uses to // locate assembly references. // Most commonly, it happens if this assembly is in the GAC or in the output path. // The path may be null or for some project system it can be "". resolvedToPackage = !string.IsNullOrWhiteSpace(dteOriginalPath) && IsSamePath(dteOriginalPath, assemblyFullPath); if (resolvedToPackage) { // Set reference properties (if needed) TrySetCopyLocal(reference); TrySetSpecificVersion(reference); } } }); if (!resolvedToPackage) { // This should be done off the UI thread // Get the msbuild project for this project var buildProject = EnvDTEProjectUtility.AsMicrosoftBuildEvaluationProject(dteProjectFullName); if (buildProject != null) { // Get the assembly name of the reference we are trying to add var assemblyName = AssemblyName.GetAssemblyName(assemblyFullPath); // Try to find the item for the assembly name var item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences() where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2) select assemblyReferenceNode.Item1).FirstOrDefault(); if (item != null) { // Add the <HintPath> metadata item as a relative path var projectPath = PathUtility.EnsureTrailingSlash(projectFullPath); var relativePath = PathUtility.GetRelativePath(projectPath, referencePath); item.SetMetadataValue("HintPath", relativePath); // Set <Private> to true item.SetMetadataValue("Private", "True"); FileSystemUtility.MakeWritable(dteProjectFullName); // Change to the UI thread to save NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Save the project after we've modified it. EnvDTEProject.Save(); }); } } else { // The reference cannot be changed by modifying the project file. // This could be a failure, however that could be a breaking // change if there is a non-msbuild project system relying on this // to skip references. // Log a warning to let the user know that their reference may have failed. NuGetProjectContext.Log( ProjectManagement.MessageLevel.Warning, Strings.FailedToAddReference, name); } } } catch (Exception e) { throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Strings.FailedToAddReference, name), e); } NuGetProjectContext.Log( ProjectManagement.MessageLevel.Debug, $"Added reference '{name}' to project:'{projectName}'. Was the Reference Resolved To Package (resolvedToPackage):'{resolvedToPackage}', " + "where Reference Path from DTE(dteOriginalPath):'{dteOriginalPath}' and Reference Path from package reference(assemblyFullPath):'{assemblyFullPath}'."); }
public virtual async Task AddReferenceAsync(string referencePath) { if (referencePath == null) { throw new ArgumentNullException(nameof(referencePath)); } var name = Path.GetFileNameWithoutExtension(referencePath); var projectName = string.Empty; var projectFullPath = string.Empty; var assemblyFullPath = string.Empty; var dteProjectFullName = string.Empty; var dteOriginalPath = string.Empty; var resolvedToPackage = false; try { // Perform all DTE operations on the UI thread await NuGetUIThreadHelper.JoinableTaskFactory.RunAsync(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Read DTE properties from the UI thread projectFullPath = ProjectFullPath; projectName = ProjectName; dteProjectFullName = VsProjectAdapter.FullName; // Get the full path to the reference assemblyFullPath = Path.Combine(projectFullPath, referencePath); // Add a reference to the project dynamic reference; try { // First try the References3.AddFiles API, as that will incur fewer // design-time builds. References3.AddFiles(new[] { assemblyFullPath }, out var referencesArray); var references = (VSLangProj.Reference[])referencesArray; reference = references[0]; } catch (Exception e) { if (e is InvalidCastException) { // We've encountered a project system that doesn't implement References3, or // there's some sort of setup issue such that we can't find the library with // the References3 type. Send a report about this. TelemetryActivity.EmitTelemetryEvent(new TelemetryEvent("References3InvalidCastException")); } // If that didn't work, fall back to References.Add. reference = References.Add(assemblyFullPath); } if (reference != null) { dteOriginalPath = GetReferencePath(reference); // If path != fullPath, we need to set CopyLocal thru msbuild by setting Private // to true. // This happens if the assembly appears in any of the search paths that VS uses to // locate assembly references. // Most commonly, it happens if this assembly is in the GAC or in the output path. // The path may be null or for some project system it can be "". resolvedToPackage = !string.IsNullOrWhiteSpace(dteOriginalPath) && IsSamePath(dteOriginalPath, assemblyFullPath); if (resolvedToPackage) { // Set reference properties (if needed) TrySetCopyLocal(reference); TrySetSpecificVersion(reference); } } }); if (!resolvedToPackage) { // This should be done off the UI thread // Get the msbuild project for this project var buildProject = EnvDTEProjectUtility.AsMSBuildEvaluationProject(dteProjectFullName); if (buildProject != null) { // Get the assembly name of the reference we are trying to add var assemblyName = AssemblyName.GetAssemblyName(assemblyFullPath); // Try to find the item for the assembly name var item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences() where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2) select assemblyReferenceNode.Item1).FirstOrDefault(); if (item != null) { // Add the <HintPath> metadata item as a relative path var projectPath = PathUtility.EnsureTrailingSlash(projectFullPath); var relativePath = PathUtility.GetRelativePath(projectPath, referencePath); item.SetMetadataValue("HintPath", relativePath); // Set <Private> to true item.SetMetadataValue("Private", "True"); FileSystemUtility.MakeWritable(dteProjectFullName); // Change to the UI thread to save NuGetUIThreadHelper.JoinableTaskFactory.Run(async delegate { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); // Save the project after we've modified it. await SaveProjectAsync(); }); } } else { // The reference cannot be changed by modifying the project file. // This could be a failure, however that could be a breaking // change if there is a non-msbuild project system relying on this // to skip references. // Log a warning to let the user know that their reference may have failed. NuGetProjectContext.Log( ProjectManagement.MessageLevel.Warning, Strings.FailedToAddReference, name); } } }
public virtual void AddReference(string referencePath) { if (referencePath == null) { throw new ArgumentNullException("referencePath"); } string name = Path.GetFileNameWithoutExtension(referencePath); try { // Get the full path to the reference string fullPath = Path.Combine(ProjectFullPath, referencePath); string assemblyPath = fullPath; bool usedTempFile = false; // There is a bug in Visual Studio whereby if the fullPath contains a comma, // then calling Project.Object.References.Add() on it will throw a COM exception. // To work around it, we copy the assembly into temp folder and add reference to the copied assembly if (fullPath.Contains(",")) { string tempFile = Path.Combine(Path.GetTempPath(), Path.GetFileName(fullPath)); File.Copy(fullPath, tempFile, true); assemblyPath = tempFile; usedTempFile = true; } // Add a reference to the project dynamic reference = EnvDTEProjectUtility.GetReferences(EnvDTEProject).Add(assemblyPath); // if we copied the assembly to temp folder earlier, delete it now since we no longer need it. if (usedTempFile) { try { File.Delete(assemblyPath); } catch { // don't care if we fail to delete a temp file } } if (reference != null) { var path = GetReferencePath(reference); // If path != fullPath, we need to set CopyLocal thru msbuild by setting Private // to true. // This happens if the assembly appears in any of the search paths that VS uses to // locate assembly references. // Most commonly, it happens if this assembly is in the GAC or in the output path. if (path != null && !path.Equals(fullPath, StringComparison.OrdinalIgnoreCase)) { // Get the msbuild project for this project MicrosoftBuildEvaluationProject buildProject = EnvDTEProjectUtility.AsMicrosoftBuildEvaluationProject(EnvDTEProject); if (buildProject != null) { // Get the assembly name of the reference we are trying to add AssemblyName assemblyName = AssemblyName.GetAssemblyName(fullPath); // Try to find the item for the assembly name MicrosoftBuildEvaluationProjectItem item = (from assemblyReferenceNode in buildProject.GetAssemblyReferences() where AssemblyNamesMatch(assemblyName, assemblyReferenceNode.Item2) select assemblyReferenceNode.Item1).FirstOrDefault(); if (item != null) { // Add the <HintPath> metadata item as a relative path item.SetMetadataValue("HintPath", referencePath); // Set <Private> to true item.SetMetadataValue("Private", "True"); // Save the project after we've modified it. FileSystemUtility.MakeWriteable(EnvDTEProject.FullName); EnvDTEProject.Save(); } } } else { TrySetCopyLocal(reference); TrySetSpecificVersion(reference); } } NuGetProjectContext.Log(MessageLevel.Debug, Strings.Debug_AddReference, name, ProjectName); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Strings.FailedToAddReference, name), e); } }