From b894d39111a660fa63ddd903637158f4f639ac0e Mon Sep 17 00:00:00 2001 From: Chris Long Date: Fri, 23 Feb 2024 21:42:12 +0000 Subject: [PATCH] fix: unhandled exception when package reference without version First() will throw exception if the Version or Include attributes are not found --- .../ProjectFileCreator.cs | 16 ++++++++--- .../Actions/ProjectFileActionsTests.cs | 27 +++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/CTA.Rules.ProjectFile/ProjectFileCreator.cs b/src/CTA.Rules.ProjectFile/ProjectFileCreator.cs index f6ef7800..ff96a63a 100644 --- a/src/CTA.Rules.ProjectFile/ProjectFileCreator.cs +++ b/src/CTA.Rules.ProjectFile/ProjectFileCreator.cs @@ -291,9 +291,19 @@ private void UpdatePackageReferences() //Select existing packages and deduplicate them by package name: var existingPackages = _projectFileXml.Descendants() .Where(d => d.Name == "PackageReference") - .Select(d => new { Name = d.Attributes("Include").First().Value, Version = d.Attributes("Version").First().Value }) - .GroupBy(d => d.Name).Select(d => d.FirstOrDefault()) - .ToDictionary(p => p.Name, p => p.Version); + .Select(d => new + { + Name = d.Attributes("Include") + .FirstOrDefault()? + .Value ?? "", + Version = d.Attributes("Version") + .FirstOrDefault()? + .Value ?? "" + }) + .GroupBy(d => d.Name) + .Select(d => d.FirstOrDefault()) + .ToDictionary(p => p.Name, + p => p.Version); _packages = _packages.Where(p => existingPackages.Keys?.Contains(p.Key) == false).ToDictionary(d => d.Key, d => d.Value); diff --git a/tst/CTA.Rules.Test/Actions/ProjectFileActionsTests.cs b/tst/CTA.Rules.Test/Actions/ProjectFileActionsTests.cs index 6a372519..935ab448 100644 --- a/tst/CTA.Rules.Test/Actions/ProjectFileActionsTests.cs +++ b/tst/CTA.Rules.Test/Actions/ProjectFileActionsTests.cs @@ -118,6 +118,33 @@ public void ProjectFileCreationHandlesNoExistingPackages() StringAssert.Contains("", result); } + [Test] + public void ProjectFileCreationHandlePackageReferenceNoVersion() + { + const string projectFile = @" + + + netcoreapp3.1 + + + + +"; + + var result = CreateNewFile( + ProjectType.CoreMvc, + new List() { SupportedFrameworks.Net8 }, + new Dictionary() + { + {"Newtonsoft.Json", "2.2.6"} + }, new List(), + newContent: projectFile); + StringAssert.Contains(SupportedFrameworks.Net8, result); + //verify both new and old package reference remain + StringAssert.Contains("", result); + StringAssert.Contains("", result); + } + private string CreateNewFile(ProjectType projectType, List targetVersions, Dictionary packageReferences, List projectReferences, bool isNetCore = false, string newContent="") { ResetProjectFile(newContent: newContent, isNetCore: isNetCore);