diff --git a/src/Umbraco.Core/Composing/TypeFinder.cs b/src/Umbraco.Core/Composing/TypeFinder.cs index 5ad1e4358047..394d9480aedb 100644 --- a/src/Umbraco.Core/Composing/TypeFinder.cs +++ b/src/Umbraco.Core/Composing/TypeFinder.cs @@ -35,7 +35,7 @@ private static string[] AssembliesAcceptingLoadExceptions var s = ConfigurationManager.AppSettings[Constants.AppSettings.AssembliesAcceptingLoadExceptions]; return _assembliesAcceptingLoadExceptions = string.IsNullOrWhiteSpace(s) ? Array.Empty() - : s.Split(',').Select(x => x.Trim()).ToArray(); + : s.Split(Constants.CharArrays.Comma).Select(x => x.Trim()).ToArray(); } } diff --git a/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs b/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs index bc76caacee57..e8fea7f27ddb 100644 --- a/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs +++ b/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs @@ -44,7 +44,7 @@ internal static string GetUmbracoMvcAreaNoCache(this IGlobalSettings globalSetti var path = globalSettings.Path; if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518 path = path.Substring(SystemDirectories.Root.Length); - return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower(); + return path.TrimStart(Constants.CharArrays.Tilde).TrimStart(Constants.CharArrays.ForwardSlash).Replace('/', '-').Trim().ToLower(); } } diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs b/src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs index 82cc5928cfec..b3980d236a63 100644 --- a/src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs +++ b/src/Umbraco.Core/Configuration/UmbracoSettings/ContentSectionExtensions.cs @@ -15,7 +15,7 @@ public static bool IsImageFile(this IContentSection contentConfig, string extens { if (contentConfig == null) throw new ArgumentNullException(nameof(contentConfig)); if (extension == null) return false; - extension = extension.TrimStart('.'); + extension = extension.TrimStart(Constants.CharArrays.Period); return contentConfig.ImageFileTypes.InvariantContains(extension); } diff --git a/src/Umbraco.Core/Constants-CharArrays.cs b/src/Umbraco.Core/Constants-CharArrays.cs new file mode 100644 index 000000000000..2f8292b4a431 --- /dev/null +++ b/src/Umbraco.Core/Constants-CharArrays.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Umbraco.Core +{ + public static partial class Constants + { + /// + /// Char Arrays to avoid allocations + /// + public static class CharArrays + { + /// + /// Char array containing only / + /// + public static readonly char[] ForwardSlash = new char[] { '/' }; + + /// + /// Char array containing only \ + /// + public static readonly char[] Backslash = new char[] { '\\' }; + + /// + /// Char array containing only ' + /// + public static readonly char[] SingleQuote = new char[] { '\'' }; + + /// + /// Char array containing only " + /// + public static readonly char[] DoubleQuote = new char[] { '\"' }; + + + /// + /// Char array containing ' " + /// + public static readonly char[] DoubleQuoteSingleQuote = new char[] { '\"', '\'' }; + + /// + /// Char array containing only _ + /// + public static readonly char[] Underscore = new char[] { '_' }; + + /// + /// Char array containing \n \r + /// + public static readonly char[] LineFeedCarriageReturn = new char[] { '\n', '\r' }; + + + /// + /// Char array containing \n + /// + public static readonly char[] LineFeed = new char[] { '\n' }; + + /// + /// Char array containing only , + /// + public static readonly char[] Comma = new char[] { ',' }; + + /// + /// Char array containing only & + /// + public static readonly char[] Ampersand = new char[] { '&' }; + + /// + /// Char array containing only \0 + /// + public static readonly char[] NullTerminator = new char[] { '\0' }; + + /// + /// Char array containing only . + /// + public static readonly char[] Period = new char[] { '.' }; + + /// + /// Char array containing only ~ + /// + public static readonly char[] Tilde = new char[] { '~' }; + /// + /// Char array containing ~ / + /// + public static readonly char[] TildeForwardSlash = new char[] { '~', '/' }; + + /// + /// Char array containing only ? + /// + public static readonly char[] QuestionMark = new char[] { '?' }; + + /// + /// Char array containing ? & + /// + public static readonly char[] QuestionMarkAmpersand = new char[] { '?', '&' }; + + /// + /// Char array containing XML 1.1 whitespace chars + /// + public static readonly char[] XmlWhitespaceChars = new char[] { ' ', '\t', '\r', '\n' }; + + /// + /// Char array containing only the Space char + /// + public static readonly char[] Space = new char[] { ' ' }; + + /// + /// Char array containing only ; + /// + public static readonly char[] Semicolon = new char[] { ';' }; + + /// + /// Char array containing a comma and a space + /// + public static readonly char[] CommaSpace = new char[] { ',', ' ' }; + + /// + /// Char array containing _ - + /// + public static readonly char[] UnderscoreDash = new char[] { '_', '-' }; + + /// + /// Char array containing = + /// + public static readonly char[] EqualsChar = new char[] { '=' }; + + /// + /// Char array containing > + /// + public static readonly char[] GreaterThan = new char[] { '>' }; + + /// + /// Char array containing | + /// + public static readonly char[] VerticalTab = new char[] { '|' }; + } + } +} diff --git a/src/Umbraco.Core/DictionaryExtensions.cs b/src/Umbraco.Core/DictionaryExtensions.cs index d9e998dbd132..88a042dbd5d6 100644 --- a/src/Umbraco.Core/DictionaryExtensions.cs +++ b/src/Umbraco.Core/DictionaryExtensions.cs @@ -253,7 +253,7 @@ public static string ToQueryString(this IDictionary d) { builder.Append(String.Format("{0}={1}&", HttpUtility.UrlEncode(i.Key), i.Value == null ? string.Empty : HttpUtility.UrlEncode(i.Value.ToString()))); } - return builder.ToString().TrimEnd('&'); + return builder.ToString().TrimEnd(Constants.CharArrays.Ampersand); } /// The get entry ignore case. diff --git a/src/Umbraco.Core/GuidUdi.cs b/src/Umbraco.Core/GuidUdi.cs index 93f670cd01b4..3743f6f108f4 100644 --- a/src/Umbraco.Core/GuidUdi.cs +++ b/src/Umbraco.Core/GuidUdi.cs @@ -33,7 +33,7 @@ public GuidUdi(Uri uriValue) : base(uriValue) { Guid guid; - if (Guid.TryParse(uriValue.AbsolutePath.TrimStart('/'), out guid) == false) + if (Guid.TryParse(uriValue.AbsolutePath.TrimStart(Constants.CharArrays.ForwardSlash), out guid) == false) throw new FormatException("URI \"" + uriValue + "\" is not a GUID entity ID."); Guid = guid; diff --git a/src/Umbraco.Core/HttpContextExtensions.cs b/src/Umbraco.Core/HttpContextExtensions.cs index 22eb4d19175a..e9ac1aa861a1 100644 --- a/src/Umbraco.Core/HttpContextExtensions.cs +++ b/src/Umbraco.Core/HttpContextExtensions.cs @@ -50,7 +50,7 @@ public static string GetCurrentRequestIpAddress(this HttpContextBase httpContext if (string.IsNullOrEmpty(ipAddress)) return request.UserHostAddress; - var addresses = ipAddress.Split(','); + var addresses = ipAddress.Split(Constants.CharArrays.Comma); if (addresses.Length != 0) return addresses[0]; diff --git a/src/Umbraco.Core/IO/IOHelper.cs b/src/Umbraco.Core/IO/IOHelper.cs index 53aa5a8179a7..8661f73fb1d4 100644 --- a/src/Umbraco.Core/IO/IOHelper.cs +++ b/src/Umbraco.Core/IO/IOHelper.cs @@ -40,7 +40,7 @@ public static string FindFile(string virtualPath) retval = virtualPath.Replace("~", SystemDirectories.Root); if (virtualPath.StartsWith("/") && virtualPath.StartsWith(SystemDirectories.Root) == false) - retval = SystemDirectories.Root + "/" + virtualPath.TrimStart('/'); + retval = SystemDirectories.Root + "/" + virtualPath.TrimStart(Constants.CharArrays.ForwardSlash); return retval; } @@ -98,11 +98,11 @@ public static string MapPath(string path, bool useHttpContext) if (String.IsNullOrEmpty(path) == false && (path.StartsWith("~") || path.StartsWith(SystemDirectories.Root))) return HostingEnvironment.MapPath(path); else - return HostingEnvironment.MapPath("~/" + path.TrimStart('/')); + return HostingEnvironment.MapPath("~/" + path.TrimStart(Constants.CharArrays.ForwardSlash)); } var root = GetRootDirectorySafe(); - var newPath = path.TrimStart('~', '/').Replace('/', IOHelper.DirSepChar); + var newPath = path.TrimStart(Constants.CharArrays.TildeForwardSlash).Replace('/', IOHelper.DirSepChar); var retval = root + IOHelper.DirSepChar.ToString(CultureInfo.InvariantCulture) + newPath; return retval; @@ -121,7 +121,7 @@ internal static string ReturnPath(string settingsKey, string standardPath, bool if (string.IsNullOrEmpty(retval)) retval = standardPath; - return retval.TrimEnd('/'); + return retval.TrimEnd(Constants.CharArrays.ForwardSlash); } internal static string ReturnPath(string settingsKey, string standardPath) @@ -188,7 +188,7 @@ internal static bool VerifyEditPath(string filePath, IEnumerable validDi internal static bool VerifyFileExtension(string filePath, IEnumerable validFileExtensions) { var ext = Path.GetExtension(filePath); - return ext != null && validFileExtensions.Contains(ext.TrimStart('.')); + return ext != null && validFileExtensions.Contains(ext.TrimStart(Constants.CharArrays.Period)); } public static bool PathStartsWith(string path, string root, char separator) diff --git a/src/Umbraco.Core/IO/PhysicalFileSystem.cs b/src/Umbraco.Core/IO/PhysicalFileSystem.cs index 5a216e8554d4..a833ba43af4f 100644 --- a/src/Umbraco.Core/IO/PhysicalFileSystem.cs +++ b/src/Umbraco.Core/IO/PhysicalFileSystem.cs @@ -33,7 +33,7 @@ public PhysicalFileSystem(string virtualRoot) _rootPath = EnsureDirectorySeparatorChar(IOHelper.MapPath(virtualRoot)).TrimEnd(Path.DirectorySeparatorChar); _rootPathFwd = EnsureUrlSeparatorChar(_rootPath); - _rootUrl = EnsureUrlSeparatorChar(IOHelper.ResolveUrl(virtualRoot)).TrimEnd('/'); + _rootUrl = EnsureUrlSeparatorChar(IOHelper.ResolveUrl(virtualRoot)).TrimEnd(Constants.CharArrays.ForwardSlash); } public PhysicalFileSystem(string rootPath, string rootUrl) @@ -54,7 +54,7 @@ public PhysicalFileSystem(string rootPath, string rootUrl) _rootPath = EnsureDirectorySeparatorChar(rootPath).TrimEnd(Path.DirectorySeparatorChar); _rootPathFwd = EnsureUrlSeparatorChar(_rootPath); - _rootUrl = EnsureUrlSeparatorChar(rootUrl).TrimEnd('/'); + _rootUrl = EnsureUrlSeparatorChar(rootUrl).TrimEnd(Constants.CharArrays.ForwardSlash); } /// @@ -259,12 +259,12 @@ public string GetRelativePath(string fullPathOrUrl) // if it starts with the root URL, strip it and trim the starting slash to make it relative // eg "/Media/1234/img.jpg" => "1234/img.jpg" if (IOHelper.PathStartsWith(path, _rootUrl, '/')) - return path.Substring(_rootUrl.Length).TrimStart('/'); + return path.Substring(_rootUrl.Length).TrimStart(Constants.CharArrays.ForwardSlash); // if it starts with the root path, strip it and trim the starting slash to make it relative // eg "c:/websites/test/root/Media/1234/img.jpg" => "1234/img.jpg" if (IOHelper.PathStartsWith(path, _rootPathFwd, '/')) - return path.Substring(_rootPathFwd.Length).TrimStart('/'); + return path.Substring(_rootPathFwd.Length).TrimStart(Constants.CharArrays.ForwardSlash); // unchanged - what else? return path; @@ -326,7 +326,7 @@ public string GetFullPath(string path) /// All separators are forward-slashes. public string GetUrl(string path) { - path = EnsureUrlSeparatorChar(path).Trim('/'); + path = EnsureUrlSeparatorChar(path).Trim(Constants.CharArrays.ForwardSlash); return _rootUrl + "/" + path; } diff --git a/src/Umbraco.Core/IO/ShadowFileSystem.cs b/src/Umbraco.Core/IO/ShadowFileSystem.cs index 84ff1b428b6f..0e9390d13f32 100644 --- a/src/Umbraco.Core/IO/ShadowFileSystem.cs +++ b/src/Umbraco.Core/IO/ShadowFileSystem.cs @@ -182,7 +182,7 @@ public void AddFile(string path, Stream stream, bool overrideIfExists) if (Nodes.TryGetValue(normPath, out sf) && sf.IsExist && (sf.IsDir || overrideIfExists == false)) throw new InvalidOperationException(string.Format("A file at path '{0}' already exists", path)); - var parts = normPath.Split('/'); + var parts = normPath.Split(Constants.CharArrays.ForwardSlash); for (var i = 0; i < parts.Length - 1; i++) { var dirPath = string.Join("/", parts.Take(i + 1)); @@ -297,7 +297,7 @@ public void AddFile(string path, string physicalPath, bool overrideIfExists = tr if (Nodes.TryGetValue(normPath, out sf) && sf.IsExist && (sf.IsDir || overrideIfExists == false)) throw new InvalidOperationException(string.Format("A file at path '{0}' already exists", path)); - var parts = normPath.Split('/'); + var parts = normPath.Split(Constants.CharArrays.ForwardSlash); for (var i = 0; i < parts.Length - 1; i++) { var dirPath = string.Join("/", parts.Take(i + 1)); diff --git a/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs b/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs index 71faf42dafbd..fb9b8af46dc0 100644 --- a/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs +++ b/src/Umbraco.Core/Migrations/Install/DatabaseBuilder.cs @@ -354,7 +354,7 @@ internal bool IsConnectionStringConfigured(ConnectionStringSettings databaseSett var sqlCeDatabaseExists = false; if (dbIsSqlCe) { - var parts = databaseSettings.ConnectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + var parts = databaseSettings.ConnectionString.Split(Constants.CharArrays.Semicolon, StringSplitOptions.RemoveEmptyEntries); var dataSourcePart = parts.FirstOrDefault(x => x.InvariantStartsWith("Data Source=")); if (dataSourcePart != null) { diff --git a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/PropertyEditorsMigrationBase.cs b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/PropertyEditorsMigrationBase.cs index 605f8a9eeda7..423ba714015e 100644 --- a/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/PropertyEditorsMigrationBase.cs +++ b/src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/PropertyEditorsMigrationBase.cs @@ -30,7 +30,7 @@ internal List GetDataTypes(string editorAlias, bool strict = true) protected int[] ConvertStringValues(string val) { - var splitVals = val.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var splitVals = val.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); var intVals = splitVals .Select(x => int.TryParse(x, out var i) ? i : int.MinValue) diff --git a/src/Umbraco.Core/Models/PathValidationExtensions.cs b/src/Umbraco.Core/Models/PathValidationExtensions.cs index 2db954b316cb..4ade88f62158 100644 --- a/src/Umbraco.Core/Models/PathValidationExtensions.cs +++ b/src/Umbraco.Core/Models/PathValidationExtensions.cs @@ -25,7 +25,7 @@ public static void ValidatePathWithException(this NodeDto entity) if (entity.Path.IsNullOrWhiteSpace()) throw new InvalidDataException($"The content item {entity.NodeId} has an empty path: {entity.Path} with parentID: {entity.ParentId}"); - var pathParts = entity.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var pathParts = entity.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); if (pathParts.Length < 2) { //a path cannot be less than 2 parts, at a minimum it must be root (-1) and it's own id @@ -53,7 +53,7 @@ public static bool ValidatePath(this IUmbracoEntity entity) if (entity.Path.IsNullOrWhiteSpace()) return false; - var pathParts = entity.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var pathParts = entity.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); if (pathParts.Length < 2) { //a path cannot be less than 2 parts, at a minimum it must be root (-1) and it's own id diff --git a/src/Umbraco.Core/Packaging/PackageDataInstallation.cs b/src/Umbraco.Core/Packaging/PackageDataInstallation.cs index 3553e224cb61..4d1f12baaa88 100644 --- a/src/Umbraco.Core/Packaging/PackageDataInstallation.cs +++ b/src/Umbraco.Core/Packaging/PackageDataInstallation.cs @@ -522,7 +522,7 @@ private Dictionary CreateContentTypeFolderStructure(IEnumerable CreateDataTypeFolderStructure(IEnumerable", //take the entire outer xml value ContentNodeId = xml.Element("content")?.AttributeValue("nodeId") ?? string.Empty, ContentLoadChildNodes = xml.Element("content")?.AttributeValue("loadChildNodes") ?? false, - Macros = xml.Element("macros")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), - Templates = xml.Element("templates")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), - Stylesheets = xml.Element("stylesheets")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), - DocumentTypes = xml.Element("documentTypes")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), - Languages = xml.Element("languages")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), - DictionaryItems = xml.Element("dictionaryitems")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), - DataTypes = xml.Element("datatypes")?.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), + Macros = xml.Element("macros")?.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), + Templates = xml.Element("templates")?.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), + Stylesheets = xml.Element("stylesheets")?.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), + DocumentTypes = xml.Element("documentTypes")?.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), + Languages = xml.Element("languages")?.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), + DictionaryItems = xml.Element("dictionaryitems")?.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), + DataTypes = xml.Element("datatypes")?.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).ToList() ?? new List(), Files = xml.Element("files")?.Elements("file").Select(x => x.Value).ToList() ?? new List() }; diff --git a/src/Umbraco.Core/Persistence/DatabaseModelDefinitions/DefinitionFactory.cs b/src/Umbraco.Core/Persistence/DatabaseModelDefinitions/DefinitionFactory.cs index 5925e58afc81..fc3713a3a428 100644 --- a/src/Umbraco.Core/Persistence/DatabaseModelDefinitions/DefinitionFactory.cs +++ b/src/Umbraco.Core/Persistence/DatabaseModelDefinitions/DefinitionFactory.cs @@ -160,7 +160,7 @@ public static IndexDefinition GetIndexDefinition(Type modelType, PropertyInfo pr if (string.IsNullOrEmpty(attribute.ForColumns) == false) { - var columns = attribute.ForColumns.Split(',').Select(p => p.Trim()); + var columns = attribute.ForColumns.Split(Constants.CharArrays.Comma).Select(p => p.Trim()); foreach (var column in columns) { definition.Columns.Add(new IndexColumnDefinition {Name = column, Direction = Direction.Ascending}); diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs index f879fd5224dc..a78a07355444 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentRepositoryBase.cs @@ -514,7 +514,7 @@ public ContentDataIntegrityReport CheckDataIntegrity(ContentDataIntegrityReportO currentParentIds.Add(node.NodeId); // paths parts without the roots - var pathParts = node.Path.Split(',').Where(x => !rootIds.Contains(int.Parse(x))).ToArray(); + var pathParts = node.Path.Split(Constants.CharArrays.Comma).Where(x => !rootIds.Contains(int.Parse(x))).ToArray(); if (!prevParentIds.Contains(node.ParentId)) { diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs index 5bd3638f308c..ed0c28869175 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/ContentTypeRepositoryBase.cs @@ -1318,7 +1318,7 @@ public string GetUniqueAlias(string alias) /// public bool HasContainerInPath(string contentPath) { - var ids = contentPath.Split(',').Select(int.Parse).ToArray(); + var ids = contentPath.Split(Constants.CharArrays.Comma).Select(int.Parse).ToArray(); return HasContainerInPath(ids); } diff --git a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs index c230d9f89478..09d41a49a099 100644 --- a/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs +++ b/src/Umbraco.Core/Persistence/Repositories/Implement/DocumentRepository.cs @@ -894,7 +894,7 @@ public bool IsPathPublished(IContent content) if (content.ParentId == -1) return content.Published; - var ids = content.Path.Split(',').Skip(1).Select(int.Parse); + var ids = content.Path.Split(Constants.CharArrays.Comma).Skip(1).Select(int.Parse); var sql = SqlContext.Sql() .SelectCount(x => x.NodeId) diff --git a/src/Umbraco.Core/Persistence/SqlSyntax/MicrosoftSqlSyntaxProviderBase.cs b/src/Umbraco.Core/Persistence/SqlSyntax/MicrosoftSqlSyntaxProviderBase.cs index be7b2cf06914..7d0659dba888 100644 --- a/src/Umbraco.Core/Persistence/SqlSyntax/MicrosoftSqlSyntaxProviderBase.cs +++ b/src/Umbraco.Core/Persistence/SqlSyntax/MicrosoftSqlSyntaxProviderBase.cs @@ -34,7 +34,7 @@ public override string GetQuotedTableName(string tableName) if (tableName.Contains(".") == false) return $"[{tableName}]"; - var tableNameParts = tableName.Split(new[] { '.' }, 2); + var tableNameParts = tableName.Split(Constants.CharArrays.Period, 2); return $"[{tableNameParts[0]}].[{tableNameParts[1]}]"; } diff --git a/src/Umbraco.Core/Persistence/SqlSyntax/SqlCeSyntaxProvider.cs b/src/Umbraco.Core/Persistence/SqlSyntax/SqlCeSyntaxProvider.cs index ffdeb3bb2a06..d37905f221bd 100644 --- a/src/Umbraco.Core/Persistence/SqlSyntax/SqlCeSyntaxProvider.cs +++ b/src/Umbraco.Core/Persistence/SqlSyntax/SqlCeSyntaxProvider.cs @@ -83,7 +83,7 @@ public override string FormatPrimaryKey(TableDefinition table) string columns = string.IsNullOrEmpty(columnDefinition.PrimaryKeyColumns) ? GetQuotedColumnName(columnDefinition.Name) : string.Join(", ", columnDefinition.PrimaryKeyColumns - .Split(new[]{',', ' '}, StringSplitOptions.RemoveEmptyEntries) + .Split(Constants.CharArrays.CommaSpace, StringSplitOptions.RemoveEmptyEntries) .Select(GetQuotedColumnName)); return string.Format(CreateConstraint, diff --git a/src/Umbraco.Core/Persistence/SqlSyntax/SqlServerSyntaxProvider.cs b/src/Umbraco.Core/Persistence/SqlSyntax/SqlServerSyntaxProvider.cs index b187ed043332..9d33a2169ca1 100644 --- a/src/Umbraco.Core/Persistence/SqlSyntax/SqlServerSyntaxProvider.cs +++ b/src/Umbraco.Core/Persistence/SqlSyntax/SqlServerSyntaxProvider.cs @@ -75,7 +75,7 @@ public ServerVersionInfo(string edition, string instanceName, string productVers private static VersionName MapProductVersion(string productVersion) { - var firstPart = string.IsNullOrWhiteSpace(productVersion) ? "??" : productVersion.Split('.')[0]; + var firstPart = string.IsNullOrWhiteSpace(productVersion) ? "??" : productVersion.Split(Constants.CharArrays.Period)[0]; switch (firstPart) { case "??": diff --git a/src/Umbraco.Core/Persistence/SqlSyntax/SqlSyntaxProviderBase.cs b/src/Umbraco.Core/Persistence/SqlSyntax/SqlSyntaxProviderBase.cs index 8cd9932eaf64..8570c49f6931 100644 --- a/src/Umbraco.Core/Persistence/SqlSyntax/SqlSyntaxProviderBase.cs +++ b/src/Umbraco.Core/Persistence/SqlSyntax/SqlSyntaxProviderBase.cs @@ -403,7 +403,7 @@ public virtual string FormatPrimaryKey(TableDefinition table) var columns = string.IsNullOrEmpty(columnDefinition.PrimaryKeyColumns) ? GetQuotedColumnName(columnDefinition.Name) : string.Join(", ", columnDefinition.PrimaryKeyColumns - .Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries) + .Split(Constants.CharArrays.CommaSpace, StringSplitOptions.RemoveEmptyEntries) .Select(GetQuotedColumnName)); var primaryKeyPart = string.Concat("PRIMARY KEY", columnDefinition.IsIndexed ? " CLUSTERED" : " NONCLUSTERED"); diff --git a/src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs b/src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs index 11502687b7a2..dc2a039bfe81 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueConverters/SliderValueConverter.cs @@ -34,7 +34,7 @@ public override object ConvertIntermediateToObject(IPublishedElement owner, IPub if (IsRangeDataType(propertyType.DataType.Id)) { - var rangeRawValues = source.ToString().Split(','); + var rangeRawValues = source.ToString().Split(Constants.CharArrays.Comma); var minimumAttempt = rangeRawValues[0].TryConvertTo(); var maximumAttempt = rangeRawValues[1].TryConvertTo(); diff --git a/src/Umbraco.Core/Services/ContentServiceExtensions.cs b/src/Umbraco.Core/Services/ContentServiceExtensions.cs index dfe02ba690a4..1d980b036b07 100644 --- a/src/Umbraco.Core/Services/ContentServiceExtensions.cs +++ b/src/Umbraco.Core/Services/ContentServiceExtensions.cs @@ -42,7 +42,7 @@ internal static IEnumerable GetAnchorValuesFromRTEContent(this IContentS var matches = AnchorRegex.Matches(rteContent); foreach (Match match in matches) { - result.Add(match.Value.Split('\"')[1]); + result.Add(match.Value.Split(Constants.CharArrays.DoubleQuote)[1]); } return result; } diff --git a/src/Umbraco.Core/Services/Implement/ContentService.cs b/src/Umbraco.Core/Services/Implement/ContentService.cs index b190e0c69a00..a809b83f23a8 100644 --- a/src/Umbraco.Core/Services/Implement/ContentService.cs +++ b/src/Umbraco.Core/Services/Implement/ContentService.cs @@ -535,7 +535,7 @@ public IEnumerable GetAncestors(IContent content) if (content.Path.IsNullOrWhiteSpace()) return Enumerable.Empty(); var rootId = Constants.System.RootString; - var ids = content.Path.Split(',') + var ids = content.Path.Split(Constants.CharArrays.Comma) .Where(x => x != rootId && x != content.Id.ToString(CultureInfo.InvariantCulture)).Select(int.Parse).ToArray(); if (ids.Any() == false) return new List(); diff --git a/src/Umbraco.Core/Services/Implement/ContentTypeServiceBaseOfTRepositoryTItemTService.cs b/src/Umbraco.Core/Services/Implement/ContentTypeServiceBaseOfTRepositoryTItemTService.cs index 3d4c109bfba9..480501212f4a 100644 --- a/src/Umbraco.Core/Services/Implement/ContentTypeServiceBaseOfTRepositoryTItemTService.cs +++ b/src/Umbraco.Core/Services/Implement/ContentTypeServiceBaseOfTRepositoryTItemTService.cs @@ -879,7 +879,7 @@ public IEnumerable GetContainers(int[] containerIds) public IEnumerable GetContainers(TItem item) { - var ancestorIds = item.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + var ancestorIds = item.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries) .Select(x => { var asInt = x.TryConvertTo(); diff --git a/src/Umbraco.Core/Services/Implement/DataTypeService.cs b/src/Umbraco.Core/Services/Implement/DataTypeService.cs index 5a93fb91b1aa..7102d0eeeb38 100644 --- a/src/Umbraco.Core/Services/Implement/DataTypeService.cs +++ b/src/Umbraco.Core/Services/Implement/DataTypeService.cs @@ -99,7 +99,7 @@ public IEnumerable GetContainers(string name, int level) public IEnumerable GetContainers(IDataType dataType) { - var ancestorIds = dataType.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + var ancestorIds = dataType.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries) .Select(x => { var asInt = x.TryConvertTo(); diff --git a/src/Umbraco.Core/Services/Implement/MediaService.cs b/src/Umbraco.Core/Services/Implement/MediaService.cs index ecd4cccc8d88..ac9c83458ddc 100644 --- a/src/Umbraco.Core/Services/Implement/MediaService.cs +++ b/src/Umbraco.Core/Services/Implement/MediaService.cs @@ -477,7 +477,7 @@ public IEnumerable GetAncestors(IMedia media) if (media.Path.IsNullOrWhiteSpace()) return Enumerable.Empty(); var rootId = Constants.System.RootString; - var ids = media.Path.Split(',') + var ids = media.Path.Split(Constants.CharArrays.Comma) .Where(x => x != rootId && x != media.Id.ToString(CultureInfo.InvariantCulture)) .Select(int.Parse) .ToArray(); diff --git a/src/Umbraco.Core/Services/Implement/NotificationService.cs b/src/Umbraco.Core/Services/Implement/NotificationService.cs index 507da9cec3d3..3c5f91e932b3 100644 --- a/src/Umbraco.Core/Services/Implement/NotificationService.cs +++ b/src/Umbraco.Core/Services/Implement/NotificationService.cs @@ -78,7 +78,7 @@ public void SendNotifications(IUser operatingUser, IEnumerable entitie if (entitiesL.Count == 0) return; //put all entity's paths into a list with the same indices - var paths = entitiesL.Select(x => x.Path.Split(',').Select(int.Parse).ToArray()).ToArray(); + var paths = entitiesL.Select(x => x.Path.Split(Constants.CharArrays.Comma).Select(int.Parse).ToArray()).ToArray(); // lazily get versions var prevVersionDictionary = new Dictionary(); @@ -176,7 +176,7 @@ public IEnumerable GetUserNotifications(IUser user, string path) /// public IEnumerable FilterUserNotificationsByPath(IEnumerable userNotifications, string path) { - var pathParts = path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); + var pathParts = path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); return userNotifications.Where(r => pathParts.InvariantContains(r.EntityId.ToString(CultureInfo.InvariantCulture))).ToList(); } diff --git a/src/Umbraco.Core/Services/Implement/PublicAccessService.cs b/src/Umbraco.Core/Services/Implement/PublicAccessService.cs index ab9ea64292e8..4e3cd960129e 100644 --- a/src/Umbraco.Core/Services/Implement/PublicAccessService.cs +++ b/src/Umbraco.Core/Services/Implement/PublicAccessService.cs @@ -54,7 +54,7 @@ public PublicAccessEntry GetEntryForContent(string contentPath) { //Get all ids in the path for the content item and ensure they all // parse to ints that are not -1. - var ids = contentPath.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + var ids = contentPath.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries) .Select(x => int.TryParse(x, out int val) ? val : -1) .Where(x => x != -1) .ToList(); diff --git a/src/Umbraco.Core/Services/UserServiceExtensions.cs b/src/Umbraco.Core/Services/UserServiceExtensions.cs index c365f1ccc24c..e817d7925ab3 100644 --- a/src/Umbraco.Core/Services/UserServiceExtensions.cs +++ b/src/Umbraco.Core/Services/UserServiceExtensions.cs @@ -10,7 +10,7 @@ public static class UserServiceExtensions { public static EntityPermission GetPermissions(this IUserService userService, IUser user, string path) { - var ids = path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + var ids = path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.TryConvertTo()) .Where(x => x.Success) .Select(x => x.Result) diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index 57ef9c0d42ff..80ef81f36d04 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -41,7 +41,7 @@ static StringExtensions() /// internal static int[] GetIdsFromPathReversed(this string path) { - var nodeIds = path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + var nodeIds = path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.TryConvertTo()) .Where(x => x.Success) .Select(x => x.Result) @@ -256,7 +256,7 @@ internal static string AppendQueryStringToUrl(this string url, params string[] q //remove any prefixed '&' or '?' for (var i = 0; i < queryStrings.Length; i++) { - queryStrings[i] = queryStrings[i].TrimStart('?', '&').TrimEnd('&'); + queryStrings[i] = queryStrings[i].TrimStart(Constants.CharArrays.QuestionMarkAmpersand).TrimEnd(Constants.CharArrays.Ampersand); } var nonEmpty = queryStrings.Where(x => !x.IsNullOrWhiteSpace()).ToArray(); @@ -315,7 +315,7 @@ public static string DecryptWithMachineKey(this string value) if (value == null) return null; - string[] parts = value.Split('\n'); + string[] parts = value.Split(Constants.CharArrays.LineFeed); StringBuilder decryptedValue = new StringBuilder(); @@ -1347,7 +1347,7 @@ public static bool CsvContains(this string csv, string value) { return false; } - var idCheckList = csv.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); + var idCheckList = csv.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); return idCheckList.Contains(value); } @@ -1362,7 +1362,7 @@ public static string ToFriendlyName(this string fileName) fileName = fileName.StripFileExtension(); // underscores and dashes to spaces - fileName = fileName.ReplaceMany(new[] { '_', '-' }, ' '); + fileName = fileName.ReplaceMany(Constants.CharArrays.UnderscoreDash, ' '); // any other conversions ? @@ -1370,7 +1370,7 @@ public static string ToFriendlyName(this string fileName) fileName = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(fileName); // Replace multiple consecutive spaces with a single space - fileName = string.Join(" ", fileName.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); + fileName = string.Join(" ", fileName.Split(Constants.CharArrays.Space, StringSplitOptions.RemoveEmptyEntries)); return fileName; } diff --git a/src/Umbraco.Core/StringUdi.cs b/src/Umbraco.Core/StringUdi.cs index 7b3239959937..77c55e6692d9 100644 --- a/src/Umbraco.Core/StringUdi.cs +++ b/src/Umbraco.Core/StringUdi.cs @@ -33,7 +33,7 @@ public StringUdi(string entityType, string id) public StringUdi(Uri uriValue) : base(uriValue) { - Id = Uri.UnescapeDataString(uriValue.AbsolutePath.TrimStart('/')); + Id = Uri.UnescapeDataString(uriValue.AbsolutePath.TrimStart(Constants.CharArrays.ForwardSlash)); } private static string EscapeUriString(string s) @@ -46,7 +46,7 @@ private static string EscapeUriString(string s) // we want to preserve the / and the unreserved // so... - return string.Join("/", s.Split('/').Select(Uri.EscapeDataString)); + return string.Join("/", s.Split(Constants.CharArrays.ForwardSlash).Select(Uri.EscapeDataString)); } /// diff --git a/src/Umbraco.Core/Strings/Css/StylesheetRule.cs b/src/Umbraco.Core/Strings/Css/StylesheetRule.cs index 6f9190625081..2c84e9adc5e0 100644 --- a/src/Umbraco.Core/Strings/Css/StylesheetRule.cs +++ b/src/Umbraco.Core/Strings/Css/StylesheetRule.cs @@ -28,7 +28,7 @@ public override string ToString() { // since we already have a string builder in play here, we'll append to it the "hard" way // instead of using string interpolation (for increased performance) - foreach (var style in Styles.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (var style in Styles.Split(Constants.CharArrays.Semicolon, StringSplitOptions.RemoveEmptyEntries)) { sb.Append("\t").Append(style.StripNewLines().Trim()).Append(";").Append(Environment.NewLine); } diff --git a/src/Umbraco.Core/Strings/Diff.cs b/src/Umbraco.Core/Strings/Diff.cs index 6cd4985ead00..9aeeb487eff0 100644 --- a/src/Umbraco.Core/Strings/Diff.cs +++ b/src/Umbraco.Core/Strings/Diff.cs @@ -232,7 +232,7 @@ private static int[] DiffCodes(string aText, IDictionary h, bool trimSpace, bool // strip off all cr, only use lf as text line separator. aText = aText.Replace("\r", ""); - var lines = aText.Split('\n'); + var lines = aText.Split(Constants.CharArrays.LineFeed); var codes = new int[lines.Length]; diff --git a/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs b/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs index 95b08c8377fd..52af734f1c47 100644 --- a/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs +++ b/src/Umbraco.Core/Sync/ApplicationUrlHelper.cs @@ -38,7 +38,7 @@ internal static string GetApplicationUrl(ILogger logger, IGlobalSettings globalS umbracoApplicationUrl = ApplicationUrlProvider?.Invoke(request); if (string.IsNullOrWhiteSpace(umbracoApplicationUrl) == false) { - umbracoApplicationUrl = umbracoApplicationUrl.TrimEnd('/'); + umbracoApplicationUrl = umbracoApplicationUrl.TrimEnd(Constants.CharArrays.ForwardSlash); logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: {UmbracoAppUrl} (provider)", umbracoApplicationUrl); return umbracoApplicationUrl; } @@ -61,7 +61,7 @@ internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, IL var url = settings.WebRouting.UmbracoApplicationUrl; if (url.IsNullOrWhiteSpace() == false) { - var umbracoApplicationUrl = url.TrimEnd('/'); + var umbracoApplicationUrl = url.TrimEnd(Constants.CharArrays.ForwardSlash); logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: {UmbracoAppUrl} (using web.routing/@umbracoApplicationUrl)", umbracoApplicationUrl); return umbracoApplicationUrl; } @@ -75,7 +75,7 @@ internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, IL url = serverRegistrar.GetCurrentServerUmbracoApplicationUrl(); if (url.IsNullOrWhiteSpace() == false) { - var umbracoApplicationUrl = url.TrimEnd('/'); + var umbracoApplicationUrl = url.TrimEnd(Constants.CharArrays.ForwardSlash); logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: {UmbracoAppUrl} (IServerRegistrar)", umbracoApplicationUrl); return umbracoApplicationUrl; } @@ -100,7 +100,7 @@ public static string GetApplicationUrlFromCurrentRequest(HttpRequestBase request var ssl = globalSettings.UseHttps ? "s" : ""; // force, whatever the first request var url = "http" + ssl + "://" + request.ServerVariables["SERVER_NAME"] + port + IOHelper.ResolveUrl(SystemDirectories.Umbraco); - return url.TrimEnd('/'); + return url.TrimEnd(Constants.CharArrays.ForwardSlash); } } } diff --git a/src/Umbraco.Core/Udi.cs b/src/Umbraco.Core/Udi.cs index b11ce250adae..4fafbc0aeb0d 100644 --- a/src/Umbraco.Core/Udi.cs +++ b/src/Umbraco.Core/Udi.cs @@ -171,7 +171,7 @@ private static bool ParseInternal(string s, bool tryParse, bool knownTypes, out throw new FormatException(string.Format("Unknown entity type \"{0}\".", entityType)); } - var path = uri.AbsolutePath.TrimStart('/'); + var path = uri.AbsolutePath.TrimStart(Constants.CharArrays.ForwardSlash); if (udiType == UdiType.GuidUdi) { diff --git a/src/Umbraco.Core/UdiGetterExtensions.cs b/src/Umbraco.Core/UdiGetterExtensions.cs index 5a5ccf5574ea..4eba1858a600 100644 --- a/src/Umbraco.Core/UdiGetterExtensions.cs +++ b/src/Umbraco.Core/UdiGetterExtensions.cs @@ -154,7 +154,7 @@ public static GuidUdi GetUdi(this IMember entity) public static StringUdi GetUdi(this Stylesheet entity) { if (entity == null) throw new ArgumentNullException("entity"); - return new StringUdi(Constants.UdiEntityType.Stylesheet, entity.Path.TrimStart('/')).EnsureClosed(); + return new StringUdi(Constants.UdiEntityType.Stylesheet, entity.Path.TrimStart(Constants.CharArrays.ForwardSlash)).EnsureClosed(); } /// @@ -165,7 +165,7 @@ public static StringUdi GetUdi(this Stylesheet entity) public static StringUdi GetUdi(this Script entity) { if (entity == null) throw new ArgumentNullException("entity"); - return new StringUdi(Constants.UdiEntityType.Script, entity.Path.TrimStart('/')).EnsureClosed(); + return new StringUdi(Constants.UdiEntityType.Script, entity.Path.TrimStart(Constants.CharArrays.ForwardSlash)).EnsureClosed(); } /// @@ -204,7 +204,7 @@ public static StringUdi GetUdi(this IPartialView entity) ? Constants.UdiEntityType.PartialViewMacro : Constants.UdiEntityType.PartialView; - return new StringUdi(entityType, entity.Path.TrimStart('/')).EnsureClosed(); + return new StringUdi(entityType, entity.Path.TrimStart(Constants.CharArrays.ForwardSlash)).EnsureClosed(); } /// diff --git a/src/Umbraco.Core/UdiRange.cs b/src/Umbraco.Core/UdiRange.cs index b70cf43d1885..857e818ce68b 100644 --- a/src/Umbraco.Core/UdiRange.cs +++ b/src/Umbraco.Core/UdiRange.cs @@ -70,7 +70,7 @@ public static UdiRange Parse(string s) } var udiUri = uri.Query == string.Empty ? uri : new UriBuilder(uri) { Query = string.Empty }.Uri; - return new UdiRange(Udi.Create(udiUri), uri.Query.TrimStart('?')); + return new UdiRange(Udi.Create(udiUri), uri.Query.TrimStart(Constants.CharArrays.QuestionMark)); } public override string ToString() diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 39fd115d62bb..8a9398459e83 100755 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -128,6 +128,7 @@ --> + diff --git a/src/Umbraco.Core/UriExtensions.cs b/src/Umbraco.Core/UriExtensions.cs index 1198b26e0fcb..60d9cd6ead44 100644 --- a/src/Umbraco.Core/UriExtensions.cs +++ b/src/Umbraco.Core/UriExtensions.cs @@ -43,8 +43,8 @@ internal static bool IsBackOfficeRequest(this Uri url, string applicationPath, I { applicationPath = applicationPath ?? string.Empty; - var fullUrlPath = url.AbsolutePath.TrimStart(new[] {'/'}); - var appPath = applicationPath.TrimStart(new[] {'/'}); + var fullUrlPath = url.AbsolutePath.TrimStart(Constants.CharArrays.ForwardSlash); + var appPath = applicationPath.TrimStart(Constants.CharArrays.ForwardSlash); var urlPath = fullUrlPath.TrimStart(appPath).EnsureStartsWith('/'); //check if this is in the umbraco back office @@ -93,7 +93,7 @@ internal static bool IsBackOfficeRequest(this Uri url, string applicationPath, I // Umbraco/MYPLUGINAREA/MYCONTROLLERNAME/{action}/{id} // so if the path contains at a minimum 3 parts: Umbraco + MYPLUGINAREA + MYCONTROLLERNAME then we will have to assume it is a // plugin controller for the front-end. - if (urlPath.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries).Length >= 3) + if (urlPath.Split(Constants.CharArrays.ForwardSlash, StringSplitOptions.RemoveEmptyEntries).Length >= 3) { return false; } diff --git a/src/Umbraco.Core/Xml/XmlHelper.cs b/src/Umbraco.Core/Xml/XmlHelper.cs index d6461ec8c6cf..f070e08d4f85 100644 --- a/src/Umbraco.Core/Xml/XmlHelper.cs +++ b/src/Umbraco.Core/Xml/XmlHelper.cs @@ -53,7 +53,7 @@ public static void SetAttribute(XmlDocument xml, XmlNode n, string name, string public static bool IsXmlWhitespace(string s) { // as per xml 1.1 specs - anything else is significant whitespace - s = s.Trim(' ', '\t', '\r', '\n'); + s = s.Trim(Constants.CharArrays.XmlWhitespaceChars); return s.Length == 0; } diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs index 7ef8112d11c1..e59900bdc471 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Building/TextBuilder.cs @@ -446,7 +446,7 @@ internal void WriteClrType(StringBuilder sb, string type) { WriteNonGenericClrType(sb, type.Substring(0, p)); sb.Append("<"); - var args = type.Substring(p + 1).TrimEnd('>').Split(','); // fixme will NOT work with nested generic types + var args = type.Substring(p + 1).TrimEnd(Umbraco.Core.Constants.CharArrays.GreaterThan).Split(Umbraco.Core.Constants.CharArrays.Comma); // fixme will NOT work with nested generic types for (var i = 0; i < args.Length; i++) { if (i > 0) sb.Append(", "); diff --git a/src/Umbraco.Web/Cache/DistributedCacheBinder.cs b/src/Umbraco.Web/Cache/DistributedCacheBinder.cs index 92ed7de881c7..5f8d77f3b27c 100644 --- a/src/Umbraco.Web/Cache/DistributedCacheBinder.cs +++ b/src/Umbraco.Web/Cache/DistributedCacheBinder.cs @@ -39,7 +39,6 @@ internal static MethodInfo FindHandler(IEventDefinition eventDefinition) private static readonly Lazy CandidateHandlers = new Lazy(() => { - var underscore = new[] { '_' }; return typeof(DistributedCacheBinder) .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) @@ -47,7 +46,7 @@ internal static MethodInfo FindHandler(IEventDefinition eventDefinition) { if (x.Name.Contains("_") == false) return null; - var parts = x.Name.Split(underscore, StringSplitOptions.RemoveEmptyEntries).Length; + var parts = x.Name.Split(Constants.CharArrays.Underscore, StringSplitOptions.RemoveEmptyEntries).Length; if (parts != 2) return null; var parameters = x.GetParameters(); diff --git a/src/Umbraco.Web/Editors/BackOfficeController.cs b/src/Umbraco.Web/Editors/BackOfficeController.cs index 18740d41fc60..458c76b3aeda 100644 --- a/src/Umbraco.Web/Editors/BackOfficeController.cs +++ b/src/Umbraco.Web/Editors/BackOfficeController.cs @@ -125,7 +125,7 @@ public async Task VerifyInvite(string invite) return RedirectToAction("Default"); } - var parts = Server.UrlDecode(invite).Split('|'); + var parts = Server.UrlDecode(invite).Split(Constants.CharArrays.VerticalTab); if (parts.Length != 2) { diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index 7cb940d88b0a..dd4dd6768107 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -333,8 +333,8 @@ internal Dictionary GetServerVariables() "umbracoSettings", new Dictionary { {"umbracoPath", _globalSettings.Path}, - {"mediaPath", IOHelper.ResolveUrl(SystemDirectories.Media).TrimEnd('/')}, - {"appPluginsPath", IOHelper.ResolveUrl(SystemDirectories.AppPlugins).TrimEnd('/')}, + {"mediaPath", IOHelper.ResolveUrl(SystemDirectories.Media).TrimEnd(Constants.CharArrays.ForwardSlash)}, + {"appPluginsPath", IOHelper.ResolveUrl(SystemDirectories.AppPlugins).TrimEnd(Constants.CharArrays.ForwardSlash)}, { "imageFileTypes", string.Join(",", Current.Configs.Settings().Content.ImageFileTypes) @@ -353,7 +353,7 @@ internal Dictionary GetServerVariables() }, {"keepUserLoggedIn", Current.Configs.Settings().Security.KeepUserLoggedIn}, {"usernameIsEmail", Current.Configs.Settings().Security.UsernameIsEmail}, - {"cssPath", IOHelper.ResolveUrl(SystemDirectories.Css).TrimEnd('/')}, + {"cssPath", IOHelper.ResolveUrl(SystemDirectories.Css).TrimEnd(Constants.CharArrays.ForwardSlash)}, {"allowPasswordReset", Current.Configs.Settings().Security.AllowPasswordReset}, {"loginBackgroundImage", Current.Configs.Settings().Content.LoginBackgroundImage}, {"loginLogoImage", Current.Configs.Settings().Content.LoginLogoImage }, diff --git a/src/Umbraco.Web/Editors/Binders/ContentModelBinderHelper.cs b/src/Umbraco.Web/Editors/Binders/ContentModelBinderHelper.cs index a017ae5afb75..e0d39b5f65ab 100644 --- a/src/Umbraco.Web/Editors/Binders/ContentModelBinderHelper.cs +++ b/src/Umbraco.Web/Editors/Binders/ContentModelBinderHelper.cs @@ -29,7 +29,7 @@ public static TModelSave BindModelFromMultipartRequest(HttpActionCon { //The name that has been assigned in JS has 2 or more parts. The second part indicates the property id // for which the file belongs, the remaining parts are just metadata that can be used by the property editor. - var parts = file.Headers.ContentDisposition.Name.Trim('\"').Split('_'); + var parts = file.Headers.ContentDisposition.Name.Trim(Constants.CharArrays.DoubleQuote).Split(Constants.CharArrays.Underscore); if (parts.Length < 2) { var response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest); @@ -64,7 +64,7 @@ public static TModelSave BindModelFromMultipartRequest(HttpActionCon // TODO: anything after 4 parts we can put in metadata - var fileName = file.Headers.ContentDisposition.FileName.Trim('\"'); + var fileName = file.Headers.ContentDisposition.FileName.Trim(Constants.CharArrays.DoubleQuote); model.UploadedFiles.Add(new ContentPropertyFile { diff --git a/src/Umbraco.Web/Editors/CodeFileController.cs b/src/Umbraco.Web/Editors/CodeFileController.cs index 0e1c4b3e607e..409cded78136 100644 --- a/src/Umbraco.Web/Editors/CodeFileController.cs +++ b/src/Umbraco.Web/Editors/CodeFileController.cs @@ -23,6 +23,7 @@ using Umbraco.Web.Trees; using Stylesheet = Umbraco.Core.Models.Stylesheet; using StylesheetRule = Umbraco.Web.Models.ContentEditing.StylesheetRule; +using CharArrays = Umbraco.Core.Constants.CharArrays; namespace Umbraco.Web.Editors { @@ -277,7 +278,7 @@ public CodeFileDisplay GetScaffold(string type, string id, string snippetName = if (id != Core.Constants.System.RootString) { - codeFileDisplay.VirtualPath += id.TrimStart("/").EnsureEndsWith("/"); + codeFileDisplay.VirtualPath += id.TrimStart(CharArrays.ForwardSlash).EnsureEndsWith("/"); //if it's not new then it will have a path, otherwise it won't codeFileDisplay.Path = Url.GetTreePathFromFilePath(id); } @@ -473,7 +474,7 @@ public string PostInterpolateStylesheetRules(StylesheetData data) data.Content = StylesheetHelper.ReplaceRule(data.Content, rule.Name, null); } - data.Content = data.Content.TrimEnd('\n', '\r'); + data.Content = data.Content.TrimEnd(CharArrays.LineFeedCarriageReturn); // now add all the posted rules if (data.Rules != null && data.Rules.Any()) diff --git a/src/Umbraco.Web/Editors/ContentTypeController.cs b/src/Umbraco.Web/Editors/ContentTypeController.cs index d426cb1f562e..1803fa735c6c 100644 --- a/src/Umbraco.Web/Editors/ContentTypeController.cs +++ b/src/Umbraco.Web/Editors/ContentTypeController.cs @@ -629,7 +629,7 @@ public async Task Upload() var model = new ContentTypeImportModel(); var file = result.FileData[0]; - var fileName = file.Headers.ContentDisposition.FileName.Trim('\"'); + var fileName = file.Headers.ContentDisposition.FileName.Trim(Constants.CharArrays.DoubleQuote); var ext = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower(); var destFileName = root + "\\" + fileName; diff --git a/src/Umbraco.Web/Editors/EntityController.cs b/src/Umbraco.Web/Editors/EntityController.cs index 65d930590678..fe78b29123d1 100644 --- a/src/Umbraco.Web/Editors/EntityController.cs +++ b/src/Umbraco.Web/Editors/EntityController.cs @@ -174,7 +174,7 @@ public IEnumerable GetPath(int id, UmbracoEntityTypes type) { var foundContent = GetResultForId(id, type); - return foundContent.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); + return foundContent.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); } /// @@ -187,7 +187,7 @@ public IEnumerable GetPath(Guid id, UmbracoEntityTypes type) { var foundContent = GetResultForKey(id, type); - return foundContent.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); + return foundContent.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); } /// @@ -315,7 +315,7 @@ private string ParseXPathQuery(string query, int id) getPath: nodeid => { var ent = Services.EntityService.Get(nodeid); - return ent.Path.Split(',').Reverse(); + return ent.Path.Split(Constants.CharArrays.Comma).Reverse(); }, publishedContentExists: i => Umbraco.Content(i) != null); } @@ -802,7 +802,7 @@ private IEnumerable GetResultForAncestors(int id, UmbracoEntityType { // TODO: Need to check for Object types that support hierarchic here, some might not. - var ids = Services.EntityService.Get(id).Path.Split(',').Select(int.Parse).Distinct().ToArray(); + var ids = Services.EntityService.Get(id).Path.Split(Constants.CharArrays.Comma).Select(int.Parse).Distinct().ToArray(); var ignoreUserStartNodes = IsDataTypeIgnoringUserStartNodes(queryStrings?.GetValue("dataTypeId")); if (ignoreUserStartNodes == false) @@ -1114,7 +1114,7 @@ private IEnumerable ExecutePostFilter(IEnumerable entities, string post { if (postFilter.IsNullOrWhiteSpace()) return entities; - var postFilterConditions = postFilter.Split('&'); + var postFilterConditions = postFilter.Split(Constants.CharArrays.Ampersand); foreach (var postFilterCondition in postFilterConditions) { @@ -1131,9 +1131,7 @@ private IEnumerable ExecutePostFilter(IEnumerable entities, string post return entities; } - private static QueryCondition BuildQueryCondition(string postFilter) - { - var postFilterParts = postFilter.Split(new[] + private static readonly string[] _postFilterSplitStrings = new[] { "=", "==", @@ -1143,7 +1141,10 @@ private static QueryCondition BuildQueryCondition(string postFilter) "<", ">=", "<=" - }, 2, StringSplitOptions.RemoveEmptyEntries); + }; + private static QueryCondition BuildQueryCondition(string postFilter) + { + var postFilterParts = postFilter.Split(_postFilterSplitStrings, 2, StringSplitOptions.RemoveEmptyEntries); if (postFilterParts.Length != 2) { diff --git a/src/Umbraco.Web/Editors/MacrosController.cs b/src/Umbraco.Web/Editors/MacrosController.cs index 38103400d98b..ec54cfdc042e 100644 --- a/src/Umbraco.Web/Editors/MacrosController.cs +++ b/src/Umbraco.Web/Editors/MacrosController.cs @@ -399,7 +399,7 @@ private IEnumerable FindPartialViewFilesInFolder(string orgPath, string files.AddRange( fileInfo.Select(file => - prefixVirtualPath.TrimEnd('/') + "/" + (path.Replace(orgPath, string.Empty).Trim('/') + "/" + file.Name).Trim('/'))); + prefixVirtualPath.TrimEnd(Constants.CharArrays.ForwardSlash) + "/" + (path.Replace(orgPath, string.Empty).Trim(Constants.CharArrays.ForwardSlash) + "/" + file.Name).Trim(Constants.CharArrays.ForwardSlash))); return files; } diff --git a/src/Umbraco.Web/Editors/MediaController.cs b/src/Umbraco.Web/Editors/MediaController.cs index dfe6939552a7..5fd59d0c9fc2 100644 --- a/src/Umbraco.Web/Editors/MediaController.cs +++ b/src/Umbraco.Web/Editors/MediaController.cs @@ -645,7 +645,7 @@ public async Task PostAddFile() if (result.FormData.ContainsKey("path")) { - var folders = result.FormData["path"].Split('/'); + var folders = result.FormData["path"].Split(Constants.CharArrays.ForwardSlash); for (int i = 0; i < folders.Length - 1; i++) { @@ -694,7 +694,7 @@ public async Task PostAddFile() //get the files foreach (var file in result.FileData) { - var fileName = file.Headers.ContentDisposition.FileName.Trim(new[] { '\"' }).TrimEnd(); + var fileName = file.Headers.ContentDisposition.FileName.Trim(Constants.CharArrays.DoubleQuote).TrimEnd(); var safeFileName = fileName.ToSafeFileName(); var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower(); diff --git a/src/Umbraco.Web/Editors/PackageInstallController.cs b/src/Umbraco.Web/Editors/PackageInstallController.cs index 103049873488..1d8f02dbf9bd 100644 --- a/src/Umbraco.Web/Editors/PackageInstallController.cs +++ b/src/Umbraco.Web/Editors/PackageInstallController.cs @@ -24,7 +24,7 @@ using Umbraco.Web.WebApi.Filters; using File = System.IO.File; using Notification = Umbraco.Web.Models.ContentEditing.Notification; - +using CharArrays = Umbraco.Core.Constants.CharArrays; namespace Umbraco.Web.Editors { /// @@ -151,7 +151,7 @@ public async Task UploadLocalPackage() //get the files foreach (var file in result.FileData) { - var fileName = file.Headers.ContentDisposition.FileName.Trim('\"'); + var fileName = file.Headers.ContentDisposition.FileName.Trim(CharArrays.DoubleQuote); var ext = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower(); if (ext.InvariantEquals("zip") || ext.InvariantEquals("umb")) diff --git a/src/Umbraco.Web/Editors/TinyMceController.cs b/src/Umbraco.Web/Editors/TinyMceController.cs index c6c1acd0481b..1d292c64fdac 100644 --- a/src/Umbraco.Web/Editors/TinyMceController.cs +++ b/src/Umbraco.Web/Editors/TinyMceController.cs @@ -74,7 +74,7 @@ public async Task UploadImage() // Really we should only have one file per request to this endpoint var file = result.FileData[0]; - var fileName = file.Headers.ContentDisposition.FileName.Trim(new[] { '\"' }).TrimEnd(); + var fileName = file.Headers.ContentDisposition.FileName.Trim(Constants.CharArrays.DoubleQuote).TrimEnd(); var safeFileName = fileName.ToSafeFileName(); var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower(); diff --git a/src/Umbraco.Web/Editors/TourController.cs b/src/Umbraco.Web/Editors/TourController.cs index 8991bcdd6a28..943d5674a278 100644 --- a/src/Umbraco.Web/Editors/TourController.cs +++ b/src/Umbraco.Web/Editors/TourController.cs @@ -10,6 +10,7 @@ using Umbraco.Web.Models; using Umbraco.Web.Mvc; using Umbraco.Web.Tour; +using CharArrays = Umbraco.Core.Constants.CharArrays; namespace Umbraco.Web.Editors { @@ -56,7 +57,7 @@ public IEnumerable GetTours() { foreach (var plugin in Directory.EnumerateDirectories(appPlugins)) { - var pluginName = Path.GetFileName(plugin.TrimEnd('\\')); + var pluginName = Path.GetFileName(plugin.TrimEnd(CharArrays.Backslash)); var pluginFilters = _filters.Where(x => x.PluginName != null && x.PluginName.IsMatch(pluginName)) .ToList(); @@ -138,7 +139,7 @@ public IEnumerable GetToursForDoctype(string doctypeAlias) { return false; } - var contentTypes = x.ContentType.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(ct => ct.Trim()); + var contentTypes = x.ContentType.Split(CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).Select(ct => ct.Trim()); return contentTypes.Intersect(doctypeAliasWithCompositions).Any(); }); } diff --git a/src/Umbraco.Web/Editors/UsersController.cs b/src/Umbraco.Web/Editors/UsersController.cs index b022e6f27a71..3f2920381937 100644 --- a/src/Umbraco.Web/Editors/UsersController.cs +++ b/src/Umbraco.Web/Editors/UsersController.cs @@ -103,7 +103,7 @@ internal static async Task PostSetAvatarInternal(HttpReques //get the file info var file = result.FileData[0]; - var fileName = file.Headers.ContentDisposition.FileName.Trim(new[] { '\"' }).TrimEnd(); + var fileName = file.Headers.ContentDisposition.FileName.Trim(Constants.CharArrays.DoubleQuote).TrimEnd(); var safeFileName = fileName.ToSafeFileName(); var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower(); diff --git a/src/Umbraco.Web/FormDataCollectionExtensions.cs b/src/Umbraco.Web/FormDataCollectionExtensions.cs index 52f86dcc5918..aabf13ac9bec 100644 --- a/src/Umbraco.Web/FormDataCollectionExtensions.cs +++ b/src/Umbraco.Web/FormDataCollectionExtensions.cs @@ -27,7 +27,7 @@ public static string ToQueryString(this FormDataCollection items, params string[ { builder.Append(string.Format("{0}={1}&", i.Key, i.Value)); } - return builder.ToString().TrimEnd('&'); + return builder.ToString().TrimEnd(Constants.CharArrays.Ampersand); } /// diff --git a/src/Umbraco.Web/HttpCookieExtensions.cs b/src/Umbraco.Web/HttpCookieExtensions.cs index ebb77bd4a490..d9294c7ff08d 100644 --- a/src/Umbraco.Web/HttpCookieExtensions.cs +++ b/src/Umbraco.Web/HttpCookieExtensions.cs @@ -39,10 +39,10 @@ public static string GetCookieValue(this HttpRequestHeaders requestHeaders, stri if (cookiesHeaderValue == null) return null; - var cookieCollection = cookiesHeaderValue.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + var cookieCollection = cookiesHeaderValue.Split(Constants.CharArrays.Semicolon, StringSplitOptions.RemoveEmptyEntries); foreach (var cookieNameValue in cookieCollection) { - var parts = cookieNameValue.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); + var parts = cookieNameValue.Split(Constants.CharArrays.EqualsChar, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) continue; if (parts[0].Trim().Equals(cookieName, StringComparison.InvariantCultureIgnoreCase)) return parts[1].Trim(); diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index b4fd8c0d86f2..54ce6408554e 100755 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -381,7 +381,7 @@ private string ParseAttribute(IDictionary pageElements, string attributeValue) if (attributeValue.StartsWith("[") == false) return attributeValue; - var tokens = attributeValue.Split(',').Select(x => x.Trim()).ToArray(); + var tokens = attributeValue.Split(Constants.CharArrays.Comma).Select(x => x.Trim()).ToArray(); // ensure we only process valid input ie each token must be [?x] and not eg a json array // like [1,2,3] which we don't want to parse - however the last one can be a literal, so diff --git a/src/Umbraco.Web/Macros/PublishedContentHashtableConverter.cs b/src/Umbraco.Web/Macros/PublishedContentHashtableConverter.cs index 3bbc4a793bd2..b9f4650e36a1 100644 --- a/src/Umbraco.Web/Macros/PublishedContentHashtableConverter.cs +++ b/src/Umbraco.Web/Macros/PublishedContentHashtableConverter.cs @@ -100,7 +100,7 @@ private void PopulatePageData(int pageId, Elements.Add("createDate", createDate); Elements.Add("updateDate", updateDate); Elements.Add("path", path); - Elements.Add("splitpath", path.Split(',')); + Elements.Add("splitpath", path.Split(Constants.CharArrays.Comma)); } /// diff --git a/src/Umbraco.Web/Media/Exif/ExifPropertyFactory.cs b/src/Umbraco.Web/Media/Exif/ExifPropertyFactory.cs index 68769eb1f3a5..4373025eb923 100644 --- a/src/Umbraco.Web/Media/Exif/ExifPropertyFactory.cs +++ b/src/Umbraco.Web/Media/Exif/ExifPropertyFactory.cs @@ -1,5 +1,6 @@ using System; using System.Text; +using Umbraco.Core; namespace Umbraco.Web.Media.Exif { @@ -44,7 +45,7 @@ public static ExifProperty Get(ushort tag, ushort type, uint count, byte[] value return new ExifDateTime(ExifTag.DateTime, ExifBitConverter.ToDateTime(value)); else if (tag == 0x9c9b || tag == 0x9c9c || // Windows tags tag == 0x9c9d || tag == 0x9c9e || tag == 0x9c9f) - return new WindowsByteString(etag, Encoding.Unicode.GetString(value).TrimEnd('\0')); + return new WindowsByteString(etag, Encoding.Unicode.GetString(value).TrimEnd(Constants.CharArrays.NullTerminator)); } else if (ifd == IFD.EXIF) { @@ -75,7 +76,7 @@ public static ExifProperty Get(ushort tag, ushort type, uint count, byte[] value hasenc = false; } - string val = (hasenc ? enc.GetString(value, 8, value.Length - 8) : enc.GetString(value)).Trim('\0'); + string val = (hasenc ? enc.GetString(value, 8, value.Length - 8) : enc.GetString(value)).Trim(Constants.CharArrays.NullTerminator); return new ExifEncodedString(ExifTag.UserComment, val, enc); } diff --git a/src/Umbraco.Web/Media/Exif/MathEx.cs b/src/Umbraco.Web/Media/Exif/MathEx.cs index 94cbccfbda8d..7489c21878fc 100644 --- a/src/Umbraco.Web/Media/Exif/MathEx.cs +++ b/src/Umbraco.Web/Media/Exif/MathEx.cs @@ -1,6 +1,6 @@ using System; using System.Text; - +using Umbraco.Core; namespace Umbraco.Web.Media.Exif { /// @@ -694,7 +694,7 @@ private static Fraction32 FromString(string s) if (s == null) throw new ArgumentNullException("s"); - string[] sa = s.Split('/'); + string[] sa = s.Split(Constants.CharArrays.ForwardSlash); int numerator = 1; int denominator = 1; @@ -1322,7 +1322,7 @@ private static UFraction32 FromString(string s) if (s == null) throw new ArgumentNullException("s"); - string[] sa = s.Split('/'); + string[] sa = s.Split(Constants.CharArrays.ForwardSlash); uint numerator = 1; uint denominator = 1; diff --git a/src/Umbraco.Web/Media/UploadAutoFillProperties.cs b/src/Umbraco.Web/Media/UploadAutoFillProperties.cs index 01ced179d60c..60de03b4507c 100644 --- a/src/Umbraco.Web/Media/UploadAutoFillProperties.cs +++ b/src/Umbraco.Web/Media/UploadAutoFillProperties.cs @@ -67,7 +67,7 @@ public void Populate(IContentBase content, IImagingAutoFillUploadField autoFillC { using (var filestream = _mediaFileSystem.OpenFile(filepath)) { - var extension = (Path.GetExtension(filepath) ?? "").TrimStart('.'); + var extension = (Path.GetExtension(filepath) ?? "").TrimStart(Constants.CharArrays.Period); var size = _contentSection.IsImageFile(extension) ? (Size?)ImageHelper.GetDimensions(filestream) : null; SetProperties(content, autoFillConfig, size, filestream.Length, extension, culture, segment); } @@ -101,7 +101,7 @@ public void Populate(IContentBase content, IImagingAutoFillUploadField autoFillC } else { - var extension = (Path.GetExtension(filepath) ?? "").TrimStart('.'); + var extension = (Path.GetExtension(filepath) ?? "").TrimStart(Constants.CharArrays.Period); var size = _contentSection.IsImageFile(extension) ? (Size?)ImageHelper.GetDimensions(filestream) : null; SetProperties(content, autoFillConfig, size, filestream.Length, extension, culture, segment); } diff --git a/src/Umbraco.Web/ModelStateExtensions.cs b/src/Umbraco.Web/ModelStateExtensions.cs index d03472ef5e38..e224a6122b8e 100644 --- a/src/Umbraco.Web/ModelStateExtensions.cs +++ b/src/Umbraco.Web/ModelStateExtensions.cs @@ -107,7 +107,7 @@ internal static void AddVariantValidationError(this System.Web.Http.ModelBinding //Add any variant specific errors here var variantErrors = modelState.Keys .Where(key => key.StartsWith("_Properties.")) //only choose _Properties errors - .Select(x => x.Split('.')) //split into parts + .Select(x => x.Split(Constants.CharArrays.Period)) //split into parts .Where(x => x.Length >= 4 && !x[2].IsNullOrWhiteSpace() && !x[3].IsNullOrWhiteSpace()) .Select(x => (culture: x[2], segment: x[3])) //if the culture is marked "invariant" than return the default language, this is because we can only edit invariant properties on the default language @@ -145,7 +145,7 @@ internal static void AddVariantValidationError(this System.Web.Http.ModelBinding .Select(x => { // Format "_" - var cs = x.Split(new[] { '_' }); + var cs = x.Split(Constants.CharArrays.Underscore); return (culture: cs[0], segment: cs[1]); }) .Where(x => !x.culture.IsNullOrWhiteSpace()) diff --git a/src/Umbraco.Web/Models/Mapping/ContentMapDefinition.cs b/src/Umbraco.Web/Models/Mapping/ContentMapDefinition.cs index 983172f8e192..16465914cb1d 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentMapDefinition.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentMapDefinition.cs @@ -253,7 +253,7 @@ private bool DetermineIsChildOfListView(IContent source, MapperContext context) if (parent == null) return false; - var pathParts = parent.Path.Split(',').Select(x => int.TryParse(x, out var i) ? i : 0).ToList(); + var pathParts = parent.Path.Split(Constants.CharArrays.Comma).Select(x => int.TryParse(x, out var i) ? i : 0).ToList(); // reduce the path parts so we exclude top level content items that // are higher up than a user's start nodes diff --git a/src/Umbraco.Web/Models/Mapping/ContentTypeMapDefinition.cs b/src/Umbraco.Web/Models/Mapping/ContentTypeMapDefinition.cs index f67a5df56cad..70285187942e 100644 --- a/src/Umbraco.Web/Models/Mapping/ContentTypeMapDefinition.cs +++ b/src/Umbraco.Web/Models/Mapping/ContentTypeMapDefinition.cs @@ -561,7 +561,7 @@ private IEnumerable MapLockedCompositions(IContentTypeComposition source return Enumerable.Empty(); var aliases = new List(); - var ancestorIds = parent.Path.Split(',').Select(int.Parse); + var ancestorIds = parent.Path.Split(Constants.CharArrays.Comma).Select(int.Parse); // loop through all content types and return ordered aliases of ancestors var allContentTypes = _contentTypeService.GetAll().ToArray(); foreach (var ancestorId in ancestorIds) diff --git a/src/Umbraco.Web/Models/Trees/TreeNode.cs b/src/Umbraco.Web/Models/Trees/TreeNode.cs index 10684b519eb8..fd7ef0d19df0 100644 --- a/src/Umbraco.Web/Models/Trees/TreeNode.cs +++ b/src/Umbraco.Web/Models/Trees/TreeNode.cs @@ -110,7 +110,7 @@ public string IconFilePath //absolute path with or without tilde if (Icon.StartsWith("~") || Icon.StartsWith("/")) - return IOHelper.ResolveUrl("~" + Icon.TrimStart('~')); + return IOHelper.ResolveUrl("~" + Icon.TrimStart(Constants.CharArrays.Tilde)); //legacy icon path return string.Format("{0}images/umbraco/{1}", Current.Configs.Global().Path.EnsureEndsWith("/"), Icon); diff --git a/src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs b/src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs index 5f81ced3f0fc..712cb8fb7212 100644 --- a/src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs +++ b/src/Umbraco.Web/Mvc/MemberAuthorizeAttribute.cs @@ -6,7 +6,7 @@ using Umbraco.Web.Security; using Umbraco.Core.Composing; using Current = Umbraco.Web.Composing.Current; - +using CharArrays = Umbraco.Core.Constants.CharArrays; namespace Umbraco.Web.Mvc { /// @@ -40,7 +40,7 @@ protected override bool AuthorizeCore(HttpContextBase httpContext) AllowType = ""; var members = new List(); - foreach (var s in AllowMembers.Split(',')) + foreach (var s in AllowMembers.Split(CharArrays.Comma)) { if (int.TryParse(s, out var id)) { @@ -49,7 +49,7 @@ protected override bool AuthorizeCore(HttpContextBase httpContext) } var helper = Current.Factory.GetInstance(); - return helper.IsMemberAuthorized(AllowType.Split(','), AllowGroup.Split(','), members); + return helper.IsMemberAuthorized(AllowType.Split(CharArrays.Comma), AllowGroup.Split(CharArrays.Comma), members); } diff --git a/src/Umbraco.Web/Mvc/RenderRouteHandler.cs b/src/Umbraco.Web/Mvc/RenderRouteHandler.cs index 28f2449187ab..b15a00a33ecd 100644 --- a/src/Umbraco.Web/Mvc/RenderRouteHandler.cs +++ b/src/Umbraco.Web/Mvc/RenderRouteHandler.cs @@ -253,7 +253,7 @@ internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext reques //the template Alias should always be already saved with a safe name. //if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed // with the action name attribute. - var templateName = request.TemplateAlias.Split('.')[0].ToSafeAlias(); + var templateName = request.TemplateAlias.Split(Umbraco.Core.Constants.CharArrays.Period)[0].ToSafeAlias(); def.ActionName = templateName; } diff --git a/src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs index fa8060bd159e..493fc96f7694 100644 --- a/src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs @@ -45,7 +45,7 @@ public IEnumerable GetReferences(object value) if (string.IsNullOrEmpty(asString)) yield break; - foreach (var udiStr in asString.Split(',')) + foreach (var udiStr in asString.Split(Constants.CharArrays.Comma)) { if (Udi.TryParse(udiStr, out var udi)) yield return new UmbracoEntityReference(udi); diff --git a/src/Umbraco.Web/PropertyEditors/MultiNodeTreePickerPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MultiNodeTreePickerPropertyEditor.cs index fd7f735e68a5..1630e706db39 100644 --- a/src/Umbraco.Web/PropertyEditors/MultiNodeTreePickerPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MultiNodeTreePickerPropertyEditor.cs @@ -34,7 +34,7 @@ public IEnumerable GetReferences(object value) { var asString = value == null ? string.Empty : value is string str ? str : value.ToString(); - var udiPaths = asString.Split(','); + var udiPaths = asString.Split(Constants.CharArrays.Comma); foreach (var udiPath in udiPaths) if (Udi.TryParse(udiPath, out var udi)) yield return new UmbracoEntityReference(udi); diff --git a/src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs index fd7e8694a385..6066bf7dfb7b 100644 --- a/src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/TagsPropertyEditor.cs @@ -57,7 +57,7 @@ public override object FromEditor(ContentPropertyData editorValue, object curren if (string.IsNullOrWhiteSpace(value) == false) { - return value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); + return value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); } return null; diff --git a/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs b/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs index 8d7bd2988917..b92141db9ca0 100644 --- a/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs +++ b/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs @@ -29,7 +29,7 @@ public IEnumerable Validate(object value, string valueType, ob yield break; } - var fileNames = selectedFiles?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var fileNames = selectedFiles?.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); if (fileNames == null || !fileNames.Any()) yield break; diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs index a56630d7c5c0..3f15eca0ccf6 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/MediaPickerValueConverter.cs @@ -57,7 +57,7 @@ public override object ConvertSourceToIntermediate(IPublishedElement owner, IPub if (source == null) return null; var nodeIds = source.ToString() - .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) + .Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries) .Select(Udi.Parse) .ToArray(); return nodeIds; diff --git a/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs b/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs index 47f879729529..9f92d6493e8f 100644 --- a/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs +++ b/src/Umbraco.Web/PropertyEditors/ValueConverters/MultiNodeTreePickerValueConverter.cs @@ -54,7 +54,7 @@ public override object ConvertSourceToIntermediate(IPublishedElement owner, IPub if (propertyType.EditorAlias.Equals(Constants.PropertyEditors.Aliases.MultiNodeTreePicker)) { var nodeIds = source.ToString() - .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) + .Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries) .Select(Udi.Parse) .ToArray(); return nodeIds; diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs index a0224f90ead9..dbb427422d30 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentCache.cs @@ -79,7 +79,7 @@ private IPublishedContent GetByRouteInternal(bool preview, string route, bool? h var pos = route.IndexOf('/'); var path = pos == 0 ? route : route.Substring(pos); var startNodeId = pos == 0 ? 0 : int.Parse(route.Substring(0, pos)); - var parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + var parts = path.Split(Constants.CharArrays.ForwardSlash, StringSplitOptions.RemoveEmptyEntries); IPublishedContent content; diff --git a/src/Umbraco.Web/RoutableDocumentFilter.cs b/src/Umbraco.Web/RoutableDocumentFilter.cs index 507a40e471fa..6096429db69f 100644 --- a/src/Umbraco.Web/RoutableDocumentFilter.cs +++ b/src/Umbraco.Web/RoutableDocumentFilter.cs @@ -53,7 +53,7 @@ public bool IsDocumentRequest(HttpContextBase httpContext, Uri uri) // use uri.AbsolutePath, not path, 'cos path has been lowercased httpContext.RewritePath(uri.AbsolutePath.Substring(0, asmxPos + 5), // filePath uri.AbsolutePath.Substring(asmxPos + 5), // pathInfo - uri.Query.TrimStart('?')); + uri.Query.TrimStart(Constants.CharArrays.QuestionMark)); maybeDoc = false; } @@ -101,7 +101,7 @@ internal bool IsReservedPathOrUrl(string url) // add URLs and paths to a new list var newReservedList = new HashSet(); foreach (var reservedUrlTrimmed in reservedUrlsCache - .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) + .Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim().ToLowerInvariant()) .Where(x => x.IsNullOrWhiteSpace() == false) .Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/")) @@ -110,7 +110,7 @@ internal bool IsReservedPathOrUrl(string url) newReservedList.Add(reservedUrlTrimmed); } - foreach (var reservedPathTrimmed in NormalizePaths(reservedPathsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))) + foreach (var reservedPathTrimmed in NormalizePaths(reservedPathsCache.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries))) { newReservedList.Add(reservedPathTrimmed); } @@ -127,7 +127,7 @@ internal bool IsReservedPathOrUrl(string url) //The URL should be cleaned up before checking: // * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/' // * We shouldn't be comparing the query at all - var pathPart = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant(); + var pathPart = url.Split(Constants.CharArrays.QuestionMark, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant(); if (pathPart.Contains(".") == false) { pathPart = pathPart.EnsureEndsWith('/'); diff --git a/src/Umbraco.Web/Routing/AliasUrlProvider.cs b/src/Umbraco.Web/Routing/AliasUrlProvider.cs index b3b56a18e719..12828f06d724 100644 --- a/src/Umbraco.Web/Routing/AliasUrlProvider.cs +++ b/src/Umbraco.Web/Routing/AliasUrlProvider.cs @@ -84,7 +84,7 @@ public IEnumerable GetOtherUrls(UmbracoContext umbracoContext, int id, yield break; var umbracoUrlName = node.Value(Constants.Conventions.Content.UrlAlias); - var aliases = umbracoUrlName?.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var aliases = umbracoUrlName?.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); if (aliases == null || aliases.Any() == false) yield break; @@ -111,7 +111,7 @@ public IEnumerable GetOtherUrls(UmbracoContext umbracoContext, int id, ? node.Value(Constants.Conventions.Content.UrlAlias, culture: domainUri.Culture.Name) : node.Value(Constants.Conventions.Content.UrlAlias); - var aliases = umbracoUrlName?.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries); + var aliases = umbracoUrlName?.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries); if (aliases == null || aliases.Any() == false) continue; @@ -132,8 +132,8 @@ public IEnumerable GetOtherUrls(UmbracoContext umbracoContext, int id, string CombinePaths(string path1, string path2) { - string path = path1.TrimEnd('/') + path2; - return path == "/" ? path : path.TrimEnd('/'); + string path = path1.TrimEnd(Constants.CharArrays.ForwardSlash) + path2; + return path == "/" ? path : path.TrimEnd(Constants.CharArrays.ForwardSlash); } #endregion diff --git a/src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs b/src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs index 9340c6c6de0e..0ee5f3d42d33 100644 --- a/src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs +++ b/src/Umbraco.Web/Routing/ContentFinderByUrlAlias.cs @@ -64,7 +64,7 @@ private static IPublishedContent FindContentByAlias(IPublishedContentCache cache const string propertyAlias = Constants.Conventions.Content.UrlAlias; - var test1 = alias.TrimStart('/') + ","; + var test1 = alias.TrimStart(Constants.CharArrays.ForwardSlash) + ","; var test2 = ",/" + test1; // test2 is ",/alias," test1 = "," + test1; // test1 is ",alias," diff --git a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs index 291ac67882bd..f26f05c36c97 100644 --- a/src/Umbraco.Web/Routing/DefaultUrlProvider.cs +++ b/src/Umbraco.Web/Routing/DefaultUrlProvider.cs @@ -5,6 +5,7 @@ using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; +using Umbraco.Core; namespace Umbraco.Web.Routing { @@ -172,8 +173,8 @@ Uri AssembleUrl(DomainAndUri domainUri, string path, Uri current, UrlMode mode) string CombinePaths(string path1, string path2) { - string path = path1.TrimEnd('/') + path2; - return path == "/" ? path : path.TrimEnd('/'); + string path = path1.TrimEnd(Constants.CharArrays.ForwardSlash) + path2; + return path == "/" ? path : path.TrimEnd(Constants.CharArrays.ForwardSlash); } #endregion diff --git a/src/Umbraco.Web/Routing/DomainUtilities.cs b/src/Umbraco.Web/Routing/DomainUtilities.cs index fb0c56b28d1c..9f5ab32acbe5 100644 --- a/src/Umbraco.Web/Routing/DomainUtilities.cs +++ b/src/Umbraco.Web/Routing/DomainUtilities.cs @@ -327,7 +327,7 @@ internal static Domain FindDomainInPath(IEnumerable domains, string path { var stopNodeId = rootNodeId ?? -1; - return path.Split(',') + return path.Split(Constants.CharArrays.Comma) .Reverse() .Select(int.Parse) .TakeWhile(id => id != stopNodeId) @@ -348,7 +348,7 @@ internal static Domain FindWildcardDomainInPath(IEnumerable domains, str { var stopNodeId = rootNodeId ?? -1; - return path.Split(',') + return path.Split(Constants.CharArrays.Comma) .Reverse() .Select(int.Parse) .TakeWhile(id => id != stopNodeId) diff --git a/src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs b/src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs index 38ecb09b2bb2..9fefeeb84358 100644 --- a/src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs +++ b/src/Umbraco.Web/Routing/NotFoundHandlerHelper.cs @@ -96,7 +96,7 @@ internal class NotFoundHandlerHelper getPath: nodeid => { var ent = entityService.Get(nodeid); - return ent.Path.Split(',').Reverse(); + return ent.Path.Split(Constants.CharArrays.Comma).Reverse(); }, publishedContentExists: i => publishedContentQuery.Content(i) != null); diff --git a/src/Umbraco.Web/Routing/UrlProviderExtensions.cs b/src/Umbraco.Web/Routing/UrlProviderExtensions.cs index afa0bc96ccd7..3bd9d985a616 100644 --- a/src/Umbraco.Web/Routing/UrlProviderExtensions.cs +++ b/src/Umbraco.Web/Routing/UrlProviderExtensions.cs @@ -164,7 +164,7 @@ private static UrlInfo HandleCouldNotGetUrl(IContent content, string culture, IC private static bool DetectCollision(IContent content, string url, string culture, UmbracoContext umbracoContext, IPublishedRouter publishedRouter, ILocalizedTextService textService, out UrlInfo urlInfo) { // test for collisions on the 'main' URL - var uri = new Uri(url.TrimEnd('/'), UriKind.RelativeOrAbsolute); + var uri = new Uri(url.TrimEnd(Constants.CharArrays.ForwardSlash), UriKind.RelativeOrAbsolute); if (uri.IsAbsoluteUri == false) uri = uri.MakeAbsolute(umbracoContext.CleanedUmbracoUrl); uri = UriUtility.UriToUmbraco(uri); var pcr = publishedRouter.CreateRequest(umbracoContext, uri); diff --git a/src/Umbraco.Web/Scheduling/KeepAlive.cs b/src/Umbraco.Web/Scheduling/KeepAlive.cs index 9a22c59566db..2dcf9a24a77d 100644 --- a/src/Umbraco.Web/Scheduling/KeepAlive.cs +++ b/src/Umbraco.Web/Scheduling/KeepAlive.cs @@ -62,7 +62,7 @@ public override async Task PerformRunAsync(CancellationToken token) return true; // repeat } - keepAlivePingUrl = keepAlivePingUrl.Replace("{umbracoApplicationUrl}", umbracoAppUrl.TrimEnd('/')); + keepAlivePingUrl = keepAlivePingUrl.Replace("{umbracoApplicationUrl}", umbracoAppUrl.TrimEnd(Constants.CharArrays.ForwardSlash)); } var request = new HttpRequestMessage(HttpMethod.Get, keepAlivePingUrl); diff --git a/src/Umbraco.Web/Search/UmbracoTreeSearcher.cs b/src/Umbraco.Web/Search/UmbracoTreeSearcher.cs index a22e2a6f6ab6..410b654e3277 100644 --- a/src/Umbraco.Web/Search/UmbracoTreeSearcher.cs +++ b/src/Umbraco.Web/Search/UmbracoTreeSearcher.cs @@ -196,7 +196,7 @@ private bool BuildQuery(StringBuilder sb, string query, string searchFrom, List< if (surroundedByQuotes) { //strip quotes, escape string, the replace again - query = query.Trim('\"', '\''); + query = query.Trim(Constants.CharArrays.DoubleQuoteSingleQuote); query = Lucene.Net.QueryParsers.QueryParser.Escape(query); @@ -230,7 +230,7 @@ private bool BuildQuery(StringBuilder sb, string query, string searchFrom, List< } else { - var trimmed = query.Trim(new[] { '\"', '\'' }); + var trimmed = query.Trim(Constants.CharArrays.DoubleQuoteSingleQuote); //nothing to search if (searchFrom.IsNullOrWhiteSpace() && trimmed.IsNullOrWhiteSpace()) @@ -243,7 +243,7 @@ private bool BuildQuery(StringBuilder sb, string query, string searchFrom, List< { query = Lucene.Net.QueryParsers.QueryParser.Escape(query); - var querywords = query.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + var querywords = query.Split(Constants.CharArrays.Space, StringSplitOptions.RemoveEmptyEntries); sb.Append("+("); diff --git a/src/Umbraco.Web/Services/DashboardService.cs b/src/Umbraco.Web/Services/DashboardService.cs index 794c6fa67111..19944a9cb1fe 100644 --- a/src/Umbraco.Web/Services/DashboardService.cs +++ b/src/Umbraco.Web/Services/DashboardService.cs @@ -86,7 +86,7 @@ private bool CheckUserAccessByRules(IUser user, ISectionService sectionService, if (grantBySectionRules.Length > 0) { var allowedSections = sectionService.GetAllowedSections(user.Id).Select(x => x.Alias).ToArray(); - var wantedSections = grantBySectionRules.SelectMany(g => g.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); + var wantedSections = grantBySectionRules.SelectMany(g => g.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries)).ToArray(); if (wantedSections.Intersect(allowedSections).Any()) hasAccess = true; @@ -97,7 +97,7 @@ private bool CheckUserAccessByRules(IUser user, ISectionService sectionService, if (hasAccess == false && grantRules.Any()) { assignedUserGroups = user.Groups.Select(x => x.Alias).ToArray(); - var wantedUserGroups = grantRules.SelectMany(g => g.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); + var wantedUserGroups = grantRules.SelectMany(g => g.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries)).ToArray(); if (wantedUserGroups.Intersect(assignedUserGroups).Any()) hasAccess = true; @@ -111,7 +111,7 @@ private bool CheckUserAccessByRules(IUser user, ISectionService sectionService, // check if this item has any deny arguments, if so check if the user is in one of the denied user groups, if so they will // be denied to see it no matter what assignedUserGroups = assignedUserGroups ?? user.Groups.Select(x => x.Alias).ToArray(); - var deniedUserGroups = denyRules.SelectMany(g => g.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).ToArray(); + var deniedUserGroups = denyRules.SelectMany(g => g.Value.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries)).ToArray(); if (deniedUserGroups.Intersect(assignedUserGroups).Any()) hasAccess = false; diff --git a/src/Umbraco.Web/Trees/ContentTreeController.cs b/src/Umbraco.Web/Trees/ContentTreeController.cs index 663af436438b..087b25b9a7e2 100644 --- a/src/Umbraco.Web/Trees/ContentTreeController.cs +++ b/src/Umbraco.Web/Trees/ContentTreeController.cs @@ -175,7 +175,7 @@ protected override MenuItemCollection PerformGetMenuForNode(string id, FormDataC var nodeMenu = GetAllNodeMenuItems(item); //if the content node is in the recycle bin, don't have a default menu, just show the regular menu - if (item.Path.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains(RecycleBinId.ToInvariantString())) + if (item.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).Contains(RecycleBinId.ToInvariantString())) { nodeMenu.DefaultMenuAlias = null; nodeMenu = GetNodeMenuItemsForDeletedContent(item); diff --git a/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs b/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs index 95de72b7bf59..e9c34608a2e9 100644 --- a/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs +++ b/src/Umbraco.Web/Trees/ContentTreeControllerBase.cs @@ -369,7 +369,7 @@ protected bool ShouldRenderChildrenOfContainer(IEntitySlim e) if (startNodes.Any(x => { - var pathParts = x.Path.Split(','); + var pathParts = x.Path.Split(Constants.CharArrays.Comma); return pathParts.Contains(e.Id.ToInvariantString()); })) { diff --git a/src/Umbraco.Web/Trees/FileSystemTreeController.cs b/src/Umbraco.Web/Trees/FileSystemTreeController.cs index 6e21c8114fd2..cad59619df4d 100644 --- a/src/Umbraco.Web/Trees/FileSystemTreeController.cs +++ b/src/Umbraco.Web/Trees/FileSystemTreeController.cs @@ -62,7 +62,7 @@ protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection if (Extensions.Contains("*")) return true; - return extension != null && Extensions.Contains(extension.Trim('.'), StringComparer.InvariantCultureIgnoreCase); + return extension != null && Extensions.Contains(extension.Trim(Constants.CharArrays.Period), StringComparer.InvariantCultureIgnoreCase); }); foreach (var file in files) diff --git a/src/Umbraco.Web/Trees/MediaTreeController.cs b/src/Umbraco.Web/Trees/MediaTreeController.cs index df44a809c936..aacd285823eb 100644 --- a/src/Umbraco.Web/Trees/MediaTreeController.cs +++ b/src/Umbraco.Web/Trees/MediaTreeController.cs @@ -125,7 +125,7 @@ protected override MenuItemCollection PerformGetMenuForNode(string id, FormDataC //if the media item is in the recycle bin, we don't have a default menu and we need to show a limited menu - if (item.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Contains(RecycleBinId.ToInvariantString())) + if (item.Path.Split(Constants.CharArrays.Comma, StringSplitOptions.RemoveEmptyEntries).Contains(RecycleBinId.ToInvariantString())) { menu.Items.Add(Services.TextService, opensDialog: true); menu.Items.Add(Services.TextService, opensDialog: true); diff --git a/src/Umbraco.Web/Trees/UrlHelperExtensions.cs b/src/Umbraco.Web/Trees/UrlHelperExtensions.cs index 3221023ca2d6..864d43583c97 100644 --- a/src/Umbraco.Web/Trees/UrlHelperExtensions.cs +++ b/src/Umbraco.Web/Trees/UrlHelperExtensions.cs @@ -49,7 +49,7 @@ internal static string GetTreePathFromFilePath(this UrlHelper urlHelper, string var sb = new StringBuilder("-1"); //split the virtual path and iterate through it - var pathPaths = virtualPath.Split('/'); + var pathPaths = virtualPath.Split(Constants.CharArrays.ForwardSlash); for (var p = 0; p < pathPaths.Length; p++) { diff --git a/src/Umbraco.Web/UmbracoInjectedModule.cs b/src/Umbraco.Web/UmbracoInjectedModule.cs index 92fee22983f6..cc130a7b567e 100644 --- a/src/Umbraco.Web/UmbracoInjectedModule.cs +++ b/src/Umbraco.Web/UmbracoInjectedModule.cs @@ -249,7 +249,7 @@ private bool EnsureHasContent(UmbracoContext context, HttpContextBase httpContex private void RewriteToBackOfficeHandler(HttpContextBase context) { // GlobalSettings.Path has already been through IOHelper.ResolveUrl() so it begins with / and vdir (if any) - var rewritePath = _globalSettings.Path.TrimEnd('/') + "/Default"; + var rewritePath = _globalSettings.Path.TrimEnd(Constants.CharArrays.ForwardSlash) + "/Default"; // rewrite the path to the path of the handler (i.e. /umbraco/RenderMvc) context.RewritePath(rewritePath, "", "", false); @@ -279,10 +279,10 @@ private void RewriteToUmbracoHandler(HttpContextBase context, PublishedRequest p // rewritten URL, but this is not what we want! // read: http://forums.iis.net/t/1146511.aspx - var query = pcr.Uri.Query.TrimStart('?'); + var query = pcr.Uri.Query.TrimStart(Constants.CharArrays.QuestionMark); // GlobalSettings.Path has already been through IOHelper.ResolveUrl() so it begins with / and vdir (if any) - var rewritePath = _globalSettings.Path.TrimEnd('/') + "/RenderMvc"; + var rewritePath = _globalSettings.Path.TrimEnd(Constants.CharArrays.ForwardSlash) + "/RenderMvc"; // rewrite the path to the path of the handler (i.e. /umbraco/RenderMvc) context.RewritePath(rewritePath, "", query, false); diff --git a/src/Umbraco.Web/UriUtility.cs b/src/Umbraco.Web/UriUtility.cs index ae0b00191762..730a50bd6196 100644 --- a/src/Umbraco.Web/UriUtility.cs +++ b/src/Umbraco.Web/UriUtility.cs @@ -42,7 +42,7 @@ internal static void ResetAppDomainAppVirtualPath() public static string ToAbsolute(string url) { //return ResolveUrl(url); - url = url.TrimStart('~'); + url = url.TrimStart(Constants.CharArrays.Tilde); return _appPathPrefix + url; } @@ -102,7 +102,7 @@ public static Uri UriToUmbraco(Uri uri) } if (path != "/") { - path = path.TrimEnd('/'); + path = path.TrimEnd(Constants.CharArrays.ForwardSlash); } //if any part of the path contains .aspx, replace it with nothing. @@ -216,7 +216,7 @@ public static string TrimPathEndSlash(string uri) var pos = Math.Min(pos1, pos2); var path = pos > 0 ? uri.Substring(0, pos) : uri; - path = path.TrimEnd('/'); + path = path.TrimEnd(Constants.CharArrays.ForwardSlash); if (pos > 0) path += uri.Substring(pos); diff --git a/src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForContentAttribute.cs b/src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForContentAttribute.cs index 28f09b46b700..550b4dcdf101 100644 --- a/src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForContentAttribute.cs +++ b/src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForContentAttribute.cs @@ -69,7 +69,7 @@ public override void OnActionExecuting(HttpActionContext actionContext) int nodeId; if (_nodeId.HasValue == false) { - var parts = _paramName.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries); + var parts = _paramName.Split(Constants.CharArrays.Period, StringSplitOptions.RemoveEmptyEntries); if (actionContext.ActionArguments[parts[0]] == null) { diff --git a/src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForMediaAttribute.cs b/src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForMediaAttribute.cs index 60e2889fd54d..3c60f43be038 100644 --- a/src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForMediaAttribute.cs +++ b/src/Umbraco.Web/WebApi/Filters/EnsureUserPermissionForMediaAttribute.cs @@ -91,7 +91,7 @@ public override void OnActionExecuting(HttpActionContext actionContext) int nodeId; if (_nodeId.HasValue == false) { - var parts = _paramName.Split(new [] { '.' }, StringSplitOptions.RemoveEmptyEntries); + var parts = _paramName.Split(Constants.CharArrays.Period, StringSplitOptions.RemoveEmptyEntries); if (actionContext.ActionArguments[parts[0]] == null) { diff --git a/src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs b/src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs index bc1e9a43180d..65f34b05fb04 100644 --- a/src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs +++ b/src/Umbraco.Web/WebApi/MemberAuthorizeAttribute.cs @@ -38,7 +38,7 @@ protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionConte AllowType = ""; var members = new List(); - foreach (var s in AllowMembers.Split(',')) + foreach (var s in AllowMembers.Split(Constants.CharArrays.Comma)) { if (int.TryParse(s, out var id)) { @@ -47,7 +47,7 @@ protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionConte } var helper = Current.Factory.GetInstance(); - return helper.IsMemberAuthorized(AllowType.Split(','), AllowGroup.Split(','), members); + return helper.IsMemberAuthorized(AllowType.Split(Constants.CharArrays.Comma), AllowGroup.Split(Constants.CharArrays.Comma), members); } }