private static void StripCommentsFromJsonFile(string fileName) { string fileContent = File.ReadAllText(fileName); var loadSettings = new JsonLoadSettings { CommentHandling = CommentHandling.Ignore }; string filteredFileContent = JArray.Parse(fileContent, loadSettings).ToString(); if (fileContent != filteredFileContent) { ProjectHelpers.CheckFileOutOfSourceControl(fileName); File.WriteAllText(fileName, filteredFileContent, Encoding.UTF8); } }
internal static bool DownloadFileToProject(string downloadPath, string targetFileName, Action <string> installCallback) { var dte = CakePackage.Dte; try { var slnFilePath = new FileInfo(dte.Solution.FullName).FullName; var cakeScriptPath = dte.Solution.FindProjectItem(Constants.ScriptFileName)?.FileNames[1]; var targetPath = Path.Combine(new FileInfo(string.IsNullOrWhiteSpace(cakeScriptPath) ? slnFilePath : cakeScriptPath).Directory.FullName, targetFileName); bool confirm = true; if (File.Exists(targetPath)) { confirm = VsShellUtilities.PromptYesNo("File already exists. Overwrite?", $"Downloading {targetFileName}", OLEMSGICON.OLEMSGICON_QUERY, CakePackage.Shell); } if (!confirm) { return(true); } try { ProjectHelpers.CheckFileOutOfSourceControl(targetPath); } catch (Exception) { // ignored } using (var wc = new WebClient()) { wc.DownloadFile(downloadPath, targetPath); VsShellUtilities.LogMessage(Constants.PackageName, $"File downloaded from '{downloadPath}' to '{targetPath}'", __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); installCallback.Invoke(targetPath); } return(true); } catch { VsShellUtilities.LogError(Constants.PackageName, $"There was an error downloading the requested file: '{downloadPath}'"); return(false); } }
public bool SaveBindings(string configPath, string bindingsXml) { string bindingPath = ConfigurationParser.GetConfigFilePath(configPath, true) ?? configPath + ".bindings"; var config = new ConfigurationParser(bindingPath); try { ProjectHelpers.CheckFileOutOfSourceControl(bindingPath); if (bindingsXml == "<binding />" && File.Exists(bindingPath)) { config.RemoveBindings(); } else { config.SaveBinding(TaskBinding.FromXml(bindingsXml)); ProjectHelpers.AddNestedFile(configPath, bindingPath); } IVsPersistDocData persistDocData; if (!CakePackage.IsDocumentDirty(configPath, out persistDocData) && persistDocData != null) { int cancelled; string newName; persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out newName, out cancelled); } else if (persistDocData == null) { new FileInfo(configPath).LastWriteTime = DateTime.Now; } return(true); } catch (Exception ex) { Logger.Log(ex); return(false); } }
public bool SaveBindings(string configPath, string bindingsXml) { string bindingPath = configPath + ".bindings"; try { ProjectHelpers.CheckFileOutOfSourceControl(bindingPath); if (bindingsXml == "<binding />" && File.Exists(bindingPath)) { ProjectHelpers.DeleteFileFromProject(bindingPath); } else { File.WriteAllText(bindingPath, "///" + bindingsXml, Encoding.UTF8); ProjectHelpers.AddNestedFile(configPath, bindingPath); } IVsPersistDocData persistDocData; if (!CakePackage.IsDocumentDirty(configPath, out persistDocData) && persistDocData != null) { int cancelled; string newName; persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out newName, out cancelled); } else if (persistDocData == null) { new FileInfo(configPath).LastWriteTime = DateTime.Now; } return(true); } catch (Exception ex) { Logger.Log(ex); return(false); } }
/// <summary> /// /// </summary> private async Task FixBindingRedirectsAsync() { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); _isProcessing = true; var files = ProjectHelpers.GetSelectedItemPaths().Where(c => c.ToLower().EndsWith("web.config") || c.ToLower().EndsWith("app.config")); if (!files.Any()) { _dte.StatusBar.Text = "Please select a web.config or app.config file to fix."; _isProcessing = false; return; } //var projectFolder = ProjectHelpers.GetRootFolder(ProjectHelpers.GetActiveProject()); int count = files.Count(); //RWM: Don't mess with these. XNamespace defaultNs = ""; XNamespace assemblyBindingNs = "urn:schemas-microsoft-com:asm.v1"; var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; try { string text = count == 1 ? " file" : " files"; _dte.StatusBar.Progress(true, $"Fixing {count} config {text}...", AmountCompleted: 1, Total: count + 1); foreach (var file in files) { var assemblyBindings = new XElement(assemblyBindingNs + "assemblyBinding"); var newBindings = new SortedDictionary <string, XElement>(); //RWM: Start by backing up the files. File.Copy(file, file + ".bak", true); Logger.Log($"Backup created for {file}."); //RWM: Load the files. var config = XDocument.Load(file); var oldBindingRoot = config.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "assemblyBinding"); var oldCount = oldBindingRoot.Elements().Count(); foreach (var dependentAssembly in oldBindingRoot.Elements().ToList()) { var assemblyIdentity = dependentAssembly.Element(assemblyBindingNs + "assemblyIdentity"); var bindingRedirect = dependentAssembly.Element(assemblyBindingNs + "bindingRedirect"); if (newBindings.ContainsKey(assemblyIdentity.Attribute("name").Value)) { Logger.Log($"Reference already exists for {assemblyIdentity.Attribute("name").Value}. Checking version..."); //RWM: We've seen this assembly before. Check to see if we can update the version. var newBindingRedirect = newBindings[assemblyIdentity.Attribute("name").Value].Descendants(assemblyBindingNs + "bindingRedirect").FirstOrDefault(); if (newBindingRedirect == null) { Logger.Log($"The bindingRedirect tag for {assemblyIdentity.Attribute("name").Value} was not found. Skipping."); continue; } var oldVersion = Version.Parse(newBindingRedirect.Attribute("newVersion").Value); var newVersion = Version.Parse(bindingRedirect.Attribute("newVersion").Value); if (newVersion > oldVersion) { newBindingRedirect.ReplaceWith(bindingRedirect); Logger.Log($"Version was newer. Binding updated."); } else { Logger.Log($"Version was the same or older. No update needed. Skipping."); } } else { newBindings.Add(assemblyIdentity.Attribute("name").Value, dependentAssembly); } } //RWM: Add the SortedDictionary items to our new assemblyBinding element. foreach (var binding in newBindings) { assemblyBindings.Add(binding.Value); } //RWM: Fix up the web.config by adding the new assemblyBindings and removing the old one. oldBindingRoot.AddBeforeSelf(assemblyBindings); oldBindingRoot.Remove(); //RWM: Save the config file. ProjectHelpers.CheckFileOutOfSourceControl(file); config.Save(file); Logger.Log($"Update complete. Result: {oldCount} bindings before, {newBindings.Count} after."); } } catch (AggregateException agEx) { _dte.StatusBar.Progress(false); Logger.Log($"Update failed. Exceptions:"); foreach (var ex in agEx.InnerExceptions) { Logger.Log($"Message: {ex.Message}{Environment.NewLine}{ex.StackTrace}"); } _dte.StatusBar.Text = "Operation failed. Please see Output Window for details."; _isProcessing = false; } finally { _dte.StatusBar.Progress(false); _dte.StatusBar.Text = "Operation finished. Please see Output Window for details."; _isProcessing = false; } }
/// <summary> /// /// </summary> private void UpgradePackagesConfig() { _isProcessing = true; var files = ProjectHelpers.GetSelectedItems().Where(c => _fileNames.Contains(Path.GetFileName(c.GetFullPath()))); if (!files.Any()) { _dte.StatusBar.Text = "Please select a package.config file to nuke from orbit."; _isProcessing = false; return; } //var projectFolder = ProjectHelpers.GetRootFolder(ProjectHelpers.GetActiveProject()); int count = files.Count(); //RWM: Don't mess with these. XNamespace defaultNs = "http://schemas.microsoft.com/developer/msbuild/2003"; var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; try { string text = count == 1 ? " file" : " files"; _dte.StatusBar.Progress(true, $"Fixing {count} config {text}...", AmountCompleted: 1, Total: count + 1); Parallel.For(0, count, options, i => { var packageReferences = new XElement(defaultNs + "ItemGroup"); var packagesConfigItem = files.ElementAt(i); var packagesConfigPath = packagesConfigItem.GetFullPath(); var projectPath = packagesConfigItem.ContainingProject.FileName; //RWM: Start by backing up the files. File.Copy(packagesConfigPath, $"{packagesConfigPath}.bak", true); File.Copy(projectPath, $"{projectPath}.bak", true); Logger.Log($"Backup created for {packagesConfigPath}."); //RWM: Load the files. var project = XDocument.Load(projectPath); var packagesConfig = XDocument.Load(packagesConfigPath); //RWM: Get references to the stuff we're gonna get rid of. var oldReferences = project.Root.Descendants().Where(c => c.Name.LocalName == "Reference"); var errors = project.Root.Descendants().Where(c => c.Name.LocalName == "Error"); var targets = project.Root.Descendants().Where(c => c.Name.LocalName == "Import"); foreach (var row in packagesConfig.Root.Elements().ToList()) { //RWM: Create the new PackageReference. packageReferences.Add(new XElement(defaultNs + "PackageReference", new XAttribute("Include", row.Attribute("id").Value), new XAttribute("Version", row.Attribute("version").Value))); //RWM: Remove the old Standard Reference. if (oldReferences != null) { oldReferences.Where(c => c.Attribute("Include") != null).Where(c => c.Attribute("Include").Value.Split(new Char[] { ',' })[0].ToLower() == row.Attribute("id").Value.ToLower()).ToList() .ForEach(c => c.Remove()); } //RWM: Remove any remaining Standard References where the PackageId is in the HintPath. if (oldReferences != null) { oldReferences.Where(c => c.Descendants().Any(d => d.Value.Contains(row.Attribute("id").Value))).ToList() .ForEach(c => c.Remove()); } //RWM: Remove any Error conditions for missing Package Targets. if (errors != null) { errors.Where(c => c.Attribute("Condition") != null).Where(c => c.Attribute("Condition").Value.Contains(row.Attribute("id").Value)).ToList() .ForEach(c => c.Remove()); } //RWM: Remove any Package Targets. if (targets != null) { targets.Where(c => c.Attribute("Project") != null).Where(c => c.Attribute("Project").Value.Contains(row.Attribute("id").Value)).ToList() .ForEach(c => c.Remove()); } } //RWM: Fix up the project file by adding PackageReferences, removing packages.config, and pulling NuGet-added Targets. project.Root.Elements().First(c => c.Name.LocalName == "ItemGroup").AddBeforeSelf(packageReferences); var packageConfigReference = project.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "None" && c.Attribute("Include").Value == "packages.config"); if (packageConfigReference != null) { packageConfigReference.Remove(); } var nugetBuildImports = project.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "Target" && c.Attribute("Name").Value == "EnsureNuGetPackageBuildImports"); if (nugetBuildImports != null && nugetBuildImports.Descendants().Count(c => c.Name.LocalName == "Error") == 0) { nugetBuildImports.Remove(); } //RWM: Upgrade the ToolsVersion so it can't be opened in VS2015 anymore. project.Root.Attribute("ToolsVersion").Value = "15.0"; //RWM: Save the project and delete Packages.config. ProjectHelpers.CheckFileOutOfSourceControl(projectPath); ProjectHelpers.CheckFileOutOfSourceControl(packagesConfigPath); project.Save(projectPath, SaveOptions.None); File.Delete(packagesConfigPath); Logger.Log($"Update complete. Visual Studio will prompt you to reload the project now."); }); } catch (AggregateException agEx) { _dte.StatusBar.Progress(false); Logger.Log($"Update failed. Exceptions:"); foreach (var ex in agEx.InnerExceptions) { Logger.Log($"Message: {ex.Message}{Environment.NewLine}{ex.StackTrace}"); } _dte.StatusBar.Text = "Operation failed. Please see Output Window for details."; _isProcessing = false; } finally { _dte.StatusBar.Progress(false); _dte.StatusBar.Text = "Operation finished. Please see Output Window for details."; _isProcessing = false; } }