diff --git a/src/Tools/dotnet-user-secrets/src/Internal/InitCommand.cs b/src/Tools/dotnet-user-secrets/src/Internal/InitCommand.cs index 5b8b038596..cbbcee8233 100644 --- a/src/Tools/dotnet-user-secrets/src/Internal/InitCommand.cs +++ b/src/Tools/dotnet-user-secrets/src/Internal/InitCommand.cs @@ -76,7 +76,7 @@ namespace Microsoft.Extensions.SecretManager.Tools.Internal var projectPath = ResolveProjectPath(ProjectPath, WorkingDirectory); // Load the project file as XML - var projectDocument = XDocument.Load(projectPath); + var projectDocument = XDocument.Load(projectPath, LoadOptions.PreserveWhitespace); // Accept the `--id` CLI option to the main app string newSecretsId = string.IsNullOrWhiteSpace(OverrideId) @@ -120,19 +120,18 @@ namespace Microsoft.Extensions.SecretManager.Tools.Internal } // Add UserSecretsId element + propertyGroup.Add(" "); propertyGroup.Add(new XElement("UserSecretsId", newSecretsId)); + propertyGroup.Add($"{Environment.NewLine} "); } var settings = new XmlWriterSettings { - Indent = true, OmitXmlDeclaration = true, }; - using (var xw = XmlWriter.Create(projectPath, settings)) - { - projectDocument.Save(xw); - } + using var xw = XmlWriter.Create(projectPath, settings); + projectDocument.Save(xw); context.Reporter.Output(Resources.FormatMessage_SetUserSecretsIdForProject(newSecretsId, projectPath)); } diff --git a/src/Tools/dotnet-user-secrets/test/InitCommandTest.cs b/src/Tools/dotnet-user-secrets/test/InitCommandTest.cs index b6df249c37..acfda466b7 100644 --- a/src/Tools/dotnet-user-secrets/test/InitCommandTest.cs +++ b/src/Tools/dotnet-user-secrets/test/InitCommandTest.cs @@ -3,6 +3,7 @@ using System; using System.IO; +using System.Linq; using System.Text; using System.Xml.Linq; using Microsoft.AspNetCore.Testing; @@ -98,6 +99,22 @@ namespace Microsoft.Extensions.SecretManager.Tools.Tests Assert.Null(projectDocument.Declaration); } + [Fact] + public void DoesNotRemoveBlankLines() + { + var projectDir = _fixture.CreateProject(null); + var projectFile = Path.Combine(projectDir, "TestProject.csproj"); + var projectDocumentWithoutSecret = XDocument.Load(projectFile, LoadOptions.PreserveWhitespace); + var lineCountWithoutSecret = projectDocumentWithoutSecret.ToString().Split(Environment.NewLine).Length; + + new InitCommand(null, null).Execute(MakeCommandContext(), projectDir); + + var projectDocumentWithSecret = XDocument.Load(projectFile, LoadOptions.PreserveWhitespace); + var lineCountWithSecret = projectDocumentWithSecret.ToString().Split(Environment.NewLine).Length; + + Assert.True(lineCountWithSecret == lineCountWithoutSecret + 1); + } + [Fact] public void OverridesIdForProjectWithSecretId() {