diff --git a/src/libraries/Microsoft.PowerFx.Core/Utils/DName.cs b/src/libraries/Microsoft.PowerFx.Core/Utils/DName.cs index 80371eece..bd5cb62b1 100644 --- a/src/libraries/Microsoft.PowerFx.Core/Utils/DName.cs +++ b/src/libraries/Microsoft.PowerFx.Core/Utils/DName.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System; +using System.Text; namespace Microsoft.PowerFx.Core.Utils { @@ -159,11 +160,36 @@ namespace Microsoft.PowerFx.Core.Utils } var fAllSpaces = true; + var fHasSpecialWhiteSpaceCharacters = false; + fModified = false; for (var i = 0; i < strName.Length; i++) { - fAllSpaces = fAllSpaces && (strName[i] == ChSpace); + var fIsSpace = strName[i] == ChSpace; + var fIsWhiteSpace = char.IsWhiteSpace(strName[i]); + fAllSpaces = fAllSpaces && fIsWhiteSpace; + fHasSpecialWhiteSpaceCharacters |= fIsWhiteSpace && !fIsSpace; + } + + if (fHasSpecialWhiteSpaceCharacters) + { + fModified = true; + var builder = new StringBuilder(strName.Length); + + for (var i = 0; i < strName.Length; i++) + { + if (char.IsWhiteSpace(strName[i])) + { + builder.Append(ChSpace); + } + else + { + builder.Append(strName[i]); + } + } + + strName = builder.ToString(); } if (!fAllSpaces) diff --git a/src/tests/Microsoft.PowerFx.Core.Tests/DNameTests.cs b/src/tests/Microsoft.PowerFx.Core.Tests/DNameTests.cs new file mode 100644 index 000000000..520d4e899 --- /dev/null +++ b/src/tests/Microsoft.PowerFx.Core.Tests/DNameTests.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. + +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.PowerFx.Core.Utils; +using Xunit; + +namespace Microsoft.PowerFx.Core.Tests +{ + public sealed class DNameTests + { + [Theory] + [InlineData(" Name ", " Name ", false)] + [InlineData("Name\bAbcd", "Name\bAbcd", false)] + [InlineData("Name\nAbcd", "Name Abcd", true)] + [InlineData(" ", "_ ", true)] + [InlineData(" \t ", "_ ", true)] + public void TestMakeValid(string name, string expected, bool expectedModified) + { + var result = DName.MakeValid(name, out var modified); + Assert.Equal(modified, expectedModified); + Assert.Equal(expected, result); + } + } +}